Assorted spelling fixes.
[wine] / dlls / shell32 / shellpath.c
1 /*
2  * Path Functions
3  *
4  * Copyright 1998, 1999, 2000 Juergen Schmied
5  * Copyright 2004 Juan Lang
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  * NOTES:
22  *
23  * Many of these functions are in SHLWAPI.DLL also
24  *
25  */
26
27 #define COBJMACROS
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <stdio.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include "wine/debug.h"
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winnls.h"
40 #include "winreg.h"
41 #include "wingdi.h"
42 #include "winuser.h"
43
44 #include "shlobj.h"
45 #include "shtypes.h"
46 #include "shresdef.h"
47 #include "shell32_main.h"
48 #include "undocshell.h"
49 #include "pidl.h"
50 #include "wine/unicode.h"
51 #include "shlwapi.h"
52 #include "xdg.h"
53 #include "sddl.h"
54 #include "knownfolders.h"
55 #include "initguid.h"
56 #include "shobjidl.h"
57
58 WINE_DEFAULT_DEBUG_CHANNEL(shell);
59
60 static const BOOL is_win64 = sizeof(void *) > sizeof(int);
61
62 /*
63         ########## Combining and Constructing paths ##########
64 */
65
66 /*************************************************************************
67  * PathAppend           [SHELL32.36]
68  */
69 BOOL WINAPI PathAppendAW(
70         LPVOID lpszPath1,
71         LPCVOID lpszPath2)
72 {
73         if (SHELL_OsIsUnicode())
74           return PathAppendW(lpszPath1, lpszPath2);
75         return PathAppendA(lpszPath1, lpszPath2);
76 }
77
78 /*************************************************************************
79  * PathCombine   [SHELL32.37]
80  */
81 LPVOID WINAPI PathCombineAW(
82         LPVOID szDest,
83         LPCVOID lpszDir,
84         LPCVOID lpszFile)
85 {
86         if (SHELL_OsIsUnicode())
87           return PathCombineW( szDest, lpszDir, lpszFile );
88         return PathCombineA( szDest, lpszDir, lpszFile );
89 }
90
91 /*************************************************************************
92  * PathAddBackslash             [SHELL32.32]
93  */
94 LPVOID WINAPI PathAddBackslashAW(LPVOID lpszPath)
95 {
96         if(SHELL_OsIsUnicode())
97           return PathAddBackslashW(lpszPath);
98         return PathAddBackslashA(lpszPath);
99 }
100
101 /*************************************************************************
102  * PathBuildRoot                [SHELL32.30]
103  */
104 LPVOID WINAPI PathBuildRootAW(LPVOID lpszPath, int drive)
105 {
106         if(SHELL_OsIsUnicode())
107           return PathBuildRootW(lpszPath, drive);
108         return PathBuildRootA(lpszPath, drive);
109 }
110
111 /*
112         Extracting Component Parts
113 */
114
115 /*************************************************************************
116  * PathFindFileName     [SHELL32.34]
117  */
118 LPVOID WINAPI PathFindFileNameAW(LPCVOID lpszPath)
119 {
120         if(SHELL_OsIsUnicode())
121           return PathFindFileNameW(lpszPath);
122         return PathFindFileNameA(lpszPath);
123 }
124
125 /*************************************************************************
126  * PathFindExtension            [SHELL32.31]
127  */
128 LPVOID WINAPI PathFindExtensionAW(LPCVOID lpszPath)
129 {
130         if (SHELL_OsIsUnicode())
131           return PathFindExtensionW(lpszPath);
132         return PathFindExtensionA(lpszPath);
133
134 }
135
136 /*************************************************************************
137  * PathGetExtensionA            [internal]
138  *
139  * NOTES
140  *  exported by ordinal
141  *  return value points to the first char after the dot
142  */
143 static LPSTR PathGetExtensionA(LPCSTR lpszPath)
144 {
145         TRACE("(%s)\n",lpszPath);
146
147         lpszPath = PathFindExtensionA(lpszPath);
148         return (LPSTR)(*lpszPath?(lpszPath+1):lpszPath);
149 }
150
151 /*************************************************************************
152  * PathGetExtensionW            [internal]
153  */
154 static LPWSTR PathGetExtensionW(LPCWSTR lpszPath)
155 {
156         TRACE("(%s)\n",debugstr_w(lpszPath));
157
158         lpszPath = PathFindExtensionW(lpszPath);
159         return (LPWSTR)(*lpszPath?(lpszPath+1):lpszPath);
160 }
161
162 /*************************************************************************
163  * PathGetExtension             [SHELL32.158]
164  */
165 LPVOID WINAPI PathGetExtensionAW(LPCVOID lpszPath,DWORD void1, DWORD void2)
166 {
167         if (SHELL_OsIsUnicode())
168           return PathGetExtensionW(lpszPath);
169         return PathGetExtensionA(lpszPath);
170 }
171
172 /*************************************************************************
173  * PathGetArgs  [SHELL32.52]
174  */
175 LPVOID WINAPI PathGetArgsAW(LPVOID lpszPath)
176 {
177         if (SHELL_OsIsUnicode())
178           return PathGetArgsW(lpszPath);
179         return PathGetArgsA(lpszPath);
180 }
181
182 /*************************************************************************
183  * PathGetDriveNumber   [SHELL32.57]
184  */
185 int WINAPI PathGetDriveNumberAW(LPVOID lpszPath)
186 {
187         if (SHELL_OsIsUnicode())
188           return PathGetDriveNumberW(lpszPath);
189         return PathGetDriveNumberA(lpszPath);
190 }
191
192 /*************************************************************************
193  * PathRemoveFileSpec [SHELL32.35]
194  */
195 BOOL WINAPI PathRemoveFileSpecAW(LPVOID lpszPath)
196 {
197         if (SHELL_OsIsUnicode())
198           return PathRemoveFileSpecW(lpszPath);
199         return PathRemoveFileSpecA(lpszPath);
200 }
201
202 /*************************************************************************
203  * PathStripPath        [SHELL32.38]
204  */
205 void WINAPI PathStripPathAW(LPVOID lpszPath)
206 {
207         if (SHELL_OsIsUnicode())
208             PathStripPathW(lpszPath);
209         else
210             PathStripPathA(lpszPath);
211 }
212
213 /*************************************************************************
214  * PathStripToRoot      [SHELL32.50]
215  */
216 BOOL WINAPI PathStripToRootAW(LPVOID lpszPath)
217 {
218         if (SHELL_OsIsUnicode())
219           return PathStripToRootW(lpszPath);
220         return PathStripToRootA(lpszPath);
221 }
222
223 /*************************************************************************
224  * PathRemoveArgs       [SHELL32.251]
225  */
226 void WINAPI PathRemoveArgsAW(LPVOID lpszPath)
227 {
228         if (SHELL_OsIsUnicode())
229             PathRemoveArgsW(lpszPath);
230         else
231             PathRemoveArgsA(lpszPath);
232 }
233
234 /*************************************************************************
235  * PathRemoveExtension  [SHELL32.250]
236  */
237 void WINAPI PathRemoveExtensionAW(LPVOID lpszPath)
238 {
239         if (SHELL_OsIsUnicode())
240             PathRemoveExtensionW(lpszPath);
241         else
242             PathRemoveExtensionA(lpszPath);
243 }
244
245
246 /*
247         Path Manipulations
248 */
249
250 /*************************************************************************
251  * PathGetShortPathA [internal]
252  */
253 static void PathGetShortPathA(LPSTR pszPath)
254 {
255         CHAR path[MAX_PATH];
256
257         TRACE("%s\n", pszPath);
258
259         if (GetShortPathNameA(pszPath, path, MAX_PATH))
260         {
261           lstrcpyA(pszPath, path);
262         }
263 }
264
265 /*************************************************************************
266  * PathGetShortPathW [internal]
267  */
268 static void PathGetShortPathW(LPWSTR pszPath)
269 {
270         WCHAR path[MAX_PATH];
271
272         TRACE("%s\n", debugstr_w(pszPath));
273
274         if (GetShortPathNameW(pszPath, path, MAX_PATH))
275         {
276           lstrcpyW(pszPath, path);
277         }
278 }
279
280 /*************************************************************************
281  * PathGetShortPath [SHELL32.92]
282  */
283 VOID WINAPI PathGetShortPathAW(LPVOID pszPath)
284 {
285         if(SHELL_OsIsUnicode())
286           PathGetShortPathW(pszPath);
287         PathGetShortPathA(pszPath);
288 }
289
290 /*************************************************************************
291  * PathRemoveBlanks [SHELL32.33]
292  */
293 void WINAPI PathRemoveBlanksAW(LPVOID str)
294 {
295         if(SHELL_OsIsUnicode())
296             PathRemoveBlanksW(str);
297         else
298             PathRemoveBlanksA(str);
299 }
300
301 /*************************************************************************
302  * PathQuoteSpaces [SHELL32.55]
303  */
304 VOID WINAPI PathQuoteSpacesAW (LPVOID lpszPath)
305 {
306         if(SHELL_OsIsUnicode())
307             PathQuoteSpacesW(lpszPath);
308         else
309             PathQuoteSpacesA(lpszPath);
310 }
311
312 /*************************************************************************
313  * PathUnquoteSpaces [SHELL32.56]
314  */
315 VOID WINAPI PathUnquoteSpacesAW(LPVOID str)
316 {
317         if(SHELL_OsIsUnicode())
318           PathUnquoteSpacesW(str);
319         else
320           PathUnquoteSpacesA(str);
321 }
322
323 /*************************************************************************
324  * PathParseIconLocation        [SHELL32.249]
325  */
326 int WINAPI PathParseIconLocationAW (LPVOID lpszPath)
327 {
328         if(SHELL_OsIsUnicode())
329           return PathParseIconLocationW(lpszPath);
330         return PathParseIconLocationA(lpszPath);
331 }
332
333 /*
334         ########## Path Testing ##########
335 */
336 /*************************************************************************
337  * PathIsUNC            [SHELL32.39]
338  */
339 BOOL WINAPI PathIsUNCAW (LPCVOID lpszPath)
340 {
341         if (SHELL_OsIsUnicode())
342           return PathIsUNCW( lpszPath );
343         return PathIsUNCA( lpszPath );
344 }
345
346 /*************************************************************************
347  *  PathIsRelative      [SHELL32.40]
348  */
349 BOOL WINAPI PathIsRelativeAW (LPCVOID lpszPath)
350 {
351         if (SHELL_OsIsUnicode())
352           return PathIsRelativeW( lpszPath );
353         return PathIsRelativeA( lpszPath );
354 }
355
356 /*************************************************************************
357  * PathIsRoot           [SHELL32.29]
358  */
359 BOOL WINAPI PathIsRootAW(LPCVOID lpszPath)
360 {
361         if (SHELL_OsIsUnicode())
362           return PathIsRootW(lpszPath);
363         return PathIsRootA(lpszPath);
364 }
365
366 /*************************************************************************
367  *  PathIsExeA          [internal]
368  */
369 static BOOL PathIsExeA (LPCSTR lpszPath)
370 {
371         LPCSTR lpszExtension = PathGetExtensionA(lpszPath);
372         int i;
373         static const char * const lpszExtensions[] =
374             {"exe", "com", "pif", "cmd", "bat", "scf", "scr", NULL };
375
376         TRACE("path=%s\n",lpszPath);
377
378         for(i=0; lpszExtensions[i]; i++)
379           if (!lstrcmpiA(lpszExtension,lpszExtensions[i])) return TRUE;
380
381         return FALSE;
382 }
383
384 /*************************************************************************
385  *  PathIsExeW          [internal]
386  */
387 static BOOL PathIsExeW (LPCWSTR lpszPath)
388 {
389         LPCWSTR lpszExtension = PathGetExtensionW(lpszPath);
390         int i;
391         static const WCHAR lpszExtensions[][4] =
392             {{'e','x','e','\0'}, {'c','o','m','\0'}, {'p','i','f','\0'},
393              {'c','m','d','\0'}, {'b','a','t','\0'}, {'s','c','f','\0'},
394              {'s','c','r','\0'}, {'\0'} };
395
396         TRACE("path=%s\n",debugstr_w(lpszPath));
397
398         for(i=0; lpszExtensions[i][0]; i++)
399           if (!strcmpiW(lpszExtension,lpszExtensions[i])) return TRUE;
400
401         return FALSE;
402 }
403
404 /*************************************************************************
405  *  PathIsExe           [SHELL32.43]
406  */
407 BOOL WINAPI PathIsExeAW (LPCVOID path)
408 {
409         if (SHELL_OsIsUnicode())
410           return PathIsExeW (path);
411         return PathIsExeA(path);
412 }
413
414 /*************************************************************************
415  * PathIsDirectory      [SHELL32.159]
416  */
417 BOOL WINAPI PathIsDirectoryAW (LPCVOID lpszPath)
418 {
419         if (SHELL_OsIsUnicode())
420           return PathIsDirectoryW (lpszPath);
421         return PathIsDirectoryA (lpszPath);
422 }
423
424 /*************************************************************************
425  * PathFileExists       [SHELL32.45]
426  */
427 BOOL WINAPI PathFileExistsAW (LPCVOID lpszPath)
428 {
429         if (SHELL_OsIsUnicode())
430           return PathFileExistsW (lpszPath);
431         return PathFileExistsA (lpszPath);
432 }
433
434 /*************************************************************************
435  * PathMatchSpec        [SHELL32.46]
436  */
437 BOOL WINAPI PathMatchSpecAW(LPVOID name, LPVOID mask)
438 {
439         if (SHELL_OsIsUnicode())
440           return PathMatchSpecW( name, mask );
441         return PathMatchSpecA( name, mask );
442 }
443
444 /*************************************************************************
445  * PathIsSameRoot       [SHELL32.650]
446  */
447 BOOL WINAPI PathIsSameRootAW(LPCVOID lpszPath1, LPCVOID lpszPath2)
448 {
449         if (SHELL_OsIsUnicode())
450           return PathIsSameRootW(lpszPath1, lpszPath2);
451         return PathIsSameRootA(lpszPath1, lpszPath2);
452 }
453
454 /*************************************************************************
455  * IsLFNDriveA          [SHELL32.41]
456  */
457 BOOL WINAPI IsLFNDriveA(LPCSTR lpszPath)
458 {
459     DWORD       fnlen;
460
461     if (!GetVolumeInformationA(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
462         return FALSE;
463     return fnlen > 12;
464 }
465
466 /*************************************************************************
467  * IsLFNDriveW          [SHELL32.42]
468  */
469 BOOL WINAPI IsLFNDriveW(LPCWSTR lpszPath)
470 {
471     DWORD       fnlen;
472
473     if (!GetVolumeInformationW(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
474         return FALSE;
475     return fnlen > 12;
476 }
477
478 /*************************************************************************
479  * IsLFNDrive           [SHELL32.119]
480  */
481 BOOL WINAPI IsLFNDriveAW(LPCVOID lpszPath)
482 {
483         if (SHELL_OsIsUnicode())
484           return IsLFNDriveW(lpszPath);
485         return IsLFNDriveA(lpszPath);
486 }
487
488 /*
489         ########## Creating Something Unique ##########
490 */
491 /*************************************************************************
492  * PathMakeUniqueNameA  [internal]
493  */
494 static BOOL PathMakeUniqueNameA(
495         LPSTR lpszBuffer,
496         DWORD dwBuffSize,
497         LPCSTR lpszShortName,
498         LPCSTR lpszLongName,
499         LPCSTR lpszPathName)
500 {
501         FIXME("%p %u %s %s %s stub\n",
502          lpszBuffer, dwBuffSize, debugstr_a(lpszShortName),
503          debugstr_a(lpszLongName), debugstr_a(lpszPathName));
504         return TRUE;
505 }
506
507 /*************************************************************************
508  * PathMakeUniqueNameW  [internal]
509  */
510 static BOOL PathMakeUniqueNameW(
511         LPWSTR lpszBuffer,
512         DWORD dwBuffSize,
513         LPCWSTR lpszShortName,
514         LPCWSTR lpszLongName,
515         LPCWSTR lpszPathName)
516 {
517         FIXME("%p %u %s %s %s stub\n",
518          lpszBuffer, dwBuffSize, debugstr_w(lpszShortName),
519          debugstr_w(lpszLongName), debugstr_w(lpszPathName));
520         return TRUE;
521 }
522
523 /*************************************************************************
524  * PathMakeUniqueName   [SHELL32.47]
525  */
526 BOOL WINAPI PathMakeUniqueNameAW(
527         LPVOID lpszBuffer,
528         DWORD dwBuffSize,
529         LPCVOID lpszShortName,
530         LPCVOID lpszLongName,
531         LPCVOID lpszPathName)
532 {
533         if (SHELL_OsIsUnicode())
534           return PathMakeUniqueNameW(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
535         return PathMakeUniqueNameA(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
536 }
537
538 /*************************************************************************
539  * PathYetAnotherMakeUniqueName [SHELL32.75]
540  *
541  * NOTES
542  *     exported by ordinal
543  */
544 BOOL WINAPI PathYetAnotherMakeUniqueName(
545         LPWSTR lpszBuffer,
546         LPCWSTR lpszPathName,
547         LPCWSTR lpszShortName,
548         LPCWSTR lpszLongName)
549 {
550     FIXME("(%p, %s, %s ,%s):stub.\n",
551           lpszBuffer, debugstr_w(lpszPathName), debugstr_w(lpszShortName), debugstr_w(lpszLongName));
552     return TRUE;
553 }
554
555
556 /*
557         ########## cleaning and resolving paths ##########
558  */
559
560 /*************************************************************************
561  * PathFindOnPath       [SHELL32.145]
562  */
563 BOOL WINAPI PathFindOnPathAW(LPVOID sFile, LPCVOID *sOtherDirs)
564 {
565         if (SHELL_OsIsUnicode())
566           return PathFindOnPathW(sFile, (LPCWSTR *)sOtherDirs);
567         return PathFindOnPathA(sFile, (LPCSTR *)sOtherDirs);
568 }
569
570 /*************************************************************************
571  * PathCleanupSpec      [SHELL32.171]
572  *
573  * lpszFile is changed in place.
574  */
575 int WINAPI PathCleanupSpec( LPCWSTR lpszPathW, LPWSTR lpszFileW )
576 {
577     int i = 0;
578     DWORD rc = 0;
579     int length = 0;
580
581     if (SHELL_OsIsUnicode())
582     {
583         LPWSTR p = lpszFileW;
584
585         TRACE("Cleanup %s\n",debugstr_w(lpszFileW));
586
587         if (lpszPathW)
588             length = strlenW(lpszPathW);
589
590         while (*p)
591         {
592             int gct = PathGetCharTypeW(*p);
593             if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
594             {
595                 lpszFileW[i]='-';
596                 rc |= PCS_REPLACEDCHAR;
597             }
598             else
599                 lpszFileW[i]=*p;
600             i++;
601             p++;
602             if (length + i == MAX_PATH)
603             {
604                 rc |= PCS_FATAL | PCS_PATHTOOLONG;
605                 break;
606             }
607         }
608         lpszFileW[i]=0;
609     }
610     else
611     {
612         LPSTR lpszFileA = (LPSTR)lpszFileW;
613         LPCSTR lpszPathA = (LPCSTR)lpszPathW;
614         LPSTR p = lpszFileA;
615
616         TRACE("Cleanup %s\n",debugstr_a(lpszFileA));
617
618         if (lpszPathA)
619             length = strlen(lpszPathA);
620
621         while (*p)
622         {
623             int gct = PathGetCharTypeA(*p);
624             if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
625             {
626                 lpszFileA[i]='-';
627                 rc |= PCS_REPLACEDCHAR;
628             }
629             else
630                 lpszFileA[i]=*p;
631             i++;
632             p++;
633             if (length + i == MAX_PATH)
634             {
635                 rc |= PCS_FATAL | PCS_PATHTOOLONG;
636                 break;
637             }
638         }
639         lpszFileA[i]=0;
640     }
641     return rc;
642 }
643
644 /*************************************************************************
645  * PathQualifyA         [SHELL32]
646  */
647 static BOOL PathQualifyA(LPCSTR pszPath)
648 {
649         FIXME("%s\n",pszPath);
650         return 0;
651 }
652
653 /*************************************************************************
654  * PathQualifyW         [SHELL32]
655  */
656 static BOOL PathQualifyW(LPCWSTR pszPath)
657 {
658         FIXME("%s\n",debugstr_w(pszPath));
659         return 0;
660 }
661
662 /*************************************************************************
663  * PathQualify  [SHELL32.49]
664  */
665 BOOL WINAPI PathQualifyAW(LPCVOID pszPath)
666 {
667         if (SHELL_OsIsUnicode())
668           return PathQualifyW(pszPath);
669         return PathQualifyA(pszPath);
670 }
671
672 static BOOL PathResolveA(LPSTR path, LPCSTR *paths, DWORD flags)
673 {
674     FIXME("(%s,%p,0x%08x),stub!\n", debugstr_a(path), paths, flags);
675     return FALSE;
676 }
677
678 static BOOL PathResolveW(LPWSTR path, LPCWSTR *paths, DWORD flags)
679 {
680     FIXME("(%s,%p,0x%08x),stub!\n", debugstr_w(path), paths, flags);
681     return FALSE;
682 }
683
684 /*************************************************************************
685  * PathResolve [SHELL32.51]
686  */
687 BOOL WINAPI PathResolveAW(LPVOID path, LPCVOID *paths, DWORD flags)
688 {
689     if (SHELL_OsIsUnicode())
690         return PathResolveW(path, (LPCWSTR*)paths, flags);
691     else
692         return PathResolveA(path, (LPCSTR*)paths, flags);
693 }
694
695 /*************************************************************************
696 *       PathProcessCommandA
697 */
698 static LONG PathProcessCommandA (
699         LPCSTR lpszPath,
700         LPSTR lpszBuff,
701         DWORD dwBuffSize,
702         DWORD dwFlags)
703 {
704         FIXME("%s %p 0x%04x 0x%04x stub\n",
705         lpszPath, lpszBuff, dwBuffSize, dwFlags);
706         if(!lpszPath) return -1;
707         if(lpszBuff) strcpy(lpszBuff, lpszPath);
708         return strlen(lpszPath);
709 }
710
711 /*************************************************************************
712 *       PathProcessCommandW
713 */
714 static LONG PathProcessCommandW (
715         LPCWSTR lpszPath,
716         LPWSTR lpszBuff,
717         DWORD dwBuffSize,
718         DWORD dwFlags)
719 {
720         FIXME("(%s, %p, 0x%04x, 0x%04x) stub\n",
721         debugstr_w(lpszPath), lpszBuff, dwBuffSize, dwFlags);
722         if(!lpszPath) return -1;
723         if(lpszBuff) strcpyW(lpszBuff, lpszPath);
724         return strlenW(lpszPath);
725 }
726
727 /*************************************************************************
728 *       PathProcessCommand (SHELL32.653)
729 */
730 LONG WINAPI PathProcessCommandAW (
731         LPCVOID lpszPath,
732         LPVOID lpszBuff,
733         DWORD dwBuffSize,
734         DWORD dwFlags)
735 {
736         if (SHELL_OsIsUnicode())
737           return PathProcessCommandW(lpszPath, lpszBuff, dwBuffSize, dwFlags);
738         return PathProcessCommandA(lpszPath, lpszBuff, dwBuffSize, dwFlags);
739 }
740
741 /*
742         ########## special ##########
743 */
744
745 /*************************************************************************
746  * PathSetDlgItemPath (SHELL32.48)
747  */
748 VOID WINAPI PathSetDlgItemPathAW(HWND hDlg, int id, LPCVOID pszPath)
749 {
750         if (SHELL_OsIsUnicode())
751             PathSetDlgItemPathW(hDlg, id, pszPath);
752         else
753             PathSetDlgItemPathA(hDlg, id, pszPath);
754 }
755
756 static const WCHAR szCurrentVersion[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\0'};
757 static const WCHAR Administrative_ToolsW[] = {'A','d','m','i','n','i','s','t','r','a','t','i','v','e',' ','T','o','o','l','s','\0'};
758 static const WCHAR AppDataW[] = {'A','p','p','D','a','t','a','\0'};
759 static const WCHAR AppData_LocalLowW[] = {'A','p','p','D','a','t','a','\\','L','o','c','a','l','L','o','w','\0'};
760 static const WCHAR Application_DataW[] = {'A','p','p','l','i','c','a','t','i','o','n',' ','D','a','t','a','\0'};
761 static const WCHAR CacheW[] = {'C','a','c','h','e','\0'};
762 static const WCHAR CD_BurningW[] = {'C','D',' ','B','u','r','n','i','n','g','\0'};
763 static const WCHAR Common_Administrative_ToolsW[] = {'C','o','m','m','o','n',' ','A','d','m','i','n','i','s','t','r','a','t','i','v','e',' ','T','o','o','l','s','\0'};
764 static const WCHAR Common_AppDataW[] = {'C','o','m','m','o','n',' ','A','p','p','D','a','t','a','\0'};
765 static const WCHAR Common_DesktopW[] = {'C','o','m','m','o','n',' ','D','e','s','k','t','o','p','\0'};
766 static const WCHAR Common_DocumentsW[] = {'C','o','m','m','o','n',' ','D','o','c','u','m','e','n','t','s','\0'};
767 static const WCHAR Common_FavoritesW[] = {'C','o','m','m','o','n',' ','F','a','v','o','r','i','t','e','s','\0'};
768 static const WCHAR CommonFilesDirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r','\0'};
769 static const WCHAR CommonFilesDirX86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
770 static const WCHAR CommonMusicW[] = {'C','o','m','m','o','n','M','u','s','i','c','\0'};
771 static const WCHAR CommonPicturesW[] = {'C','o','m','m','o','n','P','i','c','t','u','r','e','s','\0'};
772 static const WCHAR Common_ProgramsW[] = {'C','o','m','m','o','n',' ','P','r','o','g','r','a','m','s','\0'};
773 static const WCHAR Common_StartUpW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t','U','p','\0'};
774 static const WCHAR Common_Start_MenuW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t',' ','M','e','n','u','\0'};
775 static const WCHAR Common_TemplatesW[] = {'C','o','m','m','o','n',' ','T','e','m','p','l','a','t','e','s','\0'};
776 static const WCHAR CommonVideoW[] = {'C','o','m','m','o','n','V','i','d','e','o','\0'};
777 static const WCHAR ContactsW[] = {'C','o','n','t','a','c','t','s','\0'};
778 static const WCHAR CookiesW[] = {'C','o','o','k','i','e','s','\0'};
779 static const WCHAR DesktopW[] = {'D','e','s','k','t','o','p','\0'};
780 static const WCHAR DocumentsW[] = {'D','o','c','u','m','e','n','t','s','\0'};
781 static const WCHAR DownloadsW[] = {'D','o','w','n','l','o','a','d','s','\0'};
782 static const WCHAR FavoritesW[] = {'F','a','v','o','r','i','t','e','s','\0'};
783 static const WCHAR FontsW[] = {'F','o','n','t','s','\0'};
784 static const WCHAR HistoryW[] = {'H','i','s','t','o','r','y','\0'};
785 static const WCHAR LinksW[] = {'L','i','n','k','s','\0'};
786 static const WCHAR Local_AppDataW[] = {'L','o','c','a','l',' ','A','p','p','D','a','t','a','\0'};
787 static const WCHAR Local_Settings_Application_DataW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','A','p','p','l','i','c','a','t','i','o','n',' ','D','a','t','a','\0'};
788 static const WCHAR Local_Settings_CD_BurningW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','A','p','p','l','i','c','a','t','i','o','n',' ','D','a','t','a','\\','M','i','c','r','o','s','o','f','t','\\','C','D',' ','B','u','r','n','i','n','g','\0'};
789 static const WCHAR Local_Settings_HistoryW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','H','i','s','t','o','r','y','\0'};
790 static const WCHAR Local_Settings_Temporary_Internet_FilesW[] = {'L','o','c','a','l',' ','S','e','t','t','i','n','g','s','\\','T','e','m','p','o','r','a','r','y',' ','I','n','t','e','r','n','e','t',' ','F','i','l','e','s','\0'};
791 static const WCHAR Microsoft_Windows_GameExplorerW[] = {'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','G','a','m','e','E','x','p','l','o','r','e','r','\0'};
792 static const WCHAR Microsoft_Windows_LibrariesW[] = {'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','L','i','b','r','a','r','i','e','s','\0'};
793 static const WCHAR Microsoft_Windows_RingtonesW[] = {'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','R','i','n','g','t','o','n','e','s','\0'};
794 static const WCHAR MusicW[] = {'M','u','s','i','c','\0'};
795 static const WCHAR Music_PlaylistsW[] = {'M','u','s','i','c','\\','P','l','a','y','l','i','s','t','s','\0'};
796 static const WCHAR Music_Sample_MusicW[] = {'M','u','s','i','c','\\','S','a','m','p','l','e',' ','M','u','s','i','c','\0'};
797 static const WCHAR Music_Sample_PlaylistsW[] = {'M','u','s','i','c','\\','S','a','m','p','l','e',' ','P','l','a','y','l','i','s','t','s','\0'};
798 static const WCHAR My_DocumentsW[] = {'M','y',' ','D','o','c','u','m','e','n','t','s','\0'};
799 static const WCHAR My_MusicW[] = {'M','y',' ','M','u','s','i','c','\0'};
800 static const WCHAR My_PicturesW[] = {'M','y',' ','P','i','c','t','u','r','e','s','\0'};
801 static const WCHAR My_VideosW[] = {'M','y',' ','V','i','d','e','o','s','\0'};
802 static const WCHAR NetHoodW[] = {'N','e','t','H','o','o','d','\0'};
803 static const WCHAR OEM_LinksW[] = {'O','E','M',' ','L','i','n','k','s','\0'};
804 static const WCHAR PersonalW[] = {'P','e','r','s','o','n','a','l','\0'};
805 static const WCHAR PicturesW[] = {'P','i','c','t','u','r','e','s','\0'};
806 static const WCHAR Pictures_Sample_PicturesW[] = {'P','i','c','t','u','r','e','s','\\','S','a','m','p','l','e',' ','P','i','c','t','u','r','e','s','\0'};
807 static const WCHAR Pictures_Slide_ShowsW[] = {'P','i','c','t','u','r','e','s','\\','S','l','i','d','e',' ','S','h','o','w','s','\0'};
808 static const WCHAR PrintHoodW[] = {'P','r','i','n','t','H','o','o','d','\0'};
809 static const WCHAR Program_FilesW[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s','\0'};
810 static const WCHAR Program_Files_Common_FilesW[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s','\\','C','o','m','m','o','n',' ','F','i','l','e','s','\0'};
811 static const WCHAR Program_Files_x86W[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s',' ','(','x','8','6',')','\0'};
812 static const WCHAR Program_Files_x86_Common_FilesW[] = {'P','r','o','g','r','a','m',' ','F','i','l','e','s',' ','(','x','8','6',')','\\','C','o','m','m','o','n',' ','F','i','l','e','s','\0'};
813 static const WCHAR ProgramFilesDirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r','\0'};
814 static const WCHAR ProgramFilesDirX86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
815 static const WCHAR ProgramsW[] = {'P','r','o','g','r','a','m','s','\0'};
816 static const WCHAR RecentW[] = {'R','e','c','e','n','t','\0'};
817 static const WCHAR ResourcesW[] = {'R','e','s','o','u','r','c','e','s','\0'};
818 static const WCHAR Saved_GamesW[] = {'S','a','v','e','d',' ','G','a','m','e','s','\0'};
819 static const WCHAR SearchesW[] = {'S','e','a','r','c','h','e','s','\0'};
820 static const WCHAR SendToW[] = {'S','e','n','d','T','o','\0'};
821 static const WCHAR StartUpW[] = {'S','t','a','r','t','U','p','\0'};
822 static const WCHAR Start_MenuW[] = {'S','t','a','r','t',' ','M','e','n','u','\0'};
823 static const WCHAR Start_Menu_ProgramsW[] = {'S','t','a','r','t',' ','M','e','n','u','\\','P','r','o','g','r','a','m','s','\0'};
824 static const WCHAR Start_Menu_Admin_ToolsW[] = {'S','t','a','r','t',' ','M','e','n','u','\\','P','r','o','g','r','a','m','s','\\','A','d','m','i','n','i','s','t','r','a','t','i','v','e',' ','T','o','o','l','s','\0'};
825 static const WCHAR Start_Menu_StartupW[] = {'S','t','a','r','t',' ','M','e','n','u','\\','P','r','o','g','r','a','m','s','\\','S','t','a','r','t','U','p','\0'};
826 static const WCHAR TemplatesW[] = {'T','e','m','p','l','a','t','e','s','\0'};
827 static const WCHAR UsersW[] = {'U','s','e','r','s','\0'};
828 static const WCHAR UsersPublicW[] = {'U','s','e','r','s','\\','P','u','b','l','i','c','\0'};
829 static const WCHAR VideosW[] = {'V','i','d','e','o','s','\0'};
830 static const WCHAR Videos_Sample_VideosW[] = {'V','i','d','e','o','s','\\','S','a','m','p','l','e',' ','V','i','d','e','o','s','\0'};
831 static const WCHAR DefaultW[] = {'.','D','e','f','a','u','l','t','\0'};
832 static const WCHAR AllUsersProfileW[] = {'%','A','L','L','U','S','E','R','S','P','R','O','F','I','L','E','%','\0'};
833 static const WCHAR UserProfileW[] = {'%','U','S','E','R','P','R','O','F','I','L','E','%','\0'};
834 static const WCHAR SystemDriveW[] = {'%','S','y','s','t','e','m','D','r','i','v','e','%','\0'};
835 static const WCHAR ProfileListW[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s',' ','N','T','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','P','r','o','f','i','l','e','L','i','s','t',0};
836 static const WCHAR ProfilesDirectoryW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
837 static const WCHAR AllUsersProfileValueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
838 static const WCHAR szSHFolders[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','S','h','e','l','l',' ','F','o','l','d','e','r','s','\0'};
839 static const WCHAR szSHUserFolders[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','U','s','e','r',' ','S','h','e','l','l',' ','F','o','l','d','e','r','s','\0'};
840 static const WCHAR szDefaultProfileDirW[] = {'u','s','e','r','s',0};
841 static const WCHAR szKnownFolderDescriptions[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','F','o','l','d','e','r','D','e','s','c','r','i','p','t','i','o','n','s','\0'};
842 static const WCHAR szKnownFolderRedirections[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','E','x','p','l','o','r','e','r','\\','U','s','e','r',' ','S','h','e','l','l',' ','F','o','l','d','e','r','s',0};
843 static const WCHAR AllUsersW[] = {'P','u','b','l','i','c',0};
844
845 typedef enum _CSIDL_Type {
846     CSIDL_Type_User,
847     CSIDL_Type_AllUsers,
848     CSIDL_Type_CurrVer,
849     CSIDL_Type_Disallowed,
850     CSIDL_Type_NonExistent,
851     CSIDL_Type_WindowsPath,
852     CSIDL_Type_SystemPath,
853     CSIDL_Type_SystemX86Path,
854 } CSIDL_Type;
855
856 typedef struct
857 {
858     const KNOWNFOLDERID *id;
859     CSIDL_Type type;
860     LPCWSTR    szValueName;
861     LPCWSTR    szDefaultPath; /* fallback string or resource ID */
862 } CSIDL_DATA;
863
864 static const CSIDL_DATA CSIDL_Data[] =
865 {
866     { /* 0x00 - CSIDL_DESKTOP */
867         &FOLDERID_Desktop,
868         CSIDL_Type_User,
869         DesktopW,
870         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
871     },
872     { /* 0x01 - CSIDL_INTERNET */
873         &FOLDERID_InternetFolder,
874         CSIDL_Type_Disallowed,
875         NULL,
876         NULL
877     },
878     { /* 0x02 - CSIDL_PROGRAMS */
879         &FOLDERID_Programs,
880         CSIDL_Type_User,
881         ProgramsW,
882         Start_Menu_ProgramsW
883     },
884     { /* 0x03 - CSIDL_CONTROLS (.CPL files) */
885         &FOLDERID_ControlPanelFolder,
886         CSIDL_Type_SystemPath,
887         NULL,
888         NULL
889     },
890     { /* 0x04 - CSIDL_PRINTERS */
891         &FOLDERID_PrintersFolder,
892         CSIDL_Type_SystemPath,
893         NULL,
894         NULL
895     },
896     { /* 0x05 - CSIDL_PERSONAL */
897         &FOLDERID_Documents,
898         CSIDL_Type_User,
899         PersonalW,
900         MAKEINTRESOURCEW(IDS_PERSONAL)
901     },
902     { /* 0x06 - CSIDL_FAVORITES */
903         &FOLDERID_Favorites,
904         CSIDL_Type_User,
905         FavoritesW,
906         FavoritesW
907     },
908     { /* 0x07 - CSIDL_STARTUP */
909         &FOLDERID_Startup,
910         CSIDL_Type_User,
911         StartUpW,
912         Start_Menu_StartupW
913     },
914     { /* 0x08 - CSIDL_RECENT */
915         &FOLDERID_Recent,
916         CSIDL_Type_User,
917         RecentW,
918         RecentW
919     },
920     { /* 0x09 - CSIDL_SENDTO */
921         &FOLDERID_SendTo,
922         CSIDL_Type_User,
923         SendToW,
924         SendToW
925     },
926     { /* 0x0a - CSIDL_BITBUCKET - Recycle Bin */
927         &FOLDERID_RecycleBinFolder,
928         CSIDL_Type_Disallowed,
929         NULL,
930         NULL,
931     },
932     { /* 0x0b - CSIDL_STARTMENU */
933         &FOLDERID_StartMenu,
934         CSIDL_Type_User,
935         Start_MenuW,
936         Start_MenuW
937     },
938     { /* 0x0c - CSIDL_MYDOCUMENTS */
939         &GUID_NULL,
940         CSIDL_Type_Disallowed, /* matches WinXP--can't get its path */
941         NULL,
942         NULL
943     },
944     { /* 0x0d - CSIDL_MYMUSIC */
945         &FOLDERID_Music,
946         CSIDL_Type_User,
947         My_MusicW,
948         MAKEINTRESOURCEW(IDS_MYMUSIC)
949     },
950     { /* 0x0e - CSIDL_MYVIDEO */
951         &FOLDERID_Videos,
952         CSIDL_Type_User,
953         My_VideosW,
954         MAKEINTRESOURCEW(IDS_MYVIDEOS)
955     },
956     { /* 0x0f - unassigned */
957         &GUID_NULL,
958         CSIDL_Type_Disallowed,
959         NULL,
960         NULL,
961     },
962     { /* 0x10 - CSIDL_DESKTOPDIRECTORY */
963         &FOLDERID_Desktop,
964         CSIDL_Type_User,
965         DesktopW,
966         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
967     },
968     { /* 0x11 - CSIDL_DRIVES */
969         &FOLDERID_ComputerFolder,
970         CSIDL_Type_Disallowed,
971         NULL,
972         NULL,
973     },
974     { /* 0x12 - CSIDL_NETWORK */
975         &FOLDERID_NetworkFolder,
976         CSIDL_Type_Disallowed,
977         NULL,
978         NULL,
979     },
980     { /* 0x13 - CSIDL_NETHOOD */
981         &FOLDERID_NetHood,
982         CSIDL_Type_User,
983         NetHoodW,
984         NetHoodW
985     },
986     { /* 0x14 - CSIDL_FONTS */
987         &FOLDERID_Fonts,
988         CSIDL_Type_WindowsPath,
989         FontsW,
990         FontsW
991     },
992     { /* 0x15 - CSIDL_TEMPLATES */
993         &FOLDERID_Templates,
994         CSIDL_Type_User,
995         TemplatesW,
996         TemplatesW
997     },
998     { /* 0x16 - CSIDL_COMMON_STARTMENU */
999         &FOLDERID_CommonStartMenu,
1000         CSIDL_Type_AllUsers,
1001         Common_Start_MenuW,
1002         Start_MenuW
1003     },
1004     { /* 0x17 - CSIDL_COMMON_PROGRAMS */
1005         &FOLDERID_CommonPrograms,
1006         CSIDL_Type_AllUsers,
1007         Common_ProgramsW,
1008         Start_Menu_ProgramsW
1009     },
1010     { /* 0x18 - CSIDL_COMMON_STARTUP */
1011         &FOLDERID_CommonStartup,
1012         CSIDL_Type_AllUsers,
1013         Common_StartUpW,
1014         Start_Menu_StartupW
1015     },
1016     { /* 0x19 - CSIDL_COMMON_DESKTOPDIRECTORY */
1017         &FOLDERID_PublicDesktop,
1018         CSIDL_Type_AllUsers,
1019         Common_DesktopW,
1020         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
1021     },
1022     { /* 0x1a - CSIDL_APPDATA */
1023         &FOLDERID_RoamingAppData,
1024         CSIDL_Type_User,
1025         AppDataW,
1026         Application_DataW
1027     },
1028     { /* 0x1b - CSIDL_PRINTHOOD */
1029         &FOLDERID_PrintHood,
1030         CSIDL_Type_User,
1031         PrintHoodW,
1032         PrintHoodW
1033     },
1034     { /* 0x1c - CSIDL_LOCAL_APPDATA */
1035         &FOLDERID_LocalAppData,
1036         CSIDL_Type_User,
1037         Local_AppDataW,
1038         Local_Settings_Application_DataW
1039     },
1040     { /* 0x1d - CSIDL_ALTSTARTUP */
1041         &GUID_NULL,
1042         CSIDL_Type_NonExistent,
1043         NULL,
1044         NULL
1045     },
1046     { /* 0x1e - CSIDL_COMMON_ALTSTARTUP */
1047         &GUID_NULL,
1048         CSIDL_Type_NonExistent,
1049         NULL,
1050         NULL
1051     },
1052     { /* 0x1f - CSIDL_COMMON_FAVORITES */
1053         &FOLDERID_Favorites,
1054         CSIDL_Type_AllUsers,
1055         Common_FavoritesW,
1056         FavoritesW
1057     },
1058     { /* 0x20 - CSIDL_INTERNET_CACHE */
1059         &FOLDERID_InternetCache,
1060         CSIDL_Type_User,
1061         CacheW,
1062         Local_Settings_Temporary_Internet_FilesW
1063     },
1064     { /* 0x21 - CSIDL_COOKIES */
1065         &FOLDERID_Cookies,
1066         CSIDL_Type_User,
1067         CookiesW,
1068         CookiesW
1069     },
1070     { /* 0x22 - CSIDL_HISTORY */
1071         &FOLDERID_History,
1072         CSIDL_Type_User,
1073         HistoryW,
1074         Local_Settings_HistoryW
1075     },
1076     { /* 0x23 - CSIDL_COMMON_APPDATA */
1077         &FOLDERID_ProgramData,
1078         CSIDL_Type_AllUsers,
1079         Common_AppDataW,
1080         Application_DataW
1081     },
1082     { /* 0x24 - CSIDL_WINDOWS */
1083         &FOLDERID_Windows,
1084         CSIDL_Type_WindowsPath,
1085         NULL,
1086         NULL
1087     },
1088     { /* 0x25 - CSIDL_SYSTEM */
1089         &FOLDERID_System,
1090         CSIDL_Type_SystemPath,
1091         NULL,
1092         NULL
1093     },
1094     { /* 0x26 - CSIDL_PROGRAM_FILES */
1095         &FOLDERID_ProgramFiles,
1096         CSIDL_Type_CurrVer,
1097         ProgramFilesDirW,
1098         Program_FilesW
1099     },
1100     { /* 0x27 - CSIDL_MYPICTURES */
1101         &FOLDERID_Pictures,
1102         CSIDL_Type_User,
1103         My_PicturesW,
1104         MAKEINTRESOURCEW(IDS_MYPICTURES)
1105     },
1106     { /* 0x28 - CSIDL_PROFILE */
1107         &FOLDERID_Profile,
1108         CSIDL_Type_User,
1109         NULL,
1110         NULL
1111     },
1112     { /* 0x29 - CSIDL_SYSTEMX86 */
1113         &FOLDERID_SystemX86,
1114         CSIDL_Type_SystemX86Path,
1115         NULL,
1116         NULL
1117     },
1118     { /* 0x2a - CSIDL_PROGRAM_FILESX86 */
1119         &FOLDERID_ProgramFilesX86,
1120         CSIDL_Type_CurrVer,
1121         ProgramFilesDirX86W,
1122         Program_Files_x86W
1123     },
1124     { /* 0x2b - CSIDL_PROGRAM_FILES_COMMON */
1125         &FOLDERID_ProgramFilesCommon,
1126         CSIDL_Type_CurrVer,
1127         CommonFilesDirW,
1128         Program_Files_Common_FilesW
1129     },
1130     { /* 0x2c - CSIDL_PROGRAM_FILES_COMMONX86 */
1131         &FOLDERID_ProgramFilesCommonX86,
1132         CSIDL_Type_CurrVer,
1133         CommonFilesDirX86W,
1134         Program_Files_x86_Common_FilesW
1135     },
1136     { /* 0x2d - CSIDL_COMMON_TEMPLATES */
1137         &FOLDERID_CommonTemplates,
1138         CSIDL_Type_AllUsers,
1139         Common_TemplatesW,
1140         TemplatesW
1141     },
1142     { /* 0x2e - CSIDL_COMMON_DOCUMENTS */
1143         &FOLDERID_PublicDocuments,
1144         CSIDL_Type_AllUsers,
1145         Common_DocumentsW,
1146         DocumentsW
1147     },
1148     { /* 0x2f - CSIDL_COMMON_ADMINTOOLS */
1149         &FOLDERID_CommonAdminTools,
1150         CSIDL_Type_AllUsers,
1151         Common_Administrative_ToolsW,
1152         Start_Menu_Admin_ToolsW
1153     },
1154     { /* 0x30 - CSIDL_ADMINTOOLS */
1155         &FOLDERID_AdminTools,
1156         CSIDL_Type_User,
1157         Administrative_ToolsW,
1158         Start_Menu_Admin_ToolsW
1159     },
1160     { /* 0x31 - CSIDL_CONNECTIONS */
1161         &FOLDERID_ConnectionsFolder,
1162         CSIDL_Type_Disallowed,
1163         NULL,
1164         NULL
1165     },
1166     { /* 0x32 - unassigned */
1167         &GUID_NULL,
1168         CSIDL_Type_Disallowed,
1169         NULL,
1170         NULL
1171     },
1172     { /* 0x33 - unassigned */
1173         &GUID_NULL,
1174         CSIDL_Type_Disallowed,
1175         NULL,
1176         NULL
1177     },
1178     { /* 0x34 - unassigned */
1179         &GUID_NULL,
1180         CSIDL_Type_Disallowed,
1181         NULL,
1182         NULL
1183     },
1184     { /* 0x35 - CSIDL_COMMON_MUSIC */
1185         &FOLDERID_PublicMusic,
1186         CSIDL_Type_AllUsers,
1187         CommonMusicW,
1188         MusicW
1189     },
1190     { /* 0x36 - CSIDL_COMMON_PICTURES */
1191         &FOLDERID_PublicPictures,
1192         CSIDL_Type_AllUsers,
1193         CommonPicturesW,
1194         PicturesW
1195     },
1196     { /* 0x37 - CSIDL_COMMON_VIDEO */
1197         &FOLDERID_PublicVideos,
1198         CSIDL_Type_AllUsers,
1199         CommonVideoW,
1200         VideosW
1201     },
1202     { /* 0x38 - CSIDL_RESOURCES */
1203         &FOLDERID_ResourceDir,
1204         CSIDL_Type_WindowsPath,
1205         NULL,
1206         ResourcesW
1207     },
1208     { /* 0x39 - CSIDL_RESOURCES_LOCALIZED */
1209         &FOLDERID_LocalizedResourcesDir,
1210         CSIDL_Type_NonExistent,
1211         NULL,
1212         NULL
1213     },
1214     { /* 0x3a - CSIDL_COMMON_OEM_LINKS */
1215         &FOLDERID_CommonOEMLinks,
1216         CSIDL_Type_AllUsers,
1217         NULL,
1218         OEM_LinksW
1219     },
1220     { /* 0x3b - CSIDL_CDBURN_AREA */
1221         &FOLDERID_CDBurning,
1222         CSIDL_Type_User,
1223         CD_BurningW,
1224         Local_Settings_CD_BurningW
1225     },
1226     { /* 0x3c unassigned */
1227         &GUID_NULL,
1228         CSIDL_Type_Disallowed,
1229         NULL,
1230         NULL
1231     },
1232     { /* 0x3d - CSIDL_COMPUTERSNEARME */
1233         &GUID_NULL,
1234         CSIDL_Type_Disallowed, /* FIXME */
1235         NULL,
1236         NULL
1237     },
1238     { /* 0x3e - CSIDL_PROFILES */
1239         &GUID_NULL,
1240         CSIDL_Type_Disallowed, /* oddly, this matches WinXP */
1241         NULL,
1242         NULL
1243     },
1244     { /* 0x3f */
1245         &FOLDERID_AddNewPrograms,
1246         CSIDL_Type_Disallowed,
1247         NULL,
1248         NULL
1249     },
1250     { /* 0x40 */
1251         &FOLDERID_AppUpdates,
1252         CSIDL_Type_Disallowed,
1253         NULL,
1254         NULL
1255     },
1256     { /* 0x41 */
1257         &FOLDERID_ChangeRemovePrograms,
1258         CSIDL_Type_Disallowed,
1259         NULL,
1260         NULL
1261     },
1262     { /* 0x42 */
1263         &FOLDERID_ConflictFolder,
1264         CSIDL_Type_Disallowed,
1265         NULL,
1266         NULL
1267     },
1268     { /* 0x43 */
1269         &FOLDERID_Contacts,
1270         CSIDL_Type_User,
1271         ContactsW,
1272         ContactsW
1273     },
1274     { /* 0x44 */
1275         &FOLDERID_DeviceMetadataStore,
1276         CSIDL_Type_Disallowed, /* FIXME */
1277         NULL,
1278         NULL
1279     },
1280     { /* 0x45 */
1281         &GUID_NULL,
1282         CSIDL_Type_User,
1283         NULL,
1284         DocumentsW
1285     },
1286     { /* 0x46 */
1287         &FOLDERID_DocumentsLibrary,
1288         CSIDL_Type_Disallowed, /* FIXME */
1289         NULL,
1290         NULL
1291     },
1292     { /* 0x47 */
1293         &FOLDERID_Downloads,
1294         CSIDL_Type_User,
1295         NULL,
1296         DownloadsW
1297     },
1298     { /* 0x48 */
1299         &FOLDERID_Games,
1300         CSIDL_Type_Disallowed,
1301         NULL,
1302         NULL
1303     },
1304     { /* 0x49 */
1305         &FOLDERID_GameTasks,
1306         CSIDL_Type_Disallowed, /* FIXME */
1307         NULL,
1308         NULL
1309     },
1310     { /* 0x4a */
1311         &FOLDERID_HomeGroup,
1312         CSIDL_Type_Disallowed,
1313         NULL,
1314         NULL
1315     },
1316     { /* 0x4b */
1317         &FOLDERID_ImplicitAppShortcuts,
1318         CSIDL_Type_Disallowed, /* FIXME */
1319         NULL,
1320         NULL
1321     },
1322     { /* 0x4c */
1323         &FOLDERID_Libraries,
1324         CSIDL_Type_Disallowed, /* FIXME */
1325         NULL,
1326         NULL
1327     },
1328     { /* 0x4d */
1329         &FOLDERID_Links,
1330         CSIDL_Type_User,
1331         NULL,
1332         LinksW
1333     },
1334     { /* 0x4e */
1335         &FOLDERID_LocalAppDataLow,
1336         CSIDL_Type_User,
1337         NULL,
1338         AppData_LocalLowW
1339     },
1340     { /* 0x4f */
1341         &FOLDERID_MusicLibrary,
1342         CSIDL_Type_Disallowed, /* FIXME */
1343         NULL,
1344         NULL
1345     },
1346     { /* 0x50 */
1347         &FOLDERID_OriginalImages,
1348         CSIDL_Type_Disallowed, /* FIXME */
1349         NULL,
1350         NULL
1351     },
1352     { /* 0x51 */
1353         &FOLDERID_PhotoAlbums,
1354         CSIDL_Type_User,
1355         NULL,
1356         Pictures_Slide_ShowsW
1357     },
1358     { /* 0x52 */
1359         &FOLDERID_PicturesLibrary,
1360         CSIDL_Type_Disallowed, /* FIXME */
1361         NULL,
1362         NULL
1363     },
1364     { /* 0x53 */
1365         &FOLDERID_Playlists,
1366         CSIDL_Type_User,
1367         NULL,
1368         Music_PlaylistsW
1369     },
1370     { /* 0x54 */
1371         &FOLDERID_ProgramFilesX64,
1372         CSIDL_Type_NonExistent,
1373         NULL,
1374         NULL
1375     },
1376     { /* 0x55 */
1377         &FOLDERID_ProgramFilesCommonX64,
1378         CSIDL_Type_NonExistent,
1379         NULL,
1380         NULL
1381     },
1382     { /* 0x56 */
1383         &FOLDERID_Public,
1384         CSIDL_Type_CurrVer, /* FIXME */
1385         NULL,
1386         UsersPublicW
1387     },
1388     { /* 0x57 */
1389         &FOLDERID_PublicDownloads,
1390         CSIDL_Type_AllUsers,
1391         NULL,
1392         DownloadsW
1393     },
1394     { /* 0x58 */
1395         &FOLDERID_PublicGameTasks,
1396         CSIDL_Type_AllUsers,
1397         NULL,
1398         Microsoft_Windows_GameExplorerW
1399     },
1400     { /* 0x59 */
1401         &FOLDERID_PublicLibraries,
1402         CSIDL_Type_AllUsers,
1403         NULL,
1404         Microsoft_Windows_LibrariesW
1405     },
1406     { /* 0x5a */
1407         &FOLDERID_PublicRingtones,
1408         CSIDL_Type_AllUsers,
1409         NULL,
1410         Microsoft_Windows_RingtonesW
1411     },
1412     { /* 0x5b */
1413         &FOLDERID_QuickLaunch,
1414         CSIDL_Type_Disallowed, /* FIXME */
1415         NULL,
1416         NULL
1417     },
1418     { /* 0x5c */
1419         &FOLDERID_RecordedTVLibrary,
1420         CSIDL_Type_Disallowed, /* FIXME */
1421         NULL,
1422         NULL
1423     },
1424     { /* 0x5d */
1425         &FOLDERID_Ringtones,
1426         CSIDL_Type_Disallowed, /* FIXME */
1427         NULL,
1428         NULL
1429     },
1430     { /* 0x5e */
1431         &FOLDERID_SampleMusic,
1432         CSIDL_Type_AllUsers,
1433         NULL,
1434         Music_Sample_MusicW
1435     },
1436     { /* 0x5f */
1437         &FOLDERID_SamplePictures,
1438         CSIDL_Type_AllUsers,
1439         NULL,
1440         Pictures_Sample_PicturesW
1441     },
1442     { /* 0x60 */
1443         &FOLDERID_SamplePlaylists,
1444         CSIDL_Type_AllUsers,
1445         NULL,
1446         Music_Sample_PlaylistsW
1447     },
1448     { /* 0x61 */
1449         &FOLDERID_SampleVideos,
1450         CSIDL_Type_AllUsers,
1451         NULL,
1452         Videos_Sample_VideosW
1453     },
1454     { /* 0x62 */
1455         &FOLDERID_SavedGames,
1456         CSIDL_Type_User,
1457         NULL,
1458         Saved_GamesW
1459     },
1460     { /* 0x63 */
1461         &FOLDERID_SavedSearches,
1462         CSIDL_Type_User,
1463         NULL,
1464         SearchesW
1465     },
1466     { /* 0x64 */
1467         &FOLDERID_SEARCH_CSC,
1468         CSIDL_Type_Disallowed,
1469         NULL,
1470         NULL
1471     },
1472     { /* 0x65 */
1473         &FOLDERID_SEARCH_MAPI,
1474         CSIDL_Type_Disallowed,
1475         NULL,
1476         NULL
1477     },
1478     { /* 0x66 */
1479         &FOLDERID_SearchHome,
1480         CSIDL_Type_Disallowed,
1481         NULL,
1482         NULL
1483     },
1484     { /* 0x67 */
1485         &FOLDERID_SidebarDefaultParts,
1486         CSIDL_Type_Disallowed, /* FIXME */
1487         NULL,
1488         NULL
1489     },
1490     { /* 0x68 */
1491         &FOLDERID_SidebarParts,
1492         CSIDL_Type_Disallowed, /* FIXME */
1493         NULL,
1494         NULL
1495     },
1496     { /* 0x69 */
1497         &FOLDERID_SyncManagerFolder,
1498         CSIDL_Type_Disallowed,
1499         NULL,
1500         NULL
1501     },
1502     { /* 0x6a */
1503         &FOLDERID_SyncResultsFolder,
1504         CSIDL_Type_Disallowed,
1505         NULL,
1506         NULL
1507     },
1508     { /* 0x6b */
1509         &FOLDERID_SyncSetupFolder,
1510         CSIDL_Type_Disallowed,
1511         NULL,
1512         NULL
1513     },
1514     { /* 0x6c */
1515         &FOLDERID_UserPinned,
1516         CSIDL_Type_Disallowed, /* FIXME */
1517         NULL,
1518         NULL
1519     },
1520     { /* 0x6d */
1521         &FOLDERID_UserProfiles,
1522         CSIDL_Type_CurrVer,
1523         UsersW,
1524         UsersW
1525     },
1526     { /* 0x6e */
1527         &FOLDERID_UserProgramFiles,
1528         CSIDL_Type_Disallowed, /* FIXME */
1529         NULL,
1530         NULL
1531     },
1532     { /* 0x6f */
1533         &FOLDERID_UserProgramFilesCommon,
1534         CSIDL_Type_Disallowed, /* FIXME */
1535         NULL,
1536         NULL
1537     },
1538     { /* 0x70 */
1539         &FOLDERID_UsersFiles,
1540         CSIDL_Type_Disallowed,
1541         NULL,
1542         NULL
1543     },
1544     { /* 0x71 */
1545         &FOLDERID_UsersLibraries,
1546         CSIDL_Type_Disallowed,
1547         NULL,
1548         NULL
1549     },
1550     { /* 0x72 */
1551         &FOLDERID_VideosLibrary,
1552         CSIDL_Type_Disallowed, /* FIXME */
1553         NULL,
1554         NULL
1555     }
1556 };
1557
1558 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest);
1559
1560 /* Gets the value named value from the registry key
1561  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
1562  * (or from rootKey\userPrefix\... if userPrefix is not NULL) into path, which
1563  * is assumed to be MAX_PATH WCHARs in length.
1564  * If it exists, expands the value and writes the expanded value to
1565  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
1566  * Returns successful error code if the value was retrieved from the registry,
1567  * and a failure otherwise.
1568  */
1569 static HRESULT _SHGetUserShellFolderPath(HKEY rootKey, LPCWSTR userPrefix,
1570  LPCWSTR value, LPWSTR path)
1571 {
1572     HRESULT hr;
1573     WCHAR shellFolderPath[MAX_PATH], userShellFolderPath[MAX_PATH];
1574     LPCWSTR pShellFolderPath, pUserShellFolderPath;
1575     DWORD dwType, dwPathLen = MAX_PATH;
1576     HKEY userShellFolderKey, shellFolderKey;
1577
1578     TRACE("%p,%s,%s,%p\n",rootKey, debugstr_w(userPrefix), debugstr_w(value),
1579      path);
1580
1581     if (userPrefix)
1582     {
1583         strcpyW(shellFolderPath, userPrefix);
1584         PathAddBackslashW(shellFolderPath);
1585         strcatW(shellFolderPath, szSHFolders);
1586         pShellFolderPath = shellFolderPath;
1587         strcpyW(userShellFolderPath, userPrefix);
1588         PathAddBackslashW(userShellFolderPath);
1589         strcatW(userShellFolderPath, szSHUserFolders);
1590         pUserShellFolderPath = userShellFolderPath;
1591     }
1592     else
1593     {
1594         pUserShellFolderPath = szSHUserFolders;
1595         pShellFolderPath = szSHFolders;
1596     }
1597
1598     if (RegCreateKeyW(rootKey, pShellFolderPath, &shellFolderKey))
1599     {
1600         TRACE("Failed to create %s\n", debugstr_w(pShellFolderPath));
1601         return E_FAIL;
1602     }
1603     if (RegCreateKeyW(rootKey, pUserShellFolderPath, &userShellFolderKey))
1604     {
1605         TRACE("Failed to create %s\n",
1606          debugstr_w(pUserShellFolderPath));
1607         RegCloseKey(shellFolderKey);
1608         return E_FAIL;
1609     }
1610
1611     if (!RegQueryValueExW(userShellFolderKey, value, NULL, &dwType,
1612      (LPBYTE)path, &dwPathLen) && (dwType == REG_EXPAND_SZ || dwType == REG_SZ))
1613     {
1614         LONG ret;
1615
1616         path[dwPathLen / sizeof(WCHAR)] = '\0';
1617         if (dwType == REG_EXPAND_SZ && path[0] == '%')
1618         {
1619             WCHAR szTemp[MAX_PATH];
1620
1621             _SHExpandEnvironmentStrings(path, szTemp);
1622             lstrcpynW(path, szTemp, MAX_PATH);
1623         }
1624         ret = RegSetValueExW(shellFolderKey, value, 0, REG_SZ, (LPBYTE)path,
1625          (strlenW(path) + 1) * sizeof(WCHAR));
1626         if (ret != ERROR_SUCCESS)
1627             hr = HRESULT_FROM_WIN32(ret);
1628         else
1629             hr = S_OK;
1630     }
1631     else
1632         hr = E_FAIL;
1633     RegCloseKey(shellFolderKey);
1634     RegCloseKey(userShellFolderKey);
1635     TRACE("returning 0x%08x\n", hr);
1636     return hr;
1637 }
1638
1639 /* Gets a 'semi-expanded' default value of the CSIDL with index folder into
1640  * pszPath, based on the entries in CSIDL_Data.  By semi-expanded, I mean:
1641  * - The entry's szDefaultPath may be either a string value or an integer
1642  *   resource identifier.  In the latter case, the string value of the resource
1643  *   is written.
1644  * - Depending on the entry's type, the path may begin with an (unexpanded)
1645  *   environment variable name.  The caller is responsible for expanding
1646  *   environment strings if so desired.
1647  *   The types that are prepended with environment variables are:
1648  *   CSIDL_Type_User:     %USERPROFILE%
1649  *   CSIDL_Type_AllUsers: %ALLUSERSPROFILE%
1650  *   CSIDL_Type_CurrVer:  %SystemDrive%
1651  *   (Others might make sense too, but as yet are unneeded.)
1652  */
1653 static HRESULT _SHGetDefaultValue(BYTE folder, LPWSTR pszPath)
1654 {
1655     HRESULT hr;
1656     WCHAR resourcePath[MAX_PATH];
1657     LPCWSTR pDefaultPath = NULL;
1658
1659     TRACE("0x%02x,%p\n", folder, pszPath);
1660
1661     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1662         return E_INVALIDARG;
1663     if (!pszPath)
1664         return E_INVALIDARG;
1665
1666     if (!is_win64)
1667     {
1668         BOOL is_wow64;
1669
1670         switch (folder)
1671         {
1672         case CSIDL_PROGRAM_FILES:
1673         case CSIDL_PROGRAM_FILESX86:
1674             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1675             folder = is_wow64 ? CSIDL_PROGRAM_FILESX86 : CSIDL_PROGRAM_FILES;
1676             break;
1677         case CSIDL_PROGRAM_FILES_COMMON:
1678         case CSIDL_PROGRAM_FILES_COMMONX86:
1679             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1680             folder = is_wow64 ? CSIDL_PROGRAM_FILES_COMMONX86 : CSIDL_PROGRAM_FILES_COMMON;
1681             break;
1682         }
1683     }
1684
1685     if (CSIDL_Data[folder].szDefaultPath &&
1686      IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath))
1687     {
1688         if (LoadStringW(shell32_hInstance,
1689          LOWORD(CSIDL_Data[folder].szDefaultPath), resourcePath, MAX_PATH))
1690         {
1691             hr = S_OK;
1692             pDefaultPath = resourcePath;
1693         }
1694         else
1695         {
1696             FIXME("(%d,%s), LoadString failed, missing translation?\n", folder,
1697              debugstr_w(pszPath));
1698             hr = E_FAIL;
1699         }
1700     }
1701     else
1702     {
1703         hr = S_OK;
1704         pDefaultPath = CSIDL_Data[folder].szDefaultPath;
1705     }
1706     if (SUCCEEDED(hr))
1707     {
1708         switch (CSIDL_Data[folder].type)
1709         {
1710             case CSIDL_Type_User:
1711                 strcpyW(pszPath, UserProfileW);
1712                 break;
1713             case CSIDL_Type_AllUsers:
1714                 strcpyW(pszPath, AllUsersProfileW);
1715                 break;
1716             case CSIDL_Type_CurrVer:
1717                 strcpyW(pszPath, SystemDriveW);
1718                 break;
1719             default:
1720                 ; /* no corresponding env. var, do nothing */
1721         }
1722         if (pDefaultPath)
1723         {
1724             PathAddBackslashW(pszPath);
1725             strcatW(pszPath, pDefaultPath);
1726         }
1727     }
1728     TRACE("returning 0x%08x\n", hr);
1729     return hr;
1730 }
1731
1732 /* Gets the (unexpanded) value of the folder with index folder into pszPath.
1733  * The folder's type is assumed to be CSIDL_Type_CurrVer.  Its default value
1734  * can be overridden in the HKLM\\szCurrentVersion key.
1735  * If dwFlags has SHGFP_TYPE_DEFAULT set or if the value isn't overridden in
1736  * the registry, uses _SHGetDefaultValue to get the value.
1737  */
1738 static HRESULT _SHGetCurrentVersionPath(DWORD dwFlags, BYTE folder,
1739  LPWSTR pszPath)
1740 {
1741     HRESULT hr;
1742
1743     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1744
1745     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1746         return E_INVALIDARG;
1747     if (CSIDL_Data[folder].type != CSIDL_Type_CurrVer)
1748         return E_INVALIDARG;
1749     if (!pszPath)
1750         return E_INVALIDARG;
1751
1752     if (dwFlags & SHGFP_TYPE_DEFAULT)
1753         hr = _SHGetDefaultValue(folder, pszPath);
1754     else
1755     {
1756         HKEY hKey;
1757
1758         if (RegCreateKeyW(HKEY_LOCAL_MACHINE, szCurrentVersion, &hKey))
1759             hr = E_FAIL;
1760         else
1761         {
1762             DWORD dwType, dwPathLen = MAX_PATH * sizeof(WCHAR);
1763
1764             if (RegQueryValueExW(hKey, CSIDL_Data[folder].szValueName, NULL,
1765              &dwType, (LPBYTE)pszPath, &dwPathLen) ||
1766              (dwType != REG_SZ && dwType != REG_EXPAND_SZ))
1767             {
1768                 hr = _SHGetDefaultValue(folder, pszPath);
1769                 dwType = REG_EXPAND_SZ;
1770                 switch (folder)
1771                 {
1772                 case CSIDL_PROGRAM_FILESX86:
1773                 case CSIDL_PROGRAM_FILES_COMMONX86:
1774                     /* these two should never be set on 32-bit setups */
1775                     if (!is_win64)
1776                     {
1777                         BOOL is_wow64;
1778                         IsWow64Process( GetCurrentProcess(), &is_wow64 );
1779                         if (!is_wow64) break;
1780                     }
1781                     /* fall through */
1782                 default:
1783                     RegSetValueExW(hKey, CSIDL_Data[folder].szValueName, 0, dwType,
1784                                    (LPBYTE)pszPath, (strlenW(pszPath)+1)*sizeof(WCHAR));
1785                 }
1786             }
1787             else
1788             {
1789                 pszPath[dwPathLen / sizeof(WCHAR)] = '\0';
1790                 hr = S_OK;
1791             }
1792             RegCloseKey(hKey);
1793         }
1794     }
1795     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1796     return hr;
1797 }
1798
1799 static LPWSTR _GetUserSidStringFromToken(HANDLE Token)
1800 {
1801     char InfoBuffer[64];
1802     PTOKEN_USER UserInfo;
1803     DWORD InfoSize;
1804     LPWSTR SidStr;
1805
1806     UserInfo = (PTOKEN_USER) InfoBuffer;
1807     if (! GetTokenInformation(Token, TokenUser, InfoBuffer, sizeof(InfoBuffer),
1808                               &InfoSize))
1809     {
1810         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1811             return NULL;
1812         UserInfo = HeapAlloc(GetProcessHeap(), 0, InfoSize);
1813         if (UserInfo == NULL)
1814             return NULL;
1815         if (! GetTokenInformation(Token, TokenUser, UserInfo, InfoSize,
1816                                   &InfoSize))
1817         {
1818             HeapFree(GetProcessHeap(), 0, UserInfo);
1819             return NULL;
1820         }
1821     }
1822
1823     if (! ConvertSidToStringSidW(UserInfo->User.Sid, &SidStr))
1824         SidStr = NULL;
1825
1826     if (UserInfo != (PTOKEN_USER) InfoBuffer)
1827         HeapFree(GetProcessHeap(), 0, UserInfo);
1828
1829     return SidStr;
1830 }
1831
1832 /* Gets the user's path (unexpanded) for the CSIDL with index folder:
1833  * If SHGFP_TYPE_DEFAULT is set, calls _SHGetDefaultValue for it.  Otherwise
1834  * calls _SHGetUserShellFolderPath for it.  Where it looks depends on hToken:
1835  * - if hToken is -1, looks in HKEY_USERS\.Default
1836  * - otherwise looks first in HKEY_CURRENT_USER, followed by HKEY_LOCAL_MACHINE
1837  *   if HKEY_CURRENT_USER doesn't contain any entries.  If both fail, finally
1838  *   calls _SHGetDefaultValue for it.
1839  */
1840 static HRESULT _SHGetUserProfilePath(HANDLE hToken, DWORD dwFlags, BYTE folder,
1841  LPWSTR pszPath)
1842 {
1843     HRESULT hr;
1844
1845     TRACE("%p,0x%08x,0x%02x,%p\n", hToken, dwFlags, folder, pszPath);
1846
1847     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1848         return E_INVALIDARG;
1849     if (CSIDL_Data[folder].type != CSIDL_Type_User)
1850         return E_INVALIDARG;
1851     if (!pszPath)
1852         return E_INVALIDARG;
1853
1854     if (dwFlags & SHGFP_TYPE_DEFAULT)
1855     {
1856         if (hToken != NULL && hToken != (HANDLE)-1)
1857         {
1858             FIXME("unsupported for user other than current or default\n");
1859             return E_FAIL;
1860         }
1861         hr = _SHGetDefaultValue(folder, pszPath);
1862     }
1863     else
1864     {
1865         LPCWSTR userPrefix = NULL;
1866         HKEY hRootKey;
1867
1868         if (hToken == (HANDLE)-1)
1869         {
1870             hRootKey = HKEY_USERS;
1871             userPrefix = DefaultW;
1872         }
1873         else if (hToken == NULL)
1874             hRootKey = HKEY_CURRENT_USER;
1875         else
1876         {
1877             hRootKey = HKEY_USERS;
1878             userPrefix = _GetUserSidStringFromToken(hToken);
1879             if (userPrefix == NULL)
1880             {
1881                 hr = E_FAIL;
1882                 goto error;
1883             }
1884         }
1885         hr = _SHGetUserShellFolderPath(hRootKey, userPrefix,
1886          CSIDL_Data[folder].szValueName, pszPath);
1887         if (FAILED(hr) && hRootKey != HKEY_LOCAL_MACHINE)
1888             hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1889              CSIDL_Data[folder].szValueName, pszPath);
1890         if (FAILED(hr))
1891             hr = _SHGetDefaultValue(folder, pszPath);
1892         if (userPrefix != NULL && userPrefix != DefaultW)
1893             LocalFree((HLOCAL) userPrefix);
1894     }
1895 error:
1896     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1897     return hr;
1898 }
1899
1900 /* Gets the (unexpanded) path for the CSIDL with index folder.  If dwFlags has
1901  * SHGFP_TYPE_DEFAULT set, calls _SHGetDefaultValue.  Otherwise calls
1902  * _SHGetUserShellFolderPath for it, looking only in HKEY_LOCAL_MACHINE.
1903  * If this fails, falls back to _SHGetDefaultValue.
1904  */
1905 static HRESULT _SHGetAllUsersProfilePath(DWORD dwFlags, BYTE folder,
1906  LPWSTR pszPath)
1907 {
1908     HRESULT hr;
1909
1910     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1911
1912     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1913         return E_INVALIDARG;
1914     if (CSIDL_Data[folder].type != CSIDL_Type_AllUsers)
1915         return E_INVALIDARG;
1916     if (!pszPath)
1917         return E_INVALIDARG;
1918
1919     if (dwFlags & SHGFP_TYPE_DEFAULT)
1920         hr = _SHGetDefaultValue(folder, pszPath);
1921     else
1922     {
1923         hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1924          CSIDL_Data[folder].szValueName, pszPath);
1925         if (FAILED(hr))
1926             hr = _SHGetDefaultValue(folder, pszPath);
1927     }
1928     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1929     return hr;
1930 }
1931
1932 static HRESULT _SHOpenProfilesKey(PHKEY pKey)
1933 {
1934     LONG lRet;
1935     DWORD disp;
1936
1937     lRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ProfileListW, 0, NULL, 0,
1938      KEY_ALL_ACCESS, NULL, pKey, &disp);
1939     return HRESULT_FROM_WIN32(lRet);
1940 }
1941
1942 /* Reads the value named szValueName from the key profilesKey (assumed to be
1943  * opened by _SHOpenProfilesKey) into szValue, which is assumed to be MAX_PATH
1944  * WCHARs in length.  If it doesn't exist, returns szDefault (and saves
1945  * szDefault to the registry).
1946  */
1947 static HRESULT _SHGetProfilesValue(HKEY profilesKey, LPCWSTR szValueName,
1948  LPWSTR szValue, LPCWSTR szDefault)
1949 {
1950     HRESULT hr;
1951     DWORD type, dwPathLen = MAX_PATH * sizeof(WCHAR);
1952     LONG lRet;
1953
1954     TRACE("%p,%s,%p,%s\n", profilesKey, debugstr_w(szValueName), szValue,
1955      debugstr_w(szDefault));
1956     lRet = RegQueryValueExW(profilesKey, szValueName, NULL, &type,
1957      (LPBYTE)szValue, &dwPathLen);
1958     if (!lRet && (type == REG_SZ || type == REG_EXPAND_SZ) && dwPathLen
1959      && *szValue)
1960     {
1961         dwPathLen /= sizeof(WCHAR);
1962         szValue[dwPathLen] = '\0';
1963         hr = S_OK;
1964     }
1965     else
1966     {
1967         /* Missing or invalid value, set a default */
1968         lstrcpynW(szValue, szDefault, MAX_PATH);
1969         TRACE("Setting missing value %s to %s\n", debugstr_w(szValueName),
1970                                                   debugstr_w(szValue));
1971         lRet = RegSetValueExW(profilesKey, szValueName, 0, REG_EXPAND_SZ,
1972                               (LPBYTE)szValue,
1973                               (strlenW(szValue) + 1) * sizeof(WCHAR));
1974         if (lRet)
1975             hr = HRESULT_FROM_WIN32(lRet);
1976         else
1977             hr = S_OK;
1978     }
1979     TRACE("returning 0x%08x (output value is %s)\n", hr, debugstr_w(szValue));
1980     return hr;
1981 }
1982
1983 /* Attempts to expand environment variables from szSrc into szDest, which is
1984  * assumed to be MAX_PATH characters in length.  Before referring to the
1985  * environment, handles a few variables directly, because the environment
1986  * variables may not be set when this is called (as during Wine's installation
1987  * when default values are being written to the registry).
1988  * The directly handled environment variables, and their source, are:
1989  * - ALLUSERSPROFILE, USERPROFILE: reads from the registry
1990  * - SystemDrive: uses GetSystemDirectoryW and uses the drive portion of its
1991  *   path
1992  * If one of the directly handled environment variables is expanded, only
1993  * expands a single variable, and only in the beginning of szSrc.
1994  */
1995 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest)
1996 {
1997     HRESULT hr;
1998     WCHAR szTemp[MAX_PATH], szProfilesPrefix[MAX_PATH] = { 0 };
1999     HKEY key = NULL;
2000
2001     TRACE("%s, %p\n", debugstr_w(szSrc), szDest);
2002
2003     if (!szSrc || !szDest) return E_INVALIDARG;
2004
2005     /* short-circuit if there's nothing to expand */
2006     if (szSrc[0] != '%')
2007     {
2008         strcpyW(szDest, szSrc);
2009         hr = S_OK;
2010         goto end;
2011     }
2012     /* Get the profile prefix, we'll probably be needing it */
2013     hr = _SHOpenProfilesKey(&key);
2014     if (SUCCEEDED(hr))
2015     {
2016         WCHAR def_val[MAX_PATH];
2017
2018         /* get the system drive */
2019         GetSystemDirectoryW(def_val, MAX_PATH);
2020         if (def_val[1] == ':') strcpyW( def_val + 3, szDefaultProfileDirW );
2021         else FIXME("non-drive system paths unsupported\n");
2022
2023         hr = _SHGetProfilesValue(key, ProfilesDirectoryW, szProfilesPrefix, def_val );
2024     }
2025
2026     *szDest = 0;
2027     strcpyW(szTemp, szSrc);
2028     while (SUCCEEDED(hr) && szTemp[0] == '%')
2029     {
2030         if (!strncmpiW(szTemp, AllUsersProfileW, strlenW(AllUsersProfileW)))
2031         {
2032             WCHAR szAllUsers[MAX_PATH];
2033
2034             strcpyW(szDest, szProfilesPrefix);
2035             hr = _SHGetProfilesValue(key, AllUsersProfileValueW,
2036              szAllUsers, AllUsersW);
2037             PathAppendW(szDest, szAllUsers);
2038             PathAppendW(szDest, szTemp + strlenW(AllUsersProfileW));
2039         }
2040         else if (!strncmpiW(szTemp, UserProfileW, strlenW(UserProfileW)))
2041         {
2042             WCHAR userName[MAX_PATH];
2043             DWORD userLen = MAX_PATH;
2044
2045             strcpyW(szDest, szProfilesPrefix);
2046             GetUserNameW(userName, &userLen);
2047             PathAppendW(szDest, userName);
2048             PathAppendW(szDest, szTemp + strlenW(UserProfileW));
2049         }
2050         else if (!strncmpiW(szTemp, SystemDriveW, strlenW(SystemDriveW)))
2051         {
2052             GetSystemDirectoryW(szDest, MAX_PATH);
2053             if (szDest[1] != ':')
2054             {
2055                 FIXME("non-drive system paths unsupported\n");
2056                 hr = E_FAIL;
2057             }
2058             else
2059             {
2060                 strcpyW(szDest + 3, szTemp + strlenW(SystemDriveW) + 1);
2061                 hr = S_OK;
2062             }
2063         }
2064         else
2065         {
2066             DWORD ret = ExpandEnvironmentStringsW(szSrc, szDest, MAX_PATH);
2067
2068             if (ret > MAX_PATH)
2069                 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
2070             else if (ret == 0)
2071                 hr = HRESULT_FROM_WIN32(GetLastError());
2072             else
2073                 hr = S_OK;
2074         }
2075         if (SUCCEEDED(hr) && szDest[0] == '%')
2076             strcpyW(szTemp, szDest);
2077         else
2078         {
2079             /* terminate loop */
2080             szTemp[0] = '\0';
2081         }
2082     }
2083 end:
2084     if (key)
2085         RegCloseKey(key);
2086     TRACE("returning 0x%08x (input was %s, output is %s)\n", hr,
2087      debugstr_w(szSrc), debugstr_w(szDest));
2088     return hr;
2089 }
2090
2091 /*************************************************************************
2092  * SHGetFolderPathW                     [SHELL32.@]
2093  *
2094  * Convert nFolder to path.  
2095  *
2096  * RETURNS
2097  *  Success: S_OK
2098  *  Failure: standard HRESULT error codes.
2099  *
2100  * NOTES
2101  * Most values can be overridden in either
2102  * HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
2103  * or in the same location in HKLM.
2104  * The "Shell Folders" registry key was used in NT4 and earlier systems.
2105  * Beginning with Windows 2000, the "User Shell Folders" key is used, so
2106  * changes made to it are made to the former key too.  This synchronization is
2107  * done on-demand: not until someone requests the value of one of these paths
2108  * (by calling one of the SHGet functions) is the value synchronized.
2109  * Furthermore, the HKCU paths take precedence over the HKLM paths.
2110  */
2111 HRESULT WINAPI SHGetFolderPathW(
2112         HWND hwndOwner,    /* [I] owner window */
2113         int nFolder,       /* [I] CSIDL identifying the folder */
2114         HANDLE hToken,     /* [I] access token */
2115         DWORD dwFlags,     /* [I] which path to return */
2116         LPWSTR pszPath)    /* [O] converted path */
2117 {
2118     HRESULT hr =  SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, NULL, pszPath);
2119     if(HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
2120         hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
2121     return hr;
2122 }
2123
2124 HRESULT WINAPI SHGetFolderPathAndSubDirA(
2125         HWND hwndOwner,    /* [I] owner window */
2126         int nFolder,       /* [I] CSIDL identifying the folder */
2127         HANDLE hToken,     /* [I] access token */
2128         DWORD dwFlags,     /* [I] which path to return */
2129         LPCSTR pszSubPath, /* [I] sub directory of the specified folder */
2130         LPSTR pszPath)     /* [O] converted path */
2131 {
2132     int length;
2133     HRESULT hr = S_OK;
2134     LPWSTR pszSubPathW = NULL;
2135     LPWSTR pszPathW = NULL;
2136     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2137
2138     if(pszPath) {
2139         pszPathW = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
2140         if(!pszPathW) {
2141             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2142             goto cleanup;
2143         }
2144     }
2145     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2146
2147     /* SHGetFolderPathAndSubDirW does not distinguish if pszSubPath isn't
2148      * set (null), or an empty string.therefore call it without the parameter set
2149      * if pszSubPath is an empty string
2150      */
2151     if (pszSubPath && pszSubPath[0]) {
2152         length = MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, NULL, 0);
2153         pszSubPathW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR));
2154         if(!pszSubPathW) {
2155             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2156             goto cleanup;
2157         }
2158         MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, pszSubPathW, length);
2159     }
2160
2161     hr = SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, pszSubPathW, pszPathW);
2162
2163     if (SUCCEEDED(hr) && pszPath)
2164         WideCharToMultiByte(CP_ACP, 0, pszPathW, -1, pszPath, MAX_PATH, NULL, NULL);
2165
2166 cleanup:
2167     HeapFree(GetProcessHeap(), 0, pszPathW);
2168     HeapFree(GetProcessHeap(), 0, pszSubPathW);
2169     return hr;
2170 }
2171
2172 /*************************************************************************
2173  * SHGetFolderPathAndSubDirW            [SHELL32.@]
2174  */
2175 HRESULT WINAPI SHGetFolderPathAndSubDirW(
2176         HWND hwndOwner,    /* [I] owner window */
2177         int nFolder,       /* [I] CSIDL identifying the folder */
2178         HANDLE hToken,     /* [I] access token */
2179         DWORD dwFlags,     /* [I] which path to return */
2180         LPCWSTR pszSubPath,/* [I] sub directory of the specified folder */
2181         LPWSTR pszPath)    /* [O] converted path */
2182 {
2183     HRESULT    hr;
2184     WCHAR      szBuildPath[MAX_PATH], szTemp[MAX_PATH];
2185     DWORD      folder = nFolder & CSIDL_FOLDER_MASK;
2186     CSIDL_Type type;
2187     int        ret;
2188     
2189     TRACE("%p,%p,nFolder=0x%04x,%s\n", hwndOwner,pszPath,nFolder,debugstr_w(pszSubPath));
2190
2191     /* Windows always NULL-terminates the resulting path regardless of success
2192      * or failure, so do so first
2193      */
2194     if (pszPath)
2195         *pszPath = '\0';
2196
2197     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
2198         return E_INVALIDARG;
2199     if ((SHGFP_TYPE_CURRENT != dwFlags) && (SHGFP_TYPE_DEFAULT != dwFlags))
2200         return E_INVALIDARG;
2201     szTemp[0] = 0;
2202     type = CSIDL_Data[folder].type;
2203     switch (type)
2204     {
2205         case CSIDL_Type_Disallowed:
2206             hr = E_INVALIDARG;
2207             break;
2208         case CSIDL_Type_NonExistent:
2209             hr = S_FALSE;
2210             break;
2211         case CSIDL_Type_WindowsPath:
2212             GetWindowsDirectoryW(szTemp, MAX_PATH);
2213             if (CSIDL_Data[folder].szDefaultPath &&
2214              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2215              *CSIDL_Data[folder].szDefaultPath)
2216             {
2217                 PathAddBackslashW(szTemp);
2218                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2219             }
2220             hr = S_OK;
2221             break;
2222         case CSIDL_Type_SystemPath:
2223             GetSystemDirectoryW(szTemp, MAX_PATH);
2224             if (CSIDL_Data[folder].szDefaultPath &&
2225              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2226              *CSIDL_Data[folder].szDefaultPath)
2227             {
2228                 PathAddBackslashW(szTemp);
2229                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2230             }
2231             hr = S_OK;
2232             break;
2233         case CSIDL_Type_SystemX86Path:
2234             if (!GetSystemWow64DirectoryW(szTemp, MAX_PATH)) GetSystemDirectoryW(szTemp, MAX_PATH);
2235             if (CSIDL_Data[folder].szDefaultPath &&
2236              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2237              *CSIDL_Data[folder].szDefaultPath)
2238             {
2239                 PathAddBackslashW(szTemp);
2240                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2241             }
2242             hr = S_OK;
2243             break;
2244         case CSIDL_Type_CurrVer:
2245             hr = _SHGetCurrentVersionPath(dwFlags, folder, szTemp);
2246             break;
2247         case CSIDL_Type_User:
2248             hr = _SHGetUserProfilePath(hToken, dwFlags, folder, szTemp);
2249             break;
2250         case CSIDL_Type_AllUsers:
2251             hr = _SHGetAllUsersProfilePath(dwFlags, folder, szTemp);
2252             break;
2253         default:
2254             FIXME("bogus type %d, please fix\n", type);
2255             hr = E_INVALIDARG;
2256             break;
2257     }
2258
2259     /* Expand environment strings if necessary */
2260     if (*szTemp == '%')
2261         hr = _SHExpandEnvironmentStrings(szTemp, szBuildPath);
2262     else
2263         strcpyW(szBuildPath, szTemp);
2264
2265     if (FAILED(hr)) goto end;
2266
2267     if(pszSubPath) {
2268         /* make sure the new path does not exceed th bufferlength
2269          * rememebr to backslash and the termination */
2270         if(MAX_PATH < (lstrlenW(szBuildPath) + lstrlenW(pszSubPath) + 2)) {
2271             hr = HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
2272             goto end;
2273         }
2274         PathAppendW(szBuildPath, pszSubPath);
2275         PathRemoveBackslashW(szBuildPath);
2276     }
2277     /* Copy the path if it's available before we might return */
2278     if (SUCCEEDED(hr) && pszPath)
2279         strcpyW(pszPath, szBuildPath);
2280
2281     /* if we don't care about existing directories we are ready */
2282     if(nFolder & CSIDL_FLAG_DONT_VERIFY) goto end;
2283
2284     if (PathFileExistsW(szBuildPath)) goto end;
2285
2286     /* not existing but we are not allowed to create it.  The return value
2287      * is verified against shell32 version 6.0.
2288      */
2289     if (!(nFolder & CSIDL_FLAG_CREATE))
2290     {
2291         hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
2292         goto end;
2293     }
2294
2295     /* create directory/directories */
2296     ret = SHCreateDirectoryExW(hwndOwner, szBuildPath, NULL);
2297     if (ret && ret != ERROR_ALREADY_EXISTS)
2298     {
2299         ERR("Failed to create directory %s.\n", debugstr_w(szBuildPath));
2300         hr = E_FAIL;
2301         goto end;
2302     }
2303
2304     TRACE("Created missing system directory %s\n", debugstr_w(szBuildPath));
2305 end:
2306     TRACE("returning 0x%08x (final path is %s)\n", hr, debugstr_w(szBuildPath));
2307     return hr;
2308 }
2309
2310 /*************************************************************************
2311  * SHGetFolderPathA                     [SHELL32.@]
2312  *
2313  * See SHGetFolderPathW.
2314  */
2315 HRESULT WINAPI SHGetFolderPathA(
2316         HWND hwndOwner,
2317         int nFolder,
2318         HANDLE hToken,
2319         DWORD dwFlags,
2320         LPSTR pszPath)
2321 {
2322     WCHAR szTemp[MAX_PATH];
2323     HRESULT hr;
2324
2325     TRACE("%p,%p,nFolder=0x%04x\n",hwndOwner,pszPath,nFolder);
2326
2327     if (pszPath)
2328         *pszPath = '\0';
2329     hr = SHGetFolderPathW(hwndOwner, nFolder, hToken, dwFlags, szTemp);
2330     if (SUCCEEDED(hr) && pszPath)
2331         WideCharToMultiByte(CP_ACP, 0, szTemp, -1, pszPath, MAX_PATH, NULL,
2332          NULL);
2333
2334     return hr;
2335 }
2336
2337 /* For each folder in folders, if its value has not been set in the registry,
2338  * calls _SHGetUserProfilePath or _SHGetAllUsersProfilePath (depending on the
2339  * folder's type) to get the unexpanded value first.
2340  * Writes the unexpanded value to User Shell Folders, and queries it with
2341  * SHGetFolderPathW to force the creation of the directory if it doesn't
2342  * already exist.  SHGetFolderPathW also returns the expanded value, which
2343  * this then writes to Shell Folders.
2344  */
2345 static HRESULT _SHRegisterFolders(HKEY hRootKey, HANDLE hToken,
2346  LPCWSTR szUserShellFolderPath, LPCWSTR szShellFolderPath, const UINT folders[],
2347  UINT foldersLen)
2348 {
2349     UINT i;
2350     WCHAR path[MAX_PATH];
2351     HRESULT hr = S_OK;
2352     HKEY hUserKey = NULL, hKey = NULL;
2353     DWORD dwType, dwPathLen;
2354     LONG ret;
2355
2356     TRACE("%p,%p,%s,%p,%u\n", hRootKey, hToken,
2357      debugstr_w(szUserShellFolderPath), folders, foldersLen);
2358
2359     ret = RegCreateKeyW(hRootKey, szUserShellFolderPath, &hUserKey);
2360     if (ret)
2361         hr = HRESULT_FROM_WIN32(ret);
2362     else
2363     {
2364         ret = RegCreateKeyW(hRootKey, szShellFolderPath, &hKey);
2365         if (ret)
2366             hr = HRESULT_FROM_WIN32(ret);
2367     }
2368     for (i = 0; SUCCEEDED(hr) && i < foldersLen; i++)
2369     {
2370         dwPathLen = MAX_PATH * sizeof(WCHAR);
2371         if (RegQueryValueExW(hUserKey, CSIDL_Data[folders[i]].szValueName, NULL,
2372          &dwType, (LPBYTE)path, &dwPathLen) || (dwType != REG_SZ &&
2373          dwType != REG_EXPAND_SZ))
2374         {
2375             *path = '\0';
2376             if (CSIDL_Data[folders[i]].type == CSIDL_Type_User)
2377                 _SHGetUserProfilePath(hToken, SHGFP_TYPE_DEFAULT, folders[i],
2378                  path);
2379             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_AllUsers)
2380                 _SHGetAllUsersProfilePath(SHGFP_TYPE_DEFAULT, folders[i], path);
2381             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_WindowsPath)
2382             {
2383                 GetWindowsDirectoryW(path, MAX_PATH);
2384                 if (CSIDL_Data[folders[i]].szDefaultPath &&
2385                     !IS_INTRESOURCE(CSIDL_Data[folders[i]].szDefaultPath))
2386                 {
2387                     PathAddBackslashW(path);
2388                     strcatW(path, CSIDL_Data[folders[i]].szDefaultPath);
2389                 }
2390             }
2391             else
2392                 hr = E_FAIL;
2393             if (*path)
2394             {
2395                 ret = RegSetValueExW(hUserKey,
2396                  CSIDL_Data[folders[i]].szValueName, 0, REG_EXPAND_SZ,
2397                  (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2398                 if (ret)
2399                     hr = HRESULT_FROM_WIN32(ret);
2400                 else
2401                 {
2402                     hr = SHGetFolderPathW(NULL, folders[i] | CSIDL_FLAG_CREATE,
2403                      hToken, SHGFP_TYPE_DEFAULT, path);
2404                     ret = RegSetValueExW(hKey,
2405                      CSIDL_Data[folders[i]].szValueName, 0, REG_SZ,
2406                      (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2407                     if (ret)
2408                         hr = HRESULT_FROM_WIN32(ret);
2409                 }
2410             }
2411         }
2412     }
2413     if (hUserKey)
2414         RegCloseKey(hUserKey);
2415     if (hKey)
2416         RegCloseKey(hKey);
2417
2418     TRACE("returning 0x%08x\n", hr);
2419     return hr;
2420 }
2421
2422 static HRESULT _SHRegisterUserShellFolders(BOOL bDefault)
2423 {
2424     static const UINT folders[] = {
2425      CSIDL_PROGRAMS,
2426      CSIDL_PERSONAL,
2427      CSIDL_FAVORITES,
2428      CSIDL_APPDATA,
2429      CSIDL_STARTUP,
2430      CSIDL_RECENT,
2431      CSIDL_SENDTO,
2432      CSIDL_STARTMENU,
2433      CSIDL_MYMUSIC,
2434      CSIDL_MYVIDEO,
2435      CSIDL_DESKTOPDIRECTORY,
2436      CSIDL_NETHOOD,
2437      CSIDL_TEMPLATES,
2438      CSIDL_PRINTHOOD,
2439      CSIDL_LOCAL_APPDATA,
2440      CSIDL_INTERNET_CACHE,
2441      CSIDL_COOKIES,
2442      CSIDL_HISTORY,
2443      CSIDL_MYPICTURES,
2444      CSIDL_FONTS
2445     };
2446     WCHAR userShellFolderPath[MAX_PATH], shellFolderPath[MAX_PATH];
2447     LPCWSTR pUserShellFolderPath, pShellFolderPath;
2448     HRESULT hr = S_OK;
2449     HKEY hRootKey;
2450     HANDLE hToken;
2451
2452     TRACE("%s\n", bDefault ? "TRUE" : "FALSE");
2453     if (bDefault)
2454     {
2455         hToken = (HANDLE)-1;
2456         hRootKey = HKEY_USERS;
2457         strcpyW(userShellFolderPath, DefaultW);
2458         PathAddBackslashW(userShellFolderPath);
2459         strcatW(userShellFolderPath, szSHUserFolders);
2460         pUserShellFolderPath = userShellFolderPath;
2461         strcpyW(shellFolderPath, DefaultW);
2462         PathAddBackslashW(shellFolderPath);
2463         strcatW(shellFolderPath, szSHFolders);
2464         pShellFolderPath = shellFolderPath;
2465     }
2466     else
2467     {
2468         hToken = NULL;
2469         hRootKey = HKEY_CURRENT_USER;
2470         pUserShellFolderPath = szSHUserFolders;
2471         pShellFolderPath = szSHFolders;
2472     }
2473
2474     hr = _SHRegisterFolders(hRootKey, hToken, pUserShellFolderPath,
2475      pShellFolderPath, folders, sizeof(folders) / sizeof(folders[0]));
2476     TRACE("returning 0x%08x\n", hr);
2477     return hr;
2478 }
2479
2480 static HRESULT _SHRegisterCommonShellFolders(void)
2481 {
2482     static const UINT folders[] = {
2483      CSIDL_COMMON_STARTMENU,
2484      CSIDL_COMMON_PROGRAMS,
2485      CSIDL_COMMON_STARTUP,
2486      CSIDL_COMMON_DESKTOPDIRECTORY,
2487      CSIDL_COMMON_FAVORITES,
2488      CSIDL_COMMON_APPDATA,
2489      CSIDL_COMMON_TEMPLATES,
2490      CSIDL_COMMON_DOCUMENTS,
2491      CSIDL_COMMON_ADMINTOOLS,
2492      CSIDL_COMMON_MUSIC,
2493      CSIDL_COMMON_PICTURES,
2494      CSIDL_COMMON_VIDEO,
2495     };
2496     HRESULT hr;
2497
2498     TRACE("\n");
2499     hr = _SHRegisterFolders(HKEY_LOCAL_MACHINE, NULL, szSHUserFolders,
2500      szSHFolders, folders, sizeof(folders) / sizeof(folders[0]));
2501     TRACE("returning 0x%08x\n", hr);
2502     return hr;
2503 }
2504
2505 /******************************************************************************
2506  * _SHAppendToUnixPath  [Internal]
2507  *
2508  * Helper function for _SHCreateSymbolicLinks. Appends pwszSubPath (or the 
2509  * corresponding resource, if IS_INTRESOURCE) to the unix base path 'szBasePath' 
2510  * and replaces backslashes with slashes.
2511  *
2512  * PARAMS
2513  *  szBasePath  [IO] The unix base path, which will be appended to (CP_UNXICP).
2514  *  pwszSubPath [I]  Sub-path or resource id (use MAKEINTRESOURCEW).
2515  *
2516  * RETURNS
2517  *  Success: TRUE,
2518  *  Failure: FALSE
2519  */
2520 static inline BOOL _SHAppendToUnixPath(char *szBasePath, LPCWSTR pwszSubPath) {
2521     WCHAR wszSubPath[MAX_PATH];
2522     int cLen = strlen(szBasePath);
2523     char *pBackslash;
2524
2525     if (IS_INTRESOURCE(pwszSubPath)) {
2526         if (!LoadStringW(shell32_hInstance, LOWORD(pwszSubPath), wszSubPath, MAX_PATH)) {
2527             /* Fall back to hard coded defaults. */
2528             switch (LOWORD(pwszSubPath)) {
2529                 case IDS_PERSONAL:
2530                     lstrcpyW(wszSubPath, PersonalW);
2531                     break;
2532                 case IDS_MYMUSIC:
2533                     lstrcpyW(wszSubPath, My_MusicW);
2534                     break;
2535                 case IDS_MYPICTURES:
2536                     lstrcpyW(wszSubPath, My_PicturesW);
2537                     break;
2538                 case IDS_MYVIDEOS:
2539                     lstrcpyW(wszSubPath, My_VideosW);
2540                     break;
2541                 default:
2542                     ERR("LoadString(%d) failed!\n", LOWORD(pwszSubPath));
2543                     return FALSE;
2544             }
2545         }
2546     } else {
2547         lstrcpyW(wszSubPath, pwszSubPath);
2548     }
2549  
2550     if (szBasePath[cLen-1] != '/') szBasePath[cLen++] = '/';
2551  
2552     if (!WideCharToMultiByte(CP_UNIXCP, 0, wszSubPath, -1, szBasePath + cLen,
2553                              FILENAME_MAX - cLen, NULL, NULL))
2554     {
2555         return FALSE;
2556     }
2557  
2558     pBackslash = szBasePath + cLen;
2559     while ((pBackslash = strchr(pBackslash, '\\'))) *pBackslash = '/';
2560  
2561     return TRUE;
2562 }
2563
2564 /******************************************************************************
2565  * _SHCreateSymbolicLinks  [Internal]
2566  * 
2567  * Sets up symbol links for various shell folders to point into the users home
2568  * directory. We do an educated guess about what the user would probably want:
2569  * - If there is a 'My Documents' directory in $HOME, the user probably wants
2570  *   wine's 'My Documents' to point there. Furthermore, we imply that the user
2571  *   is a Windows lover and has no problem with wine creating 'My Pictures',
2572  *   'My Music' and 'My Videos' subfolders under '$HOME/My Documents', if those
2573  *   do not already exits. We put appropriate symbolic links in place for those,
2574  *   too.
2575  * - If there is no 'My Documents' directory in $HOME, we let 'My Documents'
2576  *   point directly to $HOME. We assume the user to be a unix hacker who does not
2577  *   want wine to create anything anywhere besides the .wine directory. So, if
2578  *   there already is a 'My Music' directory in $HOME, we symlink the 'My Music'
2579  *   shell folder to it. But if not, then we check XDG_MUSIC_DIR - "well known"
2580  *   directory, and try to link to that. If that fails, then we symlink to
2581  *   $HOME directly. The same holds fo 'My Pictures' and 'My Videos'.
2582  * - The Desktop shell folder is symlinked to XDG_DESKTOP_DIR. If that does not
2583  *   exist, then we try '$HOME/Desktop'. If that does not exist, then we leave
2584  *   it alone.
2585  * ('My Music',... above in fact means LoadString(IDS_MYMUSIC))
2586  */
2587 static void _SHCreateSymbolicLinks(void)
2588 {
2589     UINT aidsMyStuff[] = { IDS_MYPICTURES, IDS_MYVIDEOS, IDS_MYMUSIC }, i;
2590     int acsidlMyStuff[] = { CSIDL_MYPICTURES, CSIDL_MYVIDEO, CSIDL_MYMUSIC };
2591     static const char * const xdg_dirs[] = { "PICTURES", "VIDEOS", "MUSIC", "DESKTOP" };
2592     static const unsigned int num = sizeof(xdg_dirs) / sizeof(xdg_dirs[0]);
2593     WCHAR wszTempPath[MAX_PATH];
2594     char szPersonalTarget[FILENAME_MAX], *pszPersonal;
2595     char szMyStuffTarget[FILENAME_MAX], *pszMyStuff;
2596     char szDesktopTarget[FILENAME_MAX], *pszDesktop;
2597     struct stat statFolder;
2598     const char *pszHome;
2599     HRESULT hr;
2600     char ** xdg_results;
2601     char * xdg_desktop_dir;
2602
2603     /* Create all necessary profile sub-dirs up to 'My Documents' and get the unix path. */
2604     hr = SHGetFolderPathW(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL,
2605                           SHGFP_TYPE_DEFAULT, wszTempPath);
2606     if (FAILED(hr)) return;
2607     pszPersonal = wine_get_unix_file_name(wszTempPath);
2608     if (!pszPersonal) return;
2609
2610     hr = XDG_UserDirLookup(xdg_dirs, num, &xdg_results);
2611     if (FAILED(hr)) xdg_results = NULL;
2612
2613     pszHome = getenv("HOME");
2614     if (pszHome && !stat(pszHome, &statFolder) && S_ISDIR(statFolder.st_mode)) {
2615         strcpy(szPersonalTarget, pszHome);
2616         if (_SHAppendToUnixPath(szPersonalTarget, MAKEINTRESOURCEW(IDS_PERSONAL)) &&
2617             !stat(szPersonalTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2618         {
2619             /* '$HOME/My Documents' exists. Create 'My Pictures', 'My Videos' and 
2620              * 'My Music' subfolders or fail silently if they already exist. */
2621             for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2622                 strcpy(szMyStuffTarget, szPersonalTarget);
2623                 if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2624                     mkdir(szMyStuffTarget, 0777);
2625             }
2626         } 
2627         else
2628         {
2629             /* '$HOME/My Documents' doesn't exists, but '$HOME' does. */ 
2630             strcpy(szPersonalTarget, pszHome);
2631         }
2632
2633         /* Replace 'My Documents' directory with a symlink of fail silently if not empty. */
2634         rmdir(pszPersonal);
2635         symlink(szPersonalTarget, pszPersonal);
2636     }
2637     else
2638     {
2639         /* '$HOME' doesn't exist. Create 'My Pictures', 'My Videos' and 'My Music' subdirs
2640          * in '%USERPROFILE%\\My Documents' or fail silently if they already exist. */
2641         strcpy(szPersonalTarget, pszPersonal);
2642         for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2643             strcpy(szMyStuffTarget, szPersonalTarget);
2644             if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2645                 mkdir(szMyStuffTarget, 0777);
2646         }
2647     }
2648
2649     /* Create symbolic links for 'My Pictures', 'My Videos' and 'My Music'. */
2650     for (i=0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2651         /* Create the current 'My Whatever' folder and get its unix path. */
2652         hr = SHGetFolderPathW(NULL, acsidlMyStuff[i]|CSIDL_FLAG_CREATE, NULL,
2653                               SHGFP_TYPE_DEFAULT, wszTempPath);
2654         if (FAILED(hr)) continue;
2655         pszMyStuff = wine_get_unix_file_name(wszTempPath);
2656         if (!pszMyStuff) continue;
2657         
2658         strcpy(szMyStuffTarget, szPersonalTarget);
2659         if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])) &&
2660             !stat(szMyStuffTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2661         {
2662             /* If there's a 'My Whatever' directory where 'My Documents' links to, link to it. */
2663             rmdir(pszMyStuff);
2664             symlink(szMyStuffTarget, pszMyStuff);
2665         } 
2666         else
2667         {
2668             rmdir(pszMyStuff);
2669             if (xdg_results && xdg_results[i])
2670             {
2671                 /* the folder specified by XDG_XXX_DIR exists, link to it. */
2672                 symlink(xdg_results[i], pszMyStuff);
2673             }
2674             else
2675             {
2676                 /* Else link to where 'My Documents' itself links to. */
2677                 symlink(szPersonalTarget, pszMyStuff);
2678             }
2679         }
2680         HeapFree(GetProcessHeap(), 0, pszMyStuff);
2681     }
2682
2683     /* Last but not least, the Desktop folder */
2684     if (pszHome)
2685         strcpy(szDesktopTarget, pszHome);
2686     else
2687         strcpy(szDesktopTarget, pszPersonal);
2688     HeapFree(GetProcessHeap(), 0, pszPersonal);
2689
2690     xdg_desktop_dir = xdg_results ? xdg_results[num - 1] : NULL;
2691     if (xdg_desktop_dir ||
2692         (_SHAppendToUnixPath(szDesktopTarget, DesktopW) &&
2693         !stat(szDesktopTarget, &statFolder) && S_ISDIR(statFolder.st_mode)))
2694     {
2695         hr = SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, NULL,
2696                               SHGFP_TYPE_DEFAULT, wszTempPath);
2697         if (SUCCEEDED(hr) && (pszDesktop = wine_get_unix_file_name(wszTempPath))) 
2698         {
2699             rmdir(pszDesktop);
2700             if (xdg_desktop_dir)
2701                 symlink(xdg_desktop_dir, pszDesktop);
2702             else
2703                 symlink(szDesktopTarget, pszDesktop);
2704             HeapFree(GetProcessHeap(), 0, pszDesktop);
2705         }
2706     }
2707
2708     /* Free resources allocated by XDG_UserDirLookup() */
2709     if (xdg_results)
2710     {
2711         for (i = 0; i < num; i++)
2712             HeapFree(GetProcessHeap(), 0, xdg_results[i]);
2713         HeapFree(GetProcessHeap(), 0, xdg_results);
2714     }
2715 }
2716
2717 /******************************************************************************
2718  * create_extra_folders  [Internal]
2719  *
2720  * Create some extra folders that don't have a standard CSIDL definition.
2721  */
2722 static HRESULT create_extra_folders(void)
2723 {
2724     static const WCHAR environW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
2725     static const WCHAR TempW[]    = {'T','e','m','p',0};
2726     static const WCHAR TEMPW[]    = {'T','E','M','P',0};
2727     static const WCHAR TMPW[]     = {'T','M','P',0};
2728     WCHAR path[MAX_PATH+5];
2729     HRESULT hr;
2730     HKEY hkey;
2731     DWORD type, size, ret;
2732
2733     ret = RegCreateKeyW( HKEY_CURRENT_USER, environW, &hkey );
2734     if (ret) return HRESULT_FROM_WIN32( ret );
2735
2736     /* FIXME: should be under AppData, but we don't want spaces in the temp path */
2737     hr = SHGetFolderPathAndSubDirW( 0, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL,
2738                                     SHGFP_TYPE_DEFAULT, TempW, path );
2739     if (SUCCEEDED(hr))
2740     {
2741         size = sizeof(path);
2742         if (RegQueryValueExW( hkey, TEMPW, NULL, &type, (LPBYTE)path, &size ))
2743             RegSetValueExW( hkey, TEMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2744         size = sizeof(path);
2745         if (RegQueryValueExW( hkey, TMPW, NULL, &type, (LPBYTE)path, &size ))
2746             RegSetValueExW( hkey, TMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2747     }
2748     RegCloseKey( hkey );
2749     return hr;
2750 }
2751
2752
2753 /******************************************************************************
2754  * set_folder_attributes
2755  *
2756  * Set the various folder attributes registry keys.
2757  */
2758 static HRESULT set_folder_attributes(void)
2759 {
2760     static const WCHAR clsidW[] = {'C','L','S','I','D','\\',0 };
2761     static const WCHAR shellfolderW[] = {'\\','S','h','e','l','l','F','o','l','d','e','r', 0 };
2762     static const WCHAR wfparsingW[] = {'W','a','n','t','s','F','O','R','P','A','R','S','I','N','G',0};
2763     static const WCHAR wfdisplayW[] = {'W','a','n','t','s','F','O','R','D','I','S','P','L','A','Y',0};
2764     static const WCHAR hideasdeleteW[] = {'H','i','d','e','A','s','D','e','l','e','t','e','P','e','r','U','s','e','r',0};
2765     static const WCHAR attributesW[] = {'A','t','t','r','i','b','u','t','e','s',0};
2766     static const WCHAR cfattributesW[] = {'C','a','l','l','F','o','r','A','t','t','r','i','b','u','t','e','s',0};
2767     static const WCHAR emptyW[] = {0};
2768
2769     static const struct
2770     {
2771         const CLSID *clsid;
2772         BOOL wfparsing : 1;
2773         BOOL wfdisplay : 1;
2774         BOOL hideasdel : 1;
2775         DWORD attr;
2776         DWORD call_for_attr;
2777     } folders[] =
2778     {
2779         { &CLSID_UnixFolder, TRUE, FALSE, FALSE },
2780         { &CLSID_UnixDosFolder, TRUE, FALSE, FALSE,
2781           SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
2782         { &CLSID_FolderShortcut, FALSE, FALSE, FALSE,
2783           SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_LINK,
2784           SFGAO_HASSUBFOLDER|SFGAO_FILESYSTEM|SFGAO_FOLDER|SFGAO_FILESYSANCESTOR },
2785         { &CLSID_MyDocuments, TRUE, FALSE, FALSE,
2786           SFGAO_FILESYSANCESTOR|SFGAO_FOLDER|SFGAO_HASSUBFOLDER, SFGAO_FILESYSTEM },
2787         { &CLSID_RecycleBin, FALSE, FALSE, FALSE,
2788           SFGAO_FOLDER|SFGAO_DROPTARGET|SFGAO_HASPROPSHEET },
2789         { &CLSID_ControlPanel, FALSE, TRUE, TRUE,
2790           SFGAO_FOLDER|SFGAO_HASSUBFOLDER }
2791     };
2792
2793     unsigned int i;
2794     WCHAR buffer[39 + (sizeof(clsidW) + sizeof(shellfolderW)) / sizeof(WCHAR)];
2795     LONG res;
2796     HKEY hkey;
2797
2798     for (i = 0; i < sizeof(folders)/sizeof(folders[0]); i++)
2799     {
2800         strcpyW( buffer, clsidW );
2801         StringFromGUID2( folders[i].clsid, buffer + strlenW(buffer), 39 );
2802         strcatW( buffer, shellfolderW );
2803         res = RegCreateKeyExW( HKEY_CLASSES_ROOT, buffer, 0, NULL, 0,
2804                                KEY_READ | KEY_WRITE, NULL, &hkey, NULL);
2805         if (res) return HRESULT_FROM_WIN32( res );
2806         if (folders[i].wfparsing)
2807             res = RegSetValueExW( hkey, wfparsingW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2808         if (folders[i].wfdisplay)
2809             res = RegSetValueExW( hkey, wfdisplayW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2810         if (folders[i].hideasdel)
2811             res = RegSetValueExW( hkey, hideasdeleteW, 0, REG_SZ, (const BYTE *)emptyW, sizeof(emptyW) );
2812         if (folders[i].attr)
2813             res = RegSetValueExW( hkey, attributesW, 0, REG_DWORD,
2814                                   (const BYTE *)&folders[i].attr, sizeof(DWORD));
2815         if (folders[i].call_for_attr)
2816             res = RegSetValueExW( hkey, cfattributesW, 0, REG_DWORD,
2817                                  (const BYTE *)&folders[i].call_for_attr, sizeof(DWORD));
2818         RegCloseKey( hkey );
2819     }
2820     return S_OK;
2821 }
2822
2823
2824 /* Register the default values in the registry, as some apps seem to depend
2825  * on their presence.  The set registered was taken from Windows XP.
2826  */
2827 HRESULT SHELL_RegisterShellFolders(void)
2828 {
2829     HRESULT hr;
2830
2831     /* Set up '$HOME' targeted symlinks for 'My Documents', 'My Pictures',
2832      * 'My Videos', 'My Music' and 'Desktop' in advance, so that the
2833      * _SHRegister*ShellFolders() functions will find everything nice and clean
2834      * and thus will not attempt to create them in the profile directory. */
2835     _SHCreateSymbolicLinks();
2836     
2837     hr = _SHRegisterUserShellFolders(TRUE);
2838     if (SUCCEEDED(hr))
2839         hr = _SHRegisterUserShellFolders(FALSE);
2840     if (SUCCEEDED(hr))
2841         hr = _SHRegisterCommonShellFolders();
2842     if (SUCCEEDED(hr))
2843         hr = create_extra_folders();
2844     if (SUCCEEDED(hr))
2845         hr = set_folder_attributes();
2846     return hr;
2847 }
2848
2849 /*************************************************************************
2850  * SHGetSpecialFolderPathA [SHELL32.@]
2851  */
2852 BOOL WINAPI SHGetSpecialFolderPathA (
2853         HWND hwndOwner,
2854         LPSTR szPath,
2855         int nFolder,
2856         BOOL bCreate)
2857 {
2858     return SHGetFolderPathA(hwndOwner, nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0), NULL, 0,
2859                             szPath) == S_OK;
2860 }
2861
2862 /*************************************************************************
2863  * SHGetSpecialFolderPathW
2864  */
2865 BOOL WINAPI SHGetSpecialFolderPathW (
2866         HWND hwndOwner,
2867         LPWSTR szPath,
2868         int nFolder,
2869         BOOL bCreate)
2870 {
2871     return SHGetFolderPathW(hwndOwner, nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0), NULL, 0,
2872                             szPath) == S_OK;
2873 }
2874
2875 /*************************************************************************
2876  * SHGetSpecialFolderPath (SHELL32.175)
2877  */
2878 BOOL WINAPI SHGetSpecialFolderPathAW (
2879         HWND hwndOwner,
2880         LPVOID szPath,
2881         int nFolder,
2882         BOOL bCreate)
2883
2884 {
2885         if (SHELL_OsIsUnicode())
2886           return SHGetSpecialFolderPathW (hwndOwner, szPath, nFolder, bCreate);
2887         return SHGetSpecialFolderPathA (hwndOwner, szPath, nFolder, bCreate);
2888 }
2889
2890 /*************************************************************************
2891  * SHGetFolderLocation [SHELL32.@]
2892  *
2893  * Gets the folder locations from the registry and creates a pidl.
2894  *
2895  * PARAMS
2896  *   hwndOwner  [I]
2897  *   nFolder    [I] CSIDL_xxxxx
2898  *   hToken     [I] token representing user, or NULL for current user, or -1 for
2899  *                  default user
2900  *   dwReserved [I] must be zero
2901  *   ppidl      [O] PIDL of a special folder
2902  *
2903  * RETURNS
2904  *  Success: S_OK
2905  *  Failure: Standard OLE-defined error result, S_FALSE or E_INVALIDARG
2906  *
2907  * NOTES
2908  *  Creates missing reg keys and directories.
2909  *  Mostly forwards to SHGetFolderPathW, but a few values of nFolder return
2910  *  virtual folders that are handled here.
2911  */
2912 HRESULT WINAPI SHGetFolderLocation(
2913         HWND hwndOwner,
2914         int nFolder,
2915         HANDLE hToken,
2916         DWORD dwReserved,
2917         LPITEMIDLIST *ppidl)
2918 {
2919     HRESULT hr = E_INVALIDARG;
2920
2921     TRACE("%p 0x%08x %p 0x%08x %p\n",
2922      hwndOwner, nFolder, hToken, dwReserved, ppidl);
2923     
2924     if (!ppidl)
2925         return E_INVALIDARG;
2926     if (dwReserved)
2927         return E_INVALIDARG;
2928
2929     /* The virtual folders' locations are not user-dependent */
2930     *ppidl = NULL;
2931     switch (nFolder & CSIDL_FOLDER_MASK)
2932     {
2933         case CSIDL_DESKTOP:
2934             *ppidl = _ILCreateDesktop();
2935             break;
2936
2937         case CSIDL_PERSONAL:
2938             *ppidl = _ILCreateMyDocuments();
2939             break;
2940
2941         case CSIDL_INTERNET:
2942             *ppidl = _ILCreateIExplore();
2943             break;
2944
2945         case CSIDL_CONTROLS:
2946             *ppidl = _ILCreateControlPanel();
2947             break;
2948
2949         case CSIDL_PRINTERS:
2950             *ppidl = _ILCreatePrinters();
2951             break;
2952
2953         case CSIDL_BITBUCKET:
2954             *ppidl = _ILCreateBitBucket();
2955             break;
2956
2957         case CSIDL_DRIVES:
2958             *ppidl = _ILCreateMyComputer();
2959             break;
2960
2961         case CSIDL_NETWORK:
2962             *ppidl = _ILCreateNetwork();
2963             break;
2964
2965         default:
2966         {
2967             WCHAR szPath[MAX_PATH];
2968
2969             hr = SHGetFolderPathW(hwndOwner, nFolder, hToken,
2970              SHGFP_TYPE_CURRENT, szPath);
2971             if (SUCCEEDED(hr))
2972             {
2973                 DWORD attributes=0;
2974
2975                 TRACE("Value=%s\n", debugstr_w(szPath));
2976                 hr = SHILCreateFromPathW(szPath, ppidl, &attributes);
2977             }
2978             else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
2979             {
2980                 /* unlike SHGetFolderPath, SHGetFolderLocation in shell32
2981                  * version 6.0 returns E_FAIL for nonexistent paths
2982                  */
2983                 hr = E_FAIL;
2984             }
2985         }
2986     }
2987     if(*ppidl)
2988         hr = S_OK;
2989
2990     TRACE("-- (new pidl %p)\n",*ppidl);
2991     return hr;
2992 }
2993
2994 /*************************************************************************
2995  * SHGetSpecialFolderLocation           [SHELL32.@]
2996  *
2997  * NOTES
2998  *   In NT5, SHGetSpecialFolderLocation needs the <winntdir>/Recent
2999  *   directory.
3000  */
3001 HRESULT WINAPI SHGetSpecialFolderLocation(
3002         HWND hwndOwner,
3003         INT nFolder,
3004         LPITEMIDLIST * ppidl)
3005 {
3006     HRESULT hr = E_INVALIDARG;
3007
3008     TRACE("(%p,0x%x,%p)\n", hwndOwner,nFolder,ppidl);
3009
3010     if (!ppidl)
3011         return E_INVALIDARG;
3012
3013     hr = SHGetFolderLocation(hwndOwner, nFolder, NULL, 0, ppidl);
3014     return hr;
3015 }
3016
3017 static int csidl_from_id( const KNOWNFOLDERID *id )
3018 {
3019     int i;
3020     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3021         if (IsEqualGUID( CSIDL_Data[i].id, id )) return i;
3022     return -1;
3023 }
3024
3025 /*************************************************************************
3026  * SHGetKnownFolderPath           [SHELL32.@]
3027  */
3028 HRESULT WINAPI SHGetKnownFolderPath(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, PWSTR *path)
3029 {
3030     HRESULT hr;
3031     WCHAR folder[MAX_PATH];
3032     int index = csidl_from_id( rfid );
3033
3034     TRACE("%s, 0x%08x, %p, %p\n", debugstr_guid(rfid), flags, token, path);
3035
3036     *path = NULL;
3037
3038     if (index < 0)
3039         return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );
3040
3041     if (flags & KF_FLAG_CREATE)
3042         index |= CSIDL_FLAG_CREATE;
3043
3044     if (flags & KF_FLAG_DONT_VERIFY)
3045         index |= CSIDL_FLAG_DONT_VERIFY;
3046
3047     if (flags & KF_FLAG_NO_ALIAS)
3048         index |= CSIDL_FLAG_NO_ALIAS;
3049
3050     if (flags & KF_FLAG_INIT)
3051         index |= CSIDL_FLAG_PER_USER_INIT;
3052
3053     if (flags & ~(KF_FLAG_CREATE|KF_FLAG_DONT_VERIFY|KF_FLAG_NO_ALIAS|KF_FLAG_INIT))
3054     {
3055         FIXME("flags 0x%08x not supported\n", flags);
3056         return E_INVALIDARG;
3057     }
3058
3059     hr = SHGetFolderPathW( NULL, index, token, 0, folder );
3060     if (SUCCEEDED(hr))
3061     {
3062         *path = CoTaskMemAlloc( (strlenW( folder ) + 1) * sizeof(WCHAR) );
3063         if (!*path)
3064             return E_OUTOFMEMORY;
3065         strcpyW( *path, folder );
3066     }
3067     return hr;
3068 }
3069
3070 /*************************************************************************
3071  * SHGetFolderPathEx           [SHELL32.@]
3072  */
3073 HRESULT WINAPI SHGetFolderPathEx(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, LPWSTR path, DWORD len)
3074 {
3075     HRESULT hr;
3076     WCHAR *buffer;
3077
3078     TRACE("%s, 0x%08x, %p, %p, %u\n", debugstr_guid(rfid), flags, token, path, len);
3079
3080     if (!path || !len) return E_INVALIDARG;
3081
3082     hr = SHGetKnownFolderPath( rfid, flags, token, &buffer );
3083     if (SUCCEEDED( hr ))
3084     {
3085         if (strlenW( buffer ) + 1 > len)
3086         {
3087             CoTaskMemFree( buffer );
3088             return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
3089         }
3090         strcpyW( path, buffer );
3091         CoTaskMemFree( buffer );
3092     }
3093     return hr;
3094 }
3095
3096 /* constant values used by known folder functions */
3097 static const WCHAR szCategory[] = {'C','a','t','e','g','o','r','y',0};
3098 static const WCHAR szName[] = {'N','a','m','e',0};
3099 static const WCHAR szRelativePath[] = {'R','e','l','a','t','i','v','e','P','a','t','h',0};
3100 static const WCHAR szParentFolder[] = {'P','a','r','e','n','t','F','o','l','d','e','r',0};
3101
3102 /*
3103  * Internal function to convert known folder identifier to path of registry key
3104  * associated with known folder.
3105  *
3106  * Parameters:
3107  *  rfid            [I] pointer to known folder identifier (may be NULL)
3108  *  lpStringGuid    [I] string with known folder identifier (used when rfid is NULL)
3109  *  lpPath          [O] place to store string address. String should be
3110  *                      later freed using HeapFree(GetProcessHeap(),0, ... )
3111  */
3112 static HRESULT get_known_folder_registry_path(
3113     REFKNOWNFOLDERID rfid,
3114     LPWSTR lpStringGuid,
3115     LPWSTR *lpPath)
3116 {
3117     static const WCHAR sBackslash[] = {'\\',0};
3118     HRESULT hr = S_OK;
3119     int length;
3120     WCHAR sGuid[50];
3121
3122     TRACE("(%s, %s, %p)\n", debugstr_guid(rfid), debugstr_w(lpStringGuid), lpPath);
3123
3124     if(rfid)
3125         StringFromGUID2(rfid, sGuid, sizeof(sGuid)/sizeof(sGuid[0]));
3126     else
3127         lstrcpyW(sGuid, lpStringGuid);
3128
3129     length = lstrlenW(szKnownFolderDescriptions)+51;
3130     *lpPath = HeapAlloc(GetProcessHeap(), 0, length*sizeof(WCHAR));
3131     if(!(*lpPath))
3132         hr = E_OUTOFMEMORY;
3133
3134     if(SUCCEEDED(hr))
3135     {
3136         lstrcpyW(*lpPath, szKnownFolderDescriptions);
3137         lstrcatW(*lpPath, sBackslash);
3138         lstrcatW(*lpPath, sGuid);
3139     }
3140
3141     return hr;
3142 }
3143
3144 /*
3145  * Internal function to get place where folder redirection information are stored.
3146  *
3147  * Parameters:
3148  *  rfid            [I] pointer to known folder identifier (may be NULL)
3149  *  rootKey         [O] root key where the redirection information are stored
3150  *                      It can be HKLM for COMMON folders, and HKCU for PERUSER folders.
3151  *                      However, besides root key, path is always that same, and is stored
3152  *                      as "szKnownFolderRedirections" constant
3153  */
3154 static HRESULT get_known_folder_redirection_place(
3155     REFKNOWNFOLDERID rfid,
3156     HKEY *rootKey)
3157 {
3158     HRESULT hr;
3159     LPWSTR lpRegistryPath = NULL;
3160     KF_CATEGORY category;
3161     DWORD dwSize;
3162
3163     /* first, get known folder's category */
3164     hr = get_known_folder_registry_path(rfid, NULL, &lpRegistryPath);
3165
3166     if(SUCCEEDED(hr))
3167     {
3168         dwSize = sizeof(category);
3169         hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, lpRegistryPath, szCategory, RRF_RT_DWORD, NULL, &category, &dwSize));
3170     }
3171
3172     if(SUCCEEDED(hr))
3173     {
3174         if(category == KF_CATEGORY_COMMON)
3175         {
3176             *rootKey = HKEY_LOCAL_MACHINE;
3177             hr = S_OK;
3178         }
3179         else if(category == KF_CATEGORY_PERUSER)
3180         {
3181             *rootKey = HKEY_CURRENT_USER;
3182             hr = S_OK;
3183         }
3184         else
3185             hr = E_FAIL;
3186     }
3187
3188     HeapFree(GetProcessHeap(), 0, lpRegistryPath);
3189     return hr;
3190 }
3191
3192 static HRESULT get_known_folder_path_by_id(REFKNOWNFOLDERID folderId, LPWSTR lpRegistryPath, DWORD dwFlags, LPWSTR *ppszPath);
3193
3194 static HRESULT get_known_folder_category(
3195     LPWSTR registryPath,
3196     KF_CATEGORY* pCategory)
3197 {
3198     DWORD dwSize = sizeof(DWORD);
3199     DWORD dwType;
3200     return HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szCategory, RRF_RT_DWORD, &dwType, pCategory, &dwSize));
3201 }
3202
3203 static HRESULT redirect_known_folder(
3204     REFKNOWNFOLDERID rfid,
3205     HWND hwnd,
3206     KF_REDIRECT_FLAGS flags,
3207     LPCWSTR pszTargetPath,
3208     UINT cFolders,
3209     KNOWNFOLDERID const *pExclusion,
3210     LPWSTR *ppszError)
3211 {
3212     HRESULT hr;
3213     HKEY rootKey = HKEY_LOCAL_MACHINE, hKey;
3214     WCHAR sGuid[39];
3215     LPWSTR lpRegistryPath = NULL, lpSrcPath = NULL;
3216     TRACE("(%s, %p, 0x%08x, %s, %d, %p, %p)\n", debugstr_guid(rfid), hwnd, flags, debugstr_w(pszTargetPath), cFolders, pExclusion, ppszError);
3217
3218     if (ppszError) *ppszError = NULL;
3219
3220     hr = get_known_folder_registry_path(rfid, NULL, &lpRegistryPath);
3221
3222     if(SUCCEEDED(hr))
3223         hr = get_known_folder_path_by_id(rfid, lpRegistryPath, 0, &lpSrcPath);
3224
3225     HeapFree(GetProcessHeap(), 0, lpRegistryPath);
3226
3227     /* get path to redirection storage */
3228     if(SUCCEEDED(hr))
3229         hr = get_known_folder_redirection_place(rfid, &rootKey);
3230
3231     /* write redirection information */
3232     if(SUCCEEDED(hr))
3233         hr = HRESULT_FROM_WIN32(RegCreateKeyExW(rootKey, szKnownFolderRedirections, 0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL));
3234
3235     if(SUCCEEDED(hr))
3236     {
3237         StringFromGUID2(rfid, sGuid, sizeof(sGuid)/sizeof(sGuid[0]));
3238
3239         hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, sGuid, 0, REG_SZ, (LPBYTE)pszTargetPath, (lstrlenW(pszTargetPath)+1)*sizeof(WCHAR)));
3240
3241         RegCloseKey(hKey);
3242     }
3243
3244     /* make sure destination path exists */
3245     SHCreateDirectory(NULL, pszTargetPath);
3246
3247     /* copy content if required */
3248     if(SUCCEEDED(hr) && (flags & KF_REDIRECT_COPY_CONTENTS) )
3249     {
3250         static const WCHAR sWildcard[] = {'\\','*',0};
3251         WCHAR srcPath[MAX_PATH+1], dstPath[MAX_PATH+1];
3252         SHFILEOPSTRUCTW fileOp;
3253
3254         ZeroMemory(srcPath, sizeof(srcPath));
3255         lstrcpyW(srcPath, lpSrcPath);
3256         lstrcatW(srcPath, sWildcard);
3257
3258         ZeroMemory(dstPath, sizeof(dstPath));
3259         lstrcpyW(dstPath, pszTargetPath);
3260
3261         ZeroMemory(&fileOp, sizeof(fileOp));
3262
3263         if(flags & KF_REDIRECT_DEL_SOURCE_CONTENTS)
3264             fileOp.wFunc = FO_MOVE;
3265         else
3266             fileOp.wFunc = FO_COPY;
3267
3268         fileOp.pFrom = srcPath;
3269         fileOp.pTo = dstPath;
3270         fileOp.fFlags = FOF_NO_UI;
3271
3272         hr = (SHFileOperationW(&fileOp)==0 ? S_OK : E_FAIL);
3273
3274         if(flags & KF_REDIRECT_DEL_SOURCE_CONTENTS)
3275         {
3276             ZeroMemory(srcPath, sizeof(srcPath));
3277             lstrcpyW(srcPath, lpSrcPath);
3278
3279             ZeroMemory(&fileOp, sizeof(fileOp));
3280             fileOp.wFunc = FO_DELETE;
3281             fileOp.pFrom = srcPath;
3282             fileOp.fFlags = FOF_NO_UI;
3283
3284             hr = (SHFileOperationW(&fileOp)==0 ? S_OK : E_FAIL);
3285         }
3286     }
3287
3288     CoTaskMemFree(lpSrcPath);
3289
3290     return hr;
3291 }
3292
3293
3294 struct knownfolder
3295 {
3296     IKnownFolder IKnownFolder_iface;
3297     LONG refs;
3298     KNOWNFOLDERID id;
3299     LPWSTR registryPath;
3300 };
3301
3302 static inline struct knownfolder *impl_from_IKnownFolder( IKnownFolder *iface )
3303 {
3304     return CONTAINING_RECORD( iface, struct knownfolder, IKnownFolder_iface );
3305 }
3306
3307 static ULONG WINAPI knownfolder_AddRef(
3308     IKnownFolder *iface )
3309 {
3310     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3311     return InterlockedIncrement( &knownfolder->refs );
3312 }
3313
3314 static ULONG WINAPI knownfolder_Release(
3315     IKnownFolder *iface )
3316 {
3317     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3318     LONG refs = InterlockedDecrement( &knownfolder->refs );
3319     if (!refs)
3320     {
3321         TRACE("destroying %p\n", knownfolder);
3322         HeapFree( GetProcessHeap(), 0, knownfolder->registryPath);
3323         HeapFree( GetProcessHeap(), 0, knownfolder );
3324     }
3325     return refs;
3326 }
3327
3328 static HRESULT WINAPI knownfolder_QueryInterface(
3329     IKnownFolder *iface,
3330     REFIID riid,
3331     void **ppv )
3332 {
3333     struct knownfolder *This = impl_from_IKnownFolder( iface );
3334
3335     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3336
3337     if ( IsEqualGUID( riid, &IID_IKnownFolder ) ||
3338          IsEqualGUID( riid, &IID_IUnknown ) )
3339     {
3340         *ppv = iface;
3341     }
3342     else
3343     {
3344         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3345         return E_NOINTERFACE;
3346     }
3347     IKnownFolder_AddRef( iface );
3348     return S_OK;
3349 }
3350
3351 static HRESULT knownfolder_set_id(
3352     struct knownfolder *knownfolder,
3353     const KNOWNFOLDERID *kfid)
3354 {
3355     HKEY hKey;
3356     HRESULT hr;
3357
3358     TRACE("%s\n", debugstr_guid(kfid));
3359
3360     knownfolder->id = *kfid;
3361
3362     /* check is it registry-registered folder */
3363     hr = get_known_folder_registry_path(kfid, NULL, &knownfolder->registryPath);
3364     if(SUCCEEDED(hr))
3365         hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, 0, 0, &hKey));
3366
3367     if(SUCCEEDED(hr))
3368     {
3369         hr = S_OK;
3370         RegCloseKey(hKey);
3371     }
3372     else
3373     {
3374         /* This known folder is not registered. To mark it, we set registryPath to NULL */
3375         HeapFree(GetProcessHeap(), 0, knownfolder->registryPath);
3376         knownfolder->registryPath = NULL;
3377         hr = S_OK;
3378     }
3379
3380     return hr;
3381 }
3382
3383 static HRESULT WINAPI knownfolder_GetId(
3384     IKnownFolder *iface,
3385     KNOWNFOLDERID *pkfid)
3386 {
3387     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3388
3389     TRACE("%p\n", pkfid);
3390
3391     *pkfid = knownfolder->id;
3392     return S_OK;
3393 }
3394
3395 static HRESULT WINAPI knownfolder_GetCategory(
3396     IKnownFolder *iface,
3397     KF_CATEGORY *pCategory)
3398 {
3399     struct knownfolder *knownfolder = impl_from_IKnownFolder(iface);
3400     HRESULT hr = S_OK;
3401
3402     TRACE("%p, %p\n", knownfolder, pCategory);
3403
3404     /* we cannot get a category for a folder which is not registered */
3405     if(!knownfolder->registryPath)
3406         hr = E_FAIL;
3407
3408     if(SUCCEEDED(hr))
3409         hr = get_known_folder_category(knownfolder->registryPath, pCategory);
3410
3411     return hr;
3412 }
3413
3414 static HRESULT WINAPI knownfolder_GetShellItem(
3415     IKnownFolder *iface,
3416     DWORD dwFlags,
3417     REFIID riid,
3418     void **ppv)
3419 {
3420     FIXME("0x%08x, %s, %p\n", dwFlags, debugstr_guid(riid), ppv);
3421     return E_NOTIMPL;
3422 }
3423
3424 static HRESULT get_known_folder_path(
3425     LPWSTR sFolderId,
3426     LPWSTR registryPath,
3427     LPWSTR *ppszPath)
3428 {
3429     static const WCHAR sBackslash[] = {'\\',0};
3430     HRESULT hr;
3431     DWORD dwSize, dwType;
3432     WCHAR path[MAX_PATH] = {0};
3433     WCHAR parentGuid[39];
3434     KF_CATEGORY category;
3435     LPWSTR parentRegistryPath, parentPath;
3436     HKEY hRedirectionRootKey = NULL;
3437
3438     TRACE("(%s, %p)\n", debugstr_w(registryPath), ppszPath);
3439     *ppszPath = NULL;
3440
3441     /* check if folder has parent */
3442     dwSize = sizeof(parentGuid);
3443     hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szParentFolder, RRF_RT_REG_SZ, &dwType, parentGuid, &dwSize));
3444     if(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) hr = S_FALSE;
3445
3446     if(hr == S_OK)
3447     {
3448         /* get parent's known folder path (recursive) */
3449         hr = get_known_folder_registry_path(NULL, parentGuid, &parentRegistryPath);
3450         if(FAILED(hr)) return hr;
3451
3452         hr = get_known_folder_path(parentGuid, parentRegistryPath, &parentPath);
3453         if(FAILED(hr)) {
3454             HeapFree(GetProcessHeap(), 0, parentRegistryPath);
3455             return hr;
3456         }
3457
3458         lstrcatW(path, parentPath);
3459         lstrcatW(path, sBackslash);
3460
3461         HeapFree(GetProcessHeap(), 0, parentRegistryPath);
3462         HeapFree(GetProcessHeap(), 0, parentPath);
3463     }
3464
3465     /* check, if folder was redirected */
3466     if(SUCCEEDED(hr))
3467         hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szCategory, RRF_RT_REG_DWORD, NULL, &category, &dwSize));
3468
3469     if(SUCCEEDED(hr))
3470     {
3471         if(category == KF_CATEGORY_COMMON)
3472             hRedirectionRootKey = HKEY_LOCAL_MACHINE;
3473         else if(category == KF_CATEGORY_PERUSER)
3474             hRedirectionRootKey = HKEY_CURRENT_USER;
3475
3476         if(hRedirectionRootKey)
3477         {
3478             hr = HRESULT_FROM_WIN32(RegGetValueW(hRedirectionRootKey, szKnownFolderRedirections, sFolderId, RRF_RT_REG_SZ, NULL, NULL, &dwSize));
3479
3480             if(SUCCEEDED(hr))
3481             {
3482                 *ppszPath = CoTaskMemAlloc(dwSize+(lstrlenW(path)+1)*sizeof(WCHAR));
3483                 if(!*ppszPath) hr = E_OUTOFMEMORY;
3484             }
3485
3486             if(SUCCEEDED(hr))
3487             {
3488                 lstrcpyW(*ppszPath, path);
3489                 hr = HRESULT_FROM_WIN32(RegGetValueW(hRedirectionRootKey, szKnownFolderRedirections, sFolderId, RRF_RT_REG_SZ, NULL, *ppszPath + lstrlenW(path), &dwSize));
3490             }
3491         }
3492
3493         if(!*ppszPath)
3494         {
3495             /* no redirection, use previous way - read the relative path from folder definition */
3496             hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szRelativePath, RRF_RT_REG_SZ, &dwType, NULL, &dwSize));
3497
3498             if(SUCCEEDED(hr))
3499             {
3500                 *ppszPath = CoTaskMemAlloc(dwSize+(lstrlenW(path)+1)*sizeof(WCHAR));
3501                 if(!*ppszPath) hr = E_OUTOFMEMORY;
3502             }
3503
3504             if(SUCCEEDED(hr))
3505             {
3506                 lstrcpyW(*ppszPath, path);
3507                 hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, registryPath, szRelativePath, RRF_RT_REG_SZ, &dwType, *ppszPath + lstrlenW(path), &dwSize));
3508             }
3509         }
3510     }
3511
3512     TRACE("returning path: %s\n", debugstr_w(*ppszPath));
3513     return hr;
3514 }
3515
3516 static HRESULT get_known_folder_path_by_id(
3517     REFKNOWNFOLDERID folderId,
3518     LPWSTR lpRegistryPath,
3519     DWORD dwFlags,
3520     LPWSTR *ppszPath)
3521 {
3522     HRESULT hr;
3523     WCHAR sGuid[39];
3524     DWORD dwAttributes;
3525
3526     TRACE("(%s, %s, 0x%08x, %p)\n", debugstr_guid(folderId), debugstr_w(lpRegistryPath), dwFlags, ppszPath);
3527
3528     /* if this is registry-registered known folder, get path from registry */
3529     if(lpRegistryPath)
3530     {
3531         StringFromGUID2(folderId, sGuid, sizeof(sGuid)/sizeof(sGuid[0]));
3532
3533         hr = get_known_folder_path(sGuid, lpRegistryPath, ppszPath);
3534     }
3535     /* in other case, use older way */
3536     else
3537         hr = SHGetKnownFolderPath( folderId, dwFlags, NULL, ppszPath );
3538
3539     if (FAILED(hr)) return hr;
3540
3541     /* check if known folder really exists */
3542     dwAttributes = GetFileAttributesW(*ppszPath);
3543     if(dwAttributes == INVALID_FILE_ATTRIBUTES || !(dwAttributes & FILE_ATTRIBUTE_DIRECTORY) )
3544     {
3545         TRACE("directory %s not found\n", debugstr_w(*ppszPath));
3546         CoTaskMemFree(*ppszPath);
3547         *ppszPath = NULL;
3548         hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
3549     }
3550
3551     return hr;
3552 }
3553
3554 static HRESULT WINAPI knownfolder_GetPath(
3555     IKnownFolder *iface,
3556     DWORD dwFlags,
3557     LPWSTR *ppszPath)
3558 {
3559     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3560     TRACE("(%p, 0x%08x, %p)\n", knownfolder, dwFlags, ppszPath);
3561
3562     return get_known_folder_path_by_id(&knownfolder->id, knownfolder->registryPath, dwFlags, ppszPath);
3563 }
3564
3565 static HRESULT WINAPI knownfolder_SetPath(
3566     IKnownFolder *iface,
3567     DWORD dwFlags,
3568     LPCWSTR pszPath)
3569 {
3570     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3571     HRESULT hr = S_OK;
3572
3573     TRACE("(%p, 0x%08x, %s)\n", knownfolder, dwFlags, debugstr_w(pszPath));
3574
3575     /* check if the known folder is registered */
3576     if(!knownfolder->registryPath)
3577         hr = E_FAIL;
3578
3579     if(SUCCEEDED(hr))
3580         hr = redirect_known_folder(&knownfolder->id, NULL, 0, pszPath, 0, NULL, NULL);
3581
3582     return hr;
3583 }
3584
3585 static HRESULT WINAPI knownfolder_GetIDList(
3586     IKnownFolder *iface,
3587     DWORD dwFlags,
3588     PIDLIST_ABSOLUTE *ppidl)
3589 {
3590     FIXME("0x%08x, %p\n", dwFlags, ppidl);
3591     return E_NOTIMPL;
3592 }
3593
3594 static HRESULT WINAPI knownfolder_GetFolderType(
3595     IKnownFolder *iface,
3596     FOLDERTYPEID *pftid)
3597 {
3598     FIXME("%p\n", pftid);
3599     return E_NOTIMPL;
3600 }
3601
3602 static HRESULT WINAPI knownfolder_GetRedirectionCapabilities(
3603     IKnownFolder *iface,
3604     KF_REDIRECTION_CAPABILITIES *pCapabilities)
3605 {
3606     FIXME("%p\n", pCapabilities);
3607     return E_NOTIMPL;
3608 }
3609
3610 static HRESULT WINAPI knownfolder_GetFolderDefinition(
3611     IKnownFolder *iface,
3612     KNOWNFOLDER_DEFINITION *pKFD)
3613 {
3614     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3615     HRESULT hr;
3616     DWORD dwSize;
3617     TRACE("(%p, %p)\n", knownfolder, pKFD);
3618
3619     if(!pKFD) return E_INVALIDARG;
3620
3621     ZeroMemory(pKFD, sizeof(*pKFD));
3622
3623     hr = get_known_folder_category(knownfolder->registryPath, &pKFD->category);
3624
3625     if(SUCCEEDED(hr))
3626         hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, szName, RRF_RT_REG_SZ, NULL, NULL, &dwSize));
3627
3628     if(SUCCEEDED(hr))
3629     {
3630         pKFD->pszName = CoTaskMemAlloc(dwSize);
3631         if(!pKFD->pszName) hr = E_OUTOFMEMORY;
3632     }
3633
3634     if(SUCCEEDED(hr))
3635         hr = HRESULT_FROM_WIN32(RegGetValueW(HKEY_LOCAL_MACHINE, knownfolder->registryPath, szName, RRF_RT_REG_SZ, NULL, pKFD->pszName, &dwSize));
3636
3637     return hr;
3638 }
3639
3640 static const struct IKnownFolderVtbl knownfolder_vtbl =
3641 {
3642     knownfolder_QueryInterface,
3643     knownfolder_AddRef,
3644     knownfolder_Release,
3645     knownfolder_GetId,
3646     knownfolder_GetCategory,
3647     knownfolder_GetShellItem,
3648     knownfolder_GetPath,
3649     knownfolder_SetPath,
3650     knownfolder_GetIDList,
3651     knownfolder_GetFolderType,
3652     knownfolder_GetRedirectionCapabilities,
3653     knownfolder_GetFolderDefinition
3654 };
3655
3656 static HRESULT knownfolder_create( struct knownfolder **knownfolder )
3657 {
3658     struct knownfolder *kf;
3659
3660     kf = HeapAlloc( GetProcessHeap(), 0, sizeof(*kf) );
3661     if (!kf) return E_OUTOFMEMORY;
3662
3663     kf->IKnownFolder_iface.lpVtbl = &knownfolder_vtbl;
3664     kf->refs = 1;
3665     memset( &kf->id, 0, sizeof(kf->id) );
3666     kf->registryPath = NULL;
3667
3668     *knownfolder = kf;
3669
3670     TRACE("returning iface %p\n", &kf->IKnownFolder_iface);
3671     return S_OK;
3672 }
3673
3674 struct foldermanager
3675 {
3676     IKnownFolderManager IKnownFolderManager_iface;
3677     LONG refs;
3678     UINT num_ids;
3679     KNOWNFOLDERID *ids;
3680 };
3681
3682 static inline struct foldermanager *impl_from_IKnownFolderManager( IKnownFolderManager *iface )
3683 {
3684     return CONTAINING_RECORD( iface, struct foldermanager, IKnownFolderManager_iface );
3685 }
3686
3687 static ULONG WINAPI foldermanager_AddRef(
3688     IKnownFolderManager *iface )
3689 {
3690     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3691     return InterlockedIncrement( &foldermanager->refs );
3692 }
3693
3694 static ULONG WINAPI foldermanager_Release(
3695     IKnownFolderManager *iface )
3696 {
3697     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3698     LONG refs = InterlockedDecrement( &foldermanager->refs );
3699     if (!refs)
3700     {
3701         TRACE("destroying %p\n", foldermanager);
3702         HeapFree( GetProcessHeap(), 0, foldermanager->ids );
3703         HeapFree( GetProcessHeap(), 0, foldermanager );
3704     }
3705     return refs;
3706 }
3707
3708 static HRESULT WINAPI foldermanager_QueryInterface(
3709     IKnownFolderManager *iface,
3710     REFIID riid,
3711     void **ppv )
3712 {
3713     struct foldermanager *This = impl_from_IKnownFolderManager( iface );
3714
3715     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3716
3717     if ( IsEqualGUID( riid, &IID_IKnownFolderManager ) ||
3718          IsEqualGUID( riid, &IID_IUnknown ) )
3719     {
3720         *ppv = iface;
3721     }
3722     else
3723     {
3724         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3725         return E_NOINTERFACE;
3726     }
3727     IKnownFolderManager_AddRef( iface );
3728     return S_OK;
3729 }
3730
3731 static HRESULT WINAPI foldermanager_FolderIdFromCsidl(
3732     IKnownFolderManager *iface,
3733     int nCsidl,
3734     KNOWNFOLDERID *pfid)
3735 {
3736     TRACE("%d, %p\n", nCsidl, pfid);
3737
3738     if (nCsidl >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
3739         return E_INVALIDARG;
3740     *pfid = *CSIDL_Data[nCsidl].id;
3741     return S_OK;
3742 }
3743
3744 static HRESULT WINAPI foldermanager_FolderIdToCsidl(
3745     IKnownFolderManager *iface,
3746     REFKNOWNFOLDERID rfid,
3747     int *pnCsidl)
3748 {
3749     int csidl;
3750
3751     TRACE("%s, %p\n", debugstr_guid(rfid), pnCsidl);
3752
3753     csidl = csidl_from_id( rfid );
3754     if (csidl == -1) return E_INVALIDARG;
3755     *pnCsidl = csidl;
3756     return S_OK;
3757 }
3758
3759 static HRESULT WINAPI foldermanager_GetFolderIds(
3760     IKnownFolderManager *iface,
3761     KNOWNFOLDERID **ppKFId,
3762     UINT *pCount)
3763 {
3764     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3765
3766     TRACE("%p, %p\n", ppKFId, pCount);
3767
3768     *ppKFId = fm->ids;
3769     *pCount = fm->num_ids;
3770     return S_OK;
3771 }
3772
3773 static BOOL is_knownfolder( struct foldermanager *fm, const KNOWNFOLDERID *id )
3774 {
3775     UINT i;
3776     HRESULT hr;
3777     LPWSTR registryPath = NULL;
3778     HKEY hKey;
3779
3780     /* TODO: move all entries from "CSIDL_Data" static array to registry known folder descriptions */
3781     for (i = 0; i < fm->num_ids; i++)
3782         if (IsEqualGUID( &fm->ids[i], id )) return TRUE;
3783
3784     hr = get_known_folder_registry_path(id, NULL, &registryPath);
3785     if(SUCCEEDED(hr))
3786         hr = HRESULT_FROM_WIN32(RegOpenKeyExW(HKEY_LOCAL_MACHINE, registryPath, 0, 0, &hKey));
3787
3788     if(SUCCEEDED(hr))
3789     {
3790         hr = S_OK;
3791         RegCloseKey(hKey);
3792     }
3793
3794     return hr == S_OK;
3795 }
3796
3797 static HRESULT WINAPI foldermanager_GetFolder(
3798     IKnownFolderManager *iface,
3799     REFKNOWNFOLDERID rfid,
3800     IKnownFolder **ppkf)
3801 {
3802     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3803     struct knownfolder *kf;
3804     HRESULT hr;
3805
3806     TRACE("%s, %p\n", debugstr_guid(rfid), ppkf);
3807
3808     if (!is_knownfolder( fm, rfid ))
3809     {
3810         WARN("unknown folder\n");
3811         return E_INVALIDARG;
3812     }
3813     hr = knownfolder_create( &kf );
3814     if (SUCCEEDED( hr ))
3815     {
3816         hr = knownfolder_set_id( kf, rfid );
3817         *ppkf = &kf->IKnownFolder_iface;
3818     }
3819     else
3820         *ppkf = NULL;
3821
3822     return hr;
3823 }
3824
3825 static HRESULT WINAPI foldermanager_GetFolderByName(
3826     IKnownFolderManager *iface,
3827     LPCWSTR pszCanonicalName,
3828     IKnownFolder **ppkf)
3829 {
3830     FIXME("%s, %p\n", debugstr_w(pszCanonicalName), ppkf);
3831     return E_NOTIMPL;
3832 }
3833
3834 static HRESULT WINAPI foldermanager_RegisterFolder(
3835     IKnownFolderManager *iface,
3836     REFKNOWNFOLDERID rfid,
3837     KNOWNFOLDER_DEFINITION const *pKFD)
3838 {
3839     HRESULT hr;
3840     HKEY hKey = NULL;
3841     DWORD dwDisp;
3842     LPWSTR registryPath = NULL;
3843     TRACE("(%p, %s, %p)\n", iface, debugstr_guid(rfid), pKFD);
3844
3845     hr = get_known_folder_registry_path(rfid, NULL, &registryPath);
3846     TRACE("registry path: %s\n", debugstr_w(registryPath));
3847
3848     if(SUCCEEDED(hr))
3849         hr = HRESULT_FROM_WIN32(RegCreateKeyExW(HKEY_LOCAL_MACHINE, registryPath, 0, NULL, 0, KEY_WRITE, 0, &hKey, &dwDisp));
3850
3851     if(SUCCEEDED(hr))
3852     {
3853         if(dwDisp == REG_OPENED_EXISTING_KEY)
3854             hr = E_FAIL;
3855
3856         if(SUCCEEDED(hr))
3857             hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szCategory, 0, REG_DWORD, (LPBYTE)&pKFD->category, sizeof(pKFD->category)));
3858
3859         if(SUCCEEDED(hr))
3860             hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szName, 0, REG_SZ, (LPBYTE)pKFD->pszName, (lstrlenW(pKFD->pszName)+1)*sizeof(WCHAR) ));
3861
3862         if(SUCCEEDED(hr) && !IsEqualGUID(&pKFD->fidParent, &GUID_NULL))
3863         {
3864             WCHAR sParentGuid[39];
3865             StringFromGUID2(&pKFD->fidParent, sParentGuid, sizeof(sParentGuid)/sizeof(sParentGuid[0]));
3866
3867             /* this known folder has parent folder */
3868             hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szParentFolder, 0, REG_SZ, (LPBYTE)sParentGuid, sizeof(sParentGuid)));
3869         }
3870
3871         if(SUCCEEDED(hr) && pKFD->category != KF_CATEGORY_VIRTUAL)
3872         {
3873             if(!pKFD->pszRelativePath)
3874                 hr = E_INVALIDARG;
3875
3876             if(SUCCEEDED(hr))
3877                 hr = HRESULT_FROM_WIN32(RegSetValueExW(hKey, szRelativePath, 0, REG_SZ, (LPBYTE)pKFD->pszRelativePath, (lstrlenW(pKFD->pszRelativePath)+1)*sizeof(WCHAR) ));
3878         }
3879
3880         RegCloseKey(hKey);
3881
3882         if(FAILED(hr))
3883             SHDeleteKeyW(HKEY_LOCAL_MACHINE, registryPath);
3884     }
3885
3886     HeapFree(GetProcessHeap(), 0, registryPath);
3887     return hr;
3888 }
3889
3890 static HRESULT WINAPI foldermanager_UnregisterFolder(
3891     IKnownFolderManager *iface,
3892     REFKNOWNFOLDERID rfid)
3893 {
3894     HRESULT hr;
3895     LPWSTR registryPath = NULL;
3896     TRACE("(%p, %s)\n", iface, debugstr_guid(rfid));
3897
3898     hr = get_known_folder_registry_path(rfid, NULL, &registryPath);
3899
3900     if(SUCCEEDED(hr))
3901         hr = HRESULT_FROM_WIN32(SHDeleteKeyW(HKEY_LOCAL_MACHINE, registryPath));
3902
3903     HeapFree(GetProcessHeap(), 0, registryPath);
3904     return hr;
3905 }
3906
3907 static HRESULT WINAPI foldermanager_FindFolderFromPath(
3908     IKnownFolderManager *iface,
3909     LPCWSTR pszPath,
3910     FFFP_MODE mode,
3911     IKnownFolder **ppkf)
3912 {
3913     FIXME("%s, 0x%08x, %p\n", debugstr_w(pszPath), mode, ppkf);
3914     return E_NOTIMPL;
3915 }
3916
3917 static HRESULT WINAPI foldermanager_FindFolderFromIDList(
3918     IKnownFolderManager *iface,
3919     PCIDLIST_ABSOLUTE pidl,
3920     IKnownFolder **ppkf)
3921 {
3922     FIXME("%p, %p\n", pidl, ppkf);
3923     return E_NOTIMPL;
3924 }
3925
3926 static HRESULT WINAPI foldermanager_Redirect(
3927     IKnownFolderManager *iface,
3928     REFKNOWNFOLDERID rfid,
3929     HWND hwnd,
3930     KF_REDIRECT_FLAGS flags,
3931     LPCWSTR pszTargetPath,
3932     UINT cFolders,
3933     KNOWNFOLDERID const *pExclusion,
3934     LPWSTR *ppszError)
3935 {
3936     return redirect_known_folder(rfid, hwnd, flags, pszTargetPath, cFolders, pExclusion, ppszError);
3937 }
3938
3939 static const struct IKnownFolderManagerVtbl foldermanager_vtbl =
3940 {
3941     foldermanager_QueryInterface,
3942     foldermanager_AddRef,
3943     foldermanager_Release,
3944     foldermanager_FolderIdFromCsidl,
3945     foldermanager_FolderIdToCsidl,
3946     foldermanager_GetFolderIds,
3947     foldermanager_GetFolder,
3948     foldermanager_GetFolderByName,
3949     foldermanager_RegisterFolder,
3950     foldermanager_UnregisterFolder,
3951     foldermanager_FindFolderFromPath,
3952     foldermanager_FindFolderFromIDList,
3953     foldermanager_Redirect
3954 };
3955
3956 static HRESULT foldermanager_create( void **ppv )
3957 {
3958     UINT i, j;
3959     struct foldermanager *fm;
3960
3961     fm = HeapAlloc( GetProcessHeap(), 0, sizeof(*fm) );
3962     if (!fm) return E_OUTOFMEMORY;
3963
3964     fm->IKnownFolderManager_iface.lpVtbl = &foldermanager_vtbl;
3965     fm->refs = 1;
3966     fm->num_ids = 0;
3967
3968     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3969     {
3970         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL )) fm->num_ids++;
3971     }
3972     fm->ids = HeapAlloc( GetProcessHeap(), 0, fm->num_ids * sizeof(KNOWNFOLDERID) );
3973     if (!fm->ids)
3974     {
3975         HeapFree( GetProcessHeap(), 0, fm );
3976         return E_OUTOFMEMORY;
3977     }
3978     for (i = j = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3979     {
3980         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL ))
3981         {
3982             fm->ids[j] = *CSIDL_Data[i].id;
3983             j++;
3984         }
3985     }
3986     TRACE("found %u known folders\n", fm->num_ids);
3987     *ppv = &fm->IKnownFolderManager_iface;
3988
3989     TRACE("returning iface %p\n", *ppv);
3990     return S_OK;
3991 }
3992
3993 HRESULT WINAPI KnownFolderManager_Constructor( IUnknown *punk, REFIID riid, void **ppv )
3994 {
3995     TRACE("%p, %s, %p\n", punk, debugstr_guid(riid), ppv);
3996
3997     if (!ppv)
3998         return E_POINTER;
3999     if (punk)
4000         return CLASS_E_NOAGGREGATION;
4001
4002     return foldermanager_create( ppv );
4003 }
4004
4005 HRESULT WINAPI SHGetKnownFolderIDList(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, PIDLIST_ABSOLUTE *pidl)
4006 {
4007         FIXME("%s, 0x%08x, %p, %p\n", debugstr_guid(rfid), flags, token, pidl);
4008         return E_NOTIMPL;
4009 }