oleaut32: Hide variables and functions count storage details in helpers.
[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 #define INITGUID
55 #include "knownfolders.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(
673         LPSTR lpszPath,
674         LPCSTR *alpszPaths,
675         DWORD dwFlags)
676 {
677         FIXME("(%s,%p,0x%08x),stub!\n",
678           lpszPath, *alpszPaths, dwFlags);
679         return 0;
680 }
681
682 static BOOL PathResolveW(
683         LPWSTR lpszPath,
684         LPCWSTR *alpszPaths,
685         DWORD dwFlags)
686 {
687         FIXME("(%s,%p,0x%08x),stub!\n",
688           debugstr_w(lpszPath), debugstr_w(*alpszPaths), dwFlags);
689         return 0;
690 }
691
692 /*************************************************************************
693  * PathResolve [SHELL32.51]
694  */
695 BOOL WINAPI PathResolveAW(
696         LPVOID lpszPath,
697         LPCVOID *alpszPaths,
698         DWORD dwFlags)
699 {
700         if (SHELL_OsIsUnicode())
701           return PathResolveW(lpszPath, (LPCWSTR*)alpszPaths, dwFlags);
702         return PathResolveA(lpszPath, (LPCSTR*)alpszPaths, dwFlags);
703 }
704
705 /*************************************************************************
706 *       PathProcessCommandA
707 */
708 static LONG PathProcessCommandA (
709         LPCSTR lpszPath,
710         LPSTR lpszBuff,
711         DWORD dwBuffSize,
712         DWORD dwFlags)
713 {
714         FIXME("%s %p 0x%04x 0x%04x stub\n",
715         lpszPath, lpszBuff, dwBuffSize, dwFlags);
716         if(!lpszPath) return -1;
717         if(lpszBuff) strcpy(lpszBuff, lpszPath);
718         return strlen(lpszPath);
719 }
720
721 /*************************************************************************
722 *       PathProcessCommandW
723 */
724 static LONG PathProcessCommandW (
725         LPCWSTR lpszPath,
726         LPWSTR lpszBuff,
727         DWORD dwBuffSize,
728         DWORD dwFlags)
729 {
730         FIXME("(%s, %p, 0x%04x, 0x%04x) stub\n",
731         debugstr_w(lpszPath), lpszBuff, dwBuffSize, dwFlags);
732         if(!lpszPath) return -1;
733         if(lpszBuff) strcpyW(lpszBuff, lpszPath);
734         return strlenW(lpszPath);
735 }
736
737 /*************************************************************************
738 *       PathProcessCommand (SHELL32.653)
739 */
740 LONG WINAPI PathProcessCommandAW (
741         LPCVOID lpszPath,
742         LPVOID lpszBuff,
743         DWORD dwBuffSize,
744         DWORD dwFlags)
745 {
746         if (SHELL_OsIsUnicode())
747           return PathProcessCommandW(lpszPath, lpszBuff, dwBuffSize, dwFlags);
748         return PathProcessCommandA(lpszPath, lpszBuff, dwBuffSize, dwFlags);
749 }
750
751 /*
752         ########## special ##########
753 */
754
755 /*************************************************************************
756  * PathSetDlgItemPath (SHELL32.48)
757  */
758 VOID WINAPI PathSetDlgItemPathAW(HWND hDlg, int id, LPCVOID pszPath)
759 {
760         if (SHELL_OsIsUnicode())
761             PathSetDlgItemPathW(hDlg, id, pszPath);
762         else
763             PathSetDlgItemPathA(hDlg, id, pszPath);
764 }
765
766 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'};
767 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'};
768 static const WCHAR AppDataW[] = {'A','p','p','D','a','t','a','\0'};
769 static const WCHAR CacheW[] = {'C','a','c','h','e','\0'};
770 static const WCHAR CD_BurningW[] = {'C','D',' ','B','u','r','n','i','n','g','\0'};
771 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'};
772 static const WCHAR Common_AppDataW[] = {'C','o','m','m','o','n',' ','A','p','p','D','a','t','a','\0'};
773 static const WCHAR Common_DesktopW[] = {'C','o','m','m','o','n',' ','D','e','s','k','t','o','p','\0'};
774 static const WCHAR Common_DocumentsW[] = {'C','o','m','m','o','n',' ','D','o','c','u','m','e','n','t','s','\0'};
775 static const WCHAR Common_FavoritesW[] = {'C','o','m','m','o','n',' ','F','a','v','o','r','i','t','e','s','\0'};
776 static const WCHAR CommonFilesDirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r','\0'};
777 static const WCHAR CommonFilesDirX86W[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
778 static const WCHAR CommonMusicW[] = {'C','o','m','m','o','n','M','u','s','i','c','\0'};
779 static const WCHAR CommonPicturesW[] = {'C','o','m','m','o','n','P','i','c','t','u','r','e','s','\0'};
780 static const WCHAR Common_ProgramsW[] = {'C','o','m','m','o','n',' ','P','r','o','g','r','a','m','s','\0'};
781 static const WCHAR Common_StartUpW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t','U','p','\0'};
782 static const WCHAR Common_Start_MenuW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t',' ','M','e','n','u','\0'};
783 static const WCHAR Common_TemplatesW[] = {'C','o','m','m','o','n',' ','T','e','m','p','l','a','t','e','s','\0'};
784 static const WCHAR CommonVideoW[] = {'C','o','m','m','o','n','V','i','d','e','o','\0'};
785 static const WCHAR ContactsW[] = {'C','o','n','t','a','c','t','s','\0'};
786 static const WCHAR CookiesW[] = {'C','o','o','k','i','e','s','\0'};
787 static const WCHAR DesktopW[] = {'D','e','s','k','t','o','p','\0'};
788 static const WCHAR FavoritesW[] = {'F','a','v','o','r','i','t','e','s','\0'};
789 static const WCHAR FontsW[] = {'F','o','n','t','s','\0'};
790 static const WCHAR HistoryW[] = {'H','i','s','t','o','r','y','\0'};
791 static const WCHAR Local_AppDataW[] = {'L','o','c','a','l',' ','A','p','p','D','a','t','a','\0'};
792 static const WCHAR My_MusicW[] = {'M','y',' ','M','u','s','i','c','\0'};
793 static const WCHAR My_PicturesW[] = {'M','y',' ','P','i','c','t','u','r','e','s','\0'};
794 static const WCHAR My_VideoW[] = {'M','y',' ','V','i','d','e','o','s','\0'};
795 static const WCHAR NetHoodW[] = {'N','e','t','H','o','o','d','\0'};
796 static const WCHAR PersonalW[] = {'P','e','r','s','o','n','a','l','\0'};
797 static const WCHAR PrintHoodW[] = {'P','r','i','n','t','H','o','o','d','\0'};
798 static const WCHAR ProgramFilesDirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r','\0'};
799 static const WCHAR ProgramFilesDirX86W[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r',' ','(','x','8','6',')','\0'};
800 static const WCHAR ProgramsW[] = {'P','r','o','g','r','a','m','s','\0'};
801 static const WCHAR RecentW[] = {'R','e','c','e','n','t','\0'};
802 static const WCHAR ResourcesW[] = {'R','e','s','o','u','r','c','e','s','\0'};
803 static const WCHAR SendToW[] = {'S','e','n','d','T','o','\0'};
804 static const WCHAR StartUpW[] = {'S','t','a','r','t','U','p','\0'};
805 static const WCHAR Start_MenuW[] = {'S','t','a','r','t',' ','M','e','n','u','\0'};
806 static const WCHAR TemplatesW[] = {'T','e','m','p','l','a','t','e','s','\0'};
807 static const WCHAR UsersW[] = {'U','s','e','r','s','\0'};
808 static const WCHAR UsersPublicW[] = {'U','s','e','r','s','\\','P','u','b','l','i','c','\0'};
809 static const WCHAR DefaultW[] = {'.','D','e','f','a','u','l','t','\0'};
810 static const WCHAR AllUsersProfileW[] = {'%','A','L','L','U','S','E','R','S','P','R','O','F','I','L','E','%','\0'};
811 static const WCHAR UserProfileW[] = {'%','U','S','E','R','P','R','O','F','I','L','E','%','\0'};
812 static const WCHAR SystemDriveW[] = {'%','S','y','s','t','e','m','D','r','i','v','e','%','\0'};
813 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};
814 static const WCHAR ProfilesDirectoryW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
815 static const WCHAR AllUsersProfileValueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
816 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'};
817 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'};
818 static const WCHAR szDefaultProfileDirW[] = {'u','s','e','r','s',0};
819 static const WCHAR AllUsersW[] = {'P','u','b','l','i','c',0};
820
821 typedef enum _CSIDL_Type {
822     CSIDL_Type_User,
823     CSIDL_Type_AllUsers,
824     CSIDL_Type_CurrVer,
825     CSIDL_Type_Disallowed,
826     CSIDL_Type_NonExistent,
827     CSIDL_Type_WindowsPath,
828     CSIDL_Type_SystemPath,
829     CSIDL_Type_SystemX86Path,
830 } CSIDL_Type;
831
832 typedef struct
833 {
834     const KNOWNFOLDERID *id;
835     CSIDL_Type type;
836     LPCWSTR    szValueName;
837     LPCWSTR    szDefaultPath; /* fallback string or resource ID */
838 } CSIDL_DATA;
839
840 static const CSIDL_DATA CSIDL_Data[] =
841 {
842     { /* 0x00 - CSIDL_DESKTOP */
843         &FOLDERID_Desktop,
844         CSIDL_Type_User,
845         DesktopW,
846         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
847     },
848     { /* 0x01 - CSIDL_INTERNET */
849         &FOLDERID_InternetFolder,
850         CSIDL_Type_Disallowed,
851         NULL,
852         NULL
853     },
854     { /* 0x02 - CSIDL_PROGRAMS */
855         &FOLDERID_Programs,
856         CSIDL_Type_User,
857         ProgramsW,
858         MAKEINTRESOURCEW(IDS_PROGRAMS)
859     },
860     { /* 0x03 - CSIDL_CONTROLS (.CPL files) */
861         &FOLDERID_ControlPanelFolder,
862         CSIDL_Type_SystemPath,
863         NULL,
864         NULL
865     },
866     { /* 0x04 - CSIDL_PRINTERS */
867         &FOLDERID_PrintersFolder,
868         CSIDL_Type_SystemPath,
869         NULL,
870         NULL
871     },
872     { /* 0x05 - CSIDL_PERSONAL */
873         &GUID_NULL,
874         CSIDL_Type_User,
875         PersonalW,
876         MAKEINTRESOURCEW(IDS_PERSONAL)
877     },
878     { /* 0x06 - CSIDL_FAVORITES */
879         &FOLDERID_Favorites,
880         CSIDL_Type_User,
881         FavoritesW,
882         MAKEINTRESOURCEW(IDS_FAVORITES)
883     },
884     { /* 0x07 - CSIDL_STARTUP */
885         &FOLDERID_Startup,
886         CSIDL_Type_User,
887         StartUpW,
888         MAKEINTRESOURCEW(IDS_STARTUP)
889     },
890     { /* 0x08 - CSIDL_RECENT */
891         &FOLDERID_Recent,
892         CSIDL_Type_User,
893         RecentW,
894         MAKEINTRESOURCEW(IDS_RECENT)
895     },
896     { /* 0x09 - CSIDL_SENDTO */
897         &FOLDERID_SendTo,
898         CSIDL_Type_User,
899         SendToW,
900         MAKEINTRESOURCEW(IDS_SENDTO)
901     },
902     { /* 0x0a - CSIDL_BITBUCKET - Recycle Bin */
903         &FOLDERID_RecycleBinFolder,
904         CSIDL_Type_Disallowed,
905         NULL,
906         NULL,
907     },
908     { /* 0x0b - CSIDL_STARTMENU */
909         &FOLDERID_StartMenu,
910         CSIDL_Type_User,
911         Start_MenuW,
912         MAKEINTRESOURCEW(IDS_STARTMENU)
913     },
914     { /* 0x0c - CSIDL_MYDOCUMENTS */
915         &GUID_NULL,
916         CSIDL_Type_Disallowed, /* matches WinXP--can't get its path */
917         NULL,
918         NULL
919     },
920     { /* 0x0d - CSIDL_MYMUSIC */
921         &FOLDERID_Music,
922         CSIDL_Type_User,
923         My_MusicW,
924         MAKEINTRESOURCEW(IDS_MYMUSIC)
925     },
926     { /* 0x0e - CSIDL_MYVIDEO */
927         &FOLDERID_Videos,
928         CSIDL_Type_User,
929         My_VideoW,
930         MAKEINTRESOURCEW(IDS_MYVIDEO)
931     },
932     { /* 0x0f - unassigned */
933         &GUID_NULL,
934         CSIDL_Type_Disallowed,
935         NULL,
936         NULL,
937     },
938     { /* 0x10 - CSIDL_DESKTOPDIRECTORY */
939         &FOLDERID_Desktop,
940         CSIDL_Type_User,
941         DesktopW,
942         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
943     },
944     { /* 0x11 - CSIDL_DRIVES */
945         &FOLDERID_ComputerFolder,
946         CSIDL_Type_Disallowed,
947         NULL,
948         NULL,
949     },
950     { /* 0x12 - CSIDL_NETWORK */
951         &FOLDERID_NetworkFolder,
952         CSIDL_Type_Disallowed,
953         NULL,
954         NULL,
955     },
956     { /* 0x13 - CSIDL_NETHOOD */
957         &FOLDERID_NetHood,
958         CSIDL_Type_User,
959         NetHoodW,
960         MAKEINTRESOURCEW(IDS_NETHOOD)
961     },
962     { /* 0x14 - CSIDL_FONTS */
963         &FOLDERID_Fonts,
964         CSIDL_Type_WindowsPath,
965         FontsW,
966         FontsW
967     },
968     { /* 0x15 - CSIDL_TEMPLATES */
969         &FOLDERID_Templates,
970         CSIDL_Type_User,
971         TemplatesW,
972         MAKEINTRESOURCEW(IDS_TEMPLATES)
973     },
974     { /* 0x16 - CSIDL_COMMON_STARTMENU */
975         &FOLDERID_CommonStartMenu,
976         CSIDL_Type_AllUsers,
977         Common_Start_MenuW,
978         MAKEINTRESOURCEW(IDS_STARTMENU)
979     },
980     { /* 0x17 - CSIDL_COMMON_PROGRAMS */
981         &FOLDERID_CommonPrograms,
982         CSIDL_Type_AllUsers,
983         Common_ProgramsW,
984         MAKEINTRESOURCEW(IDS_PROGRAMS)
985     },
986     { /* 0x18 - CSIDL_COMMON_STARTUP */
987         &FOLDERID_CommonStartup,
988         CSIDL_Type_AllUsers,
989         Common_StartUpW,
990         MAKEINTRESOURCEW(IDS_STARTUP)
991     },
992     { /* 0x19 - CSIDL_COMMON_DESKTOPDIRECTORY */
993         &FOLDERID_PublicDesktop,
994         CSIDL_Type_AllUsers,
995         Common_DesktopW,
996         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
997     },
998     { /* 0x1a - CSIDL_APPDATA */
999         &FOLDERID_RoamingAppData,
1000         CSIDL_Type_User,
1001         AppDataW,
1002         MAKEINTRESOURCEW(IDS_APPDATA)
1003     },
1004     { /* 0x1b - CSIDL_PRINTHOOD */
1005         &FOLDERID_PrintHood,
1006         CSIDL_Type_User,
1007         PrintHoodW,
1008         MAKEINTRESOURCEW(IDS_PRINTHOOD)
1009     },
1010     { /* 0x1c - CSIDL_LOCAL_APPDATA */
1011         &FOLDERID_LocalAppData,
1012         CSIDL_Type_User,
1013         Local_AppDataW,
1014         MAKEINTRESOURCEW(IDS_LOCAL_APPDATA)
1015     },
1016     { /* 0x1d - CSIDL_ALTSTARTUP */
1017         &GUID_NULL,
1018         CSIDL_Type_NonExistent,
1019         NULL,
1020         NULL
1021     },
1022     { /* 0x1e - CSIDL_COMMON_ALTSTARTUP */
1023         &GUID_NULL,
1024         CSIDL_Type_NonExistent,
1025         NULL,
1026         NULL
1027     },
1028     { /* 0x1f - CSIDL_COMMON_FAVORITES */
1029         &FOLDERID_Favorites,
1030         CSIDL_Type_AllUsers,
1031         Common_FavoritesW,
1032         MAKEINTRESOURCEW(IDS_FAVORITES)
1033     },
1034     { /* 0x20 - CSIDL_INTERNET_CACHE */
1035         &FOLDERID_InternetCache,
1036         CSIDL_Type_User,
1037         CacheW,
1038         MAKEINTRESOURCEW(IDS_INTERNET_CACHE)
1039     },
1040     { /* 0x21 - CSIDL_COOKIES */
1041         &FOLDERID_Cookies,
1042         CSIDL_Type_User,
1043         CookiesW,
1044         MAKEINTRESOURCEW(IDS_COOKIES)
1045     },
1046     { /* 0x22 - CSIDL_HISTORY */
1047         &FOLDERID_History,
1048         CSIDL_Type_User,
1049         HistoryW,
1050         MAKEINTRESOURCEW(IDS_HISTORY)
1051     },
1052     { /* 0x23 - CSIDL_COMMON_APPDATA */
1053         &FOLDERID_ProgramData,
1054         CSIDL_Type_AllUsers,
1055         Common_AppDataW,
1056         MAKEINTRESOURCEW(IDS_APPDATA)
1057     },
1058     { /* 0x24 - CSIDL_WINDOWS */
1059         &FOLDERID_Windows,
1060         CSIDL_Type_WindowsPath,
1061         NULL,
1062         NULL
1063     },
1064     { /* 0x25 - CSIDL_SYSTEM */
1065         &FOLDERID_System,
1066         CSIDL_Type_SystemPath,
1067         NULL,
1068         NULL
1069     },
1070     { /* 0x26 - CSIDL_PROGRAM_FILES */
1071         &FOLDERID_ProgramFiles,
1072         CSIDL_Type_CurrVer,
1073         ProgramFilesDirW,
1074         MAKEINTRESOURCEW(IDS_PROGRAM_FILES)
1075     },
1076     { /* 0x27 - CSIDL_MYPICTURES */
1077         &FOLDERID_Pictures,
1078         CSIDL_Type_User,
1079         My_PicturesW,
1080         MAKEINTRESOURCEW(IDS_MYPICTURES)
1081     },
1082     { /* 0x28 - CSIDL_PROFILE */
1083         &FOLDERID_Profile,
1084         CSIDL_Type_User,
1085         NULL,
1086         NULL
1087     },
1088     { /* 0x29 - CSIDL_SYSTEMX86 */
1089         &FOLDERID_SystemX86,
1090         CSIDL_Type_SystemX86Path,
1091         NULL,
1092         NULL
1093     },
1094     { /* 0x2a - CSIDL_PROGRAM_FILESX86 */
1095         &FOLDERID_ProgramFilesX86,
1096         CSIDL_Type_CurrVer,
1097         ProgramFilesDirX86W,
1098         MAKEINTRESOURCEW(IDS_PROGRAM_FILESX86)
1099     },
1100     { /* 0x2b - CSIDL_PROGRAM_FILES_COMMON */
1101         &FOLDERID_ProgramFilesCommon,
1102         CSIDL_Type_CurrVer,
1103         CommonFilesDirW,
1104         MAKEINTRESOURCEW(IDS_PROGRAM_FILES_COMMON)
1105     },
1106     { /* 0x2c - CSIDL_PROGRAM_FILES_COMMONX86 */
1107         &FOLDERID_ProgramFilesCommonX86,
1108         CSIDL_Type_CurrVer,
1109         CommonFilesDirX86W,
1110         MAKEINTRESOURCEW(IDS_PROGRAM_FILES_COMMONX86)
1111     },
1112     { /* 0x2d - CSIDL_COMMON_TEMPLATES */
1113         &FOLDERID_CommonTemplates,
1114         CSIDL_Type_AllUsers,
1115         Common_TemplatesW,
1116         MAKEINTRESOURCEW(IDS_TEMPLATES)
1117     },
1118     { /* 0x2e - CSIDL_COMMON_DOCUMENTS */
1119         &FOLDERID_PublicDocuments,
1120         CSIDL_Type_AllUsers,
1121         Common_DocumentsW,
1122         MAKEINTRESOURCEW(IDS_COMMON_DOCUMENTS)
1123     },
1124     { /* 0x2f - CSIDL_COMMON_ADMINTOOLS */
1125         &FOLDERID_CommonAdminTools,
1126         CSIDL_Type_AllUsers,
1127         Common_Administrative_ToolsW,
1128         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1129     },
1130     { /* 0x30 - CSIDL_ADMINTOOLS */
1131         &FOLDERID_AdminTools,
1132         CSIDL_Type_User,
1133         Administrative_ToolsW,
1134         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1135     },
1136     { /* 0x31 - CSIDL_CONNECTIONS */
1137         &FOLDERID_ConnectionsFolder,
1138         CSIDL_Type_Disallowed,
1139         NULL,
1140         NULL
1141     },
1142     { /* 0x32 - unassigned */
1143         &GUID_NULL,
1144         CSIDL_Type_Disallowed,
1145         NULL,
1146         NULL
1147     },
1148     { /* 0x33 - unassigned */
1149         &GUID_NULL,
1150         CSIDL_Type_Disallowed,
1151         NULL,
1152         NULL
1153     },
1154     { /* 0x34 - unassigned */
1155         &GUID_NULL,
1156         CSIDL_Type_Disallowed,
1157         NULL,
1158         NULL
1159     },
1160     { /* 0x35 - CSIDL_COMMON_MUSIC */
1161         &FOLDERID_PublicMusic,
1162         CSIDL_Type_AllUsers,
1163         CommonMusicW,
1164         MAKEINTRESOURCEW(IDS_COMMON_MUSIC)
1165     },
1166     { /* 0x36 - CSIDL_COMMON_PICTURES */
1167         &FOLDERID_PublicPictures,
1168         CSIDL_Type_AllUsers,
1169         CommonPicturesW,
1170         MAKEINTRESOURCEW(IDS_COMMON_PICTURES)
1171     },
1172     { /* 0x37 - CSIDL_COMMON_VIDEO */
1173         &FOLDERID_PublicVideos,
1174         CSIDL_Type_AllUsers,
1175         CommonVideoW,
1176         MAKEINTRESOURCEW(IDS_COMMON_VIDEO)
1177     },
1178     { /* 0x38 - CSIDL_RESOURCES */
1179         &FOLDERID_ResourceDir,
1180         CSIDL_Type_WindowsPath,
1181         NULL,
1182         ResourcesW
1183     },
1184     { /* 0x39 - CSIDL_RESOURCES_LOCALIZED */
1185         &FOLDERID_LocalizedResourcesDir,
1186         CSIDL_Type_NonExistent,
1187         NULL,
1188         NULL
1189     },
1190     { /* 0x3a - CSIDL_COMMON_OEM_LINKS */
1191         &FOLDERID_CommonOEMLinks,
1192         CSIDL_Type_AllUsers,
1193         NULL,
1194         MAKEINTRESOURCEW(IDS_COMMON_OEM_LINKS)
1195     },
1196     { /* 0x3b - CSIDL_CDBURN_AREA */
1197         &FOLDERID_CDBurning,
1198         CSIDL_Type_User,
1199         CD_BurningW,
1200         MAKEINTRESOURCEW(IDS_CDBURN_AREA)
1201     },
1202     { /* 0x3c unassigned */
1203         &GUID_NULL,
1204         CSIDL_Type_Disallowed,
1205         NULL,
1206         NULL
1207     },
1208     { /* 0x3d - CSIDL_COMPUTERSNEARME */
1209         &GUID_NULL,
1210         CSIDL_Type_Disallowed, /* FIXME */
1211         NULL,
1212         NULL
1213     },
1214     { /* 0x3e - CSIDL_PROFILES */
1215         &GUID_NULL,
1216         CSIDL_Type_Disallowed, /* oddly, this matches WinXP */
1217         NULL,
1218         NULL
1219     },
1220     { /* 0x3f */
1221         &FOLDERID_AddNewPrograms,
1222         CSIDL_Type_Disallowed,
1223         NULL,
1224         NULL
1225     },
1226     { /* 0x40 */
1227         &FOLDERID_AppUpdates,
1228         CSIDL_Type_Disallowed,
1229         NULL,
1230         NULL
1231     },
1232     { /* 0x41 */
1233         &FOLDERID_ChangeRemovePrograms,
1234         CSIDL_Type_Disallowed,
1235         NULL,
1236         NULL
1237     },
1238     { /* 0x42 */
1239         &FOLDERID_ConflictFolder,
1240         CSIDL_Type_Disallowed,
1241         NULL,
1242         NULL
1243     },
1244     { /* 0x43 */
1245         &FOLDERID_Contacts,
1246         CSIDL_Type_User,
1247         ContactsW,
1248         MAKEINTRESOURCEW(IDS_CONTACTS)
1249     },
1250     { /* 0x44 */
1251         &FOLDERID_DeviceMetadataStore,
1252         CSIDL_Type_Disallowed, /* FIXME */
1253         NULL,
1254         NULL
1255     },
1256     { /* 0x45 */
1257         &FOLDERID_Documents,
1258         CSIDL_Type_User,
1259         NULL,
1260         MAKEINTRESOURCEW(IDS_DOCUMENTS)
1261     },
1262     { /* 0x46 */
1263         &FOLDERID_DocumentsLibrary,
1264         CSIDL_Type_Disallowed, /* FIXME */
1265         NULL,
1266         NULL
1267     },
1268     { /* 0x47 */
1269         &FOLDERID_Downloads,
1270         CSIDL_Type_User,
1271         NULL,
1272         MAKEINTRESOURCEW(IDS_DOWNLOADS)
1273     },
1274     { /* 0x48 */
1275         &FOLDERID_Games,
1276         CSIDL_Type_Disallowed,
1277         NULL,
1278         NULL
1279     },
1280     { /* 0x49 */
1281         &FOLDERID_GameTasks,
1282         CSIDL_Type_Disallowed, /* FIXME */
1283         NULL,
1284         NULL
1285     },
1286     { /* 0x4a */
1287         &FOLDERID_HomeGroup,
1288         CSIDL_Type_Disallowed,
1289         NULL,
1290         NULL
1291     },
1292     { /* 0x4b */
1293         &FOLDERID_ImplicitAppShortcuts,
1294         CSIDL_Type_Disallowed, /* FIXME */
1295         NULL,
1296         NULL
1297     },
1298     { /* 0x4c */
1299         &FOLDERID_Libraries,
1300         CSIDL_Type_Disallowed, /* FIXME */
1301         NULL,
1302         NULL
1303     },
1304     { /* 0x4d */
1305         &FOLDERID_Links,
1306         CSIDL_Type_User,
1307         NULL,
1308         MAKEINTRESOURCEW(IDS_LINKS)
1309     },
1310     { /* 0x4e */
1311         &FOLDERID_LocalAppDataLow,
1312         CSIDL_Type_User,
1313         NULL,
1314         MAKEINTRESOURCEW(IDS_LOCAL_APPDATA_LOW)
1315     },
1316     { /* 0x4f */
1317         &FOLDERID_MusicLibrary,
1318         CSIDL_Type_Disallowed, /* FIXME */
1319         NULL,
1320         NULL
1321     },
1322     { /* 0x50 */
1323         &FOLDERID_OriginalImages,
1324         CSIDL_Type_Disallowed, /* FIXME */
1325         NULL,
1326         NULL
1327     },
1328     { /* 0x51 */
1329         &FOLDERID_PhotoAlbums,
1330         CSIDL_Type_User,
1331         NULL,
1332         MAKEINTRESOURCEW(IDS_PHOTO_ALBUMS)
1333     },
1334     { /* 0x52 */
1335         &FOLDERID_PicturesLibrary,
1336         CSIDL_Type_Disallowed, /* FIXME */
1337         NULL,
1338         NULL
1339     },
1340     { /* 0x53 */
1341         &FOLDERID_Playlists,
1342         CSIDL_Type_User,
1343         NULL,
1344         MAKEINTRESOURCEW(IDS_PLAYLISTS)
1345     },
1346     { /* 0x54 */
1347         &FOLDERID_ProgramFilesX64,
1348         CSIDL_Type_NonExistent,
1349         NULL,
1350         NULL
1351     },
1352     { /* 0x55 */
1353         &FOLDERID_ProgramFilesCommonX64,
1354         CSIDL_Type_NonExistent,
1355         NULL,
1356         NULL
1357     },
1358     { /* 0x56 */
1359         &FOLDERID_Public,
1360         CSIDL_Type_CurrVer, /* FIXME */
1361         NULL,
1362         UsersPublicW
1363     },
1364     { /* 0x57 */
1365         &FOLDERID_PublicDownloads,
1366         CSIDL_Type_AllUsers,
1367         NULL,
1368         MAKEINTRESOURCEW(IDS_PUBLIC_DOWNLOADS)
1369     },
1370     { /* 0x58 */
1371         &FOLDERID_PublicGameTasks,
1372         CSIDL_Type_AllUsers,
1373         NULL,
1374         MAKEINTRESOURCEW(IDS_PUBLIC_GAME_TASKS)
1375     },
1376     { /* 0x59 */
1377         &FOLDERID_PublicLibraries,
1378         CSIDL_Type_AllUsers,
1379         NULL,
1380         MAKEINTRESOURCEW(IDS_PUBLIC_LIBRARIES)
1381     },
1382     { /* 0x5a */
1383         &FOLDERID_PublicRingtones,
1384         CSIDL_Type_AllUsers,
1385         NULL,
1386         MAKEINTRESOURCEW(IDS_PUBLIC_RINGTONES)
1387     },
1388     { /* 0x5b */
1389         &FOLDERID_QuickLaunch,
1390         CSIDL_Type_Disallowed, /* FIXME */
1391         NULL,
1392         NULL
1393     },
1394     { /* 0x5c */
1395         &FOLDERID_RecordedTVLibrary,
1396         CSIDL_Type_Disallowed, /* FIXME */
1397         NULL,
1398         NULL
1399     },
1400     { /* 0x5d */
1401         &FOLDERID_Ringtones,
1402         CSIDL_Type_Disallowed, /* FIXME */
1403         NULL,
1404         NULL
1405     },
1406     { /* 0x5e */
1407         &FOLDERID_SampleMusic,
1408         CSIDL_Type_AllUsers,
1409         NULL,
1410         MAKEINTRESOURCEW(IDS_SAMPLE_MUSIC)
1411     },
1412     { /* 0x5f */
1413         &FOLDERID_SamplePictures,
1414         CSIDL_Type_AllUsers,
1415         NULL,
1416         MAKEINTRESOURCEW(IDS_SAMPLE_PICTURES)
1417     },
1418     { /* 0x60 */
1419         &FOLDERID_SamplePlaylists,
1420         CSIDL_Type_AllUsers,
1421         NULL,
1422         MAKEINTRESOURCEW(IDS_SAMPLE_PLAYLISTS)
1423     },
1424     { /* 0x61 */
1425         &FOLDERID_SampleVideos,
1426         CSIDL_Type_AllUsers,
1427         NULL,
1428         MAKEINTRESOURCEW(IDS_SAMPLE_VIDEOS)
1429     },
1430     { /* 0x62 */
1431         &FOLDERID_SavedGames,
1432         CSIDL_Type_User,
1433         NULL,
1434         MAKEINTRESOURCEW(IDS_SAVED_GAMES)
1435     },
1436     { /* 0x63 */
1437         &FOLDERID_SavedSearches,
1438         CSIDL_Type_User,
1439         NULL,
1440         MAKEINTRESOURCEW(IDS_SAVED_SEARCHES)
1441     },
1442     { /* 0x64 */
1443         &FOLDERID_SEARCH_CSC,
1444         CSIDL_Type_Disallowed,
1445         NULL,
1446         NULL
1447     },
1448     { /* 0x65 */
1449         &FOLDERID_SEARCH_MAPI,
1450         CSIDL_Type_Disallowed,
1451         NULL,
1452         NULL
1453     },
1454     { /* 0x66 */
1455         &FOLDERID_SearchHome,
1456         CSIDL_Type_Disallowed,
1457         NULL,
1458         NULL
1459     },
1460     { /* 0x67 */
1461         &FOLDERID_SidebarDefaultParts,
1462         CSIDL_Type_Disallowed, /* FIXME */
1463         NULL,
1464         NULL
1465     },
1466     { /* 0x68 */
1467         &FOLDERID_SidebarParts,
1468         CSIDL_Type_Disallowed, /* FIXME */
1469         NULL,
1470         NULL
1471     },
1472     { /* 0x69 */
1473         &FOLDERID_SyncManagerFolder,
1474         CSIDL_Type_Disallowed,
1475         NULL,
1476         NULL
1477     },
1478     { /* 0x6a */
1479         &FOLDERID_SyncResultsFolder,
1480         CSIDL_Type_Disallowed,
1481         NULL,
1482         NULL
1483     },
1484     { /* 0x6b */
1485         &FOLDERID_SyncSetupFolder,
1486         CSIDL_Type_Disallowed,
1487         NULL,
1488         NULL
1489     },
1490     { /* 0x6c */
1491         &FOLDERID_UserPinned,
1492         CSIDL_Type_Disallowed, /* FIXME */
1493         NULL,
1494         NULL
1495     },
1496     { /* 0x6d */
1497         &FOLDERID_UserProfiles,
1498         CSIDL_Type_CurrVer,
1499         UsersW,
1500         MAKEINTRESOURCEW(IDS_USER_PROFILES)
1501     },
1502     { /* 0x6e */
1503         &FOLDERID_UserProgramFiles,
1504         CSIDL_Type_Disallowed, /* FIXME */
1505         NULL,
1506         NULL
1507     },
1508     { /* 0x6f */
1509         &FOLDERID_UserProgramFilesCommon,
1510         CSIDL_Type_Disallowed, /* FIXME */
1511         NULL,
1512         NULL
1513     },
1514     { /* 0x70 */
1515         &FOLDERID_UsersFiles,
1516         CSIDL_Type_Disallowed,
1517         NULL,
1518         NULL
1519     },
1520     { /* 0x71 */
1521         &FOLDERID_UsersLibraries,
1522         CSIDL_Type_Disallowed,
1523         NULL,
1524         NULL
1525     },
1526     { /* 0x72 */
1527         &FOLDERID_VideosLibrary,
1528         CSIDL_Type_Disallowed, /* FIXME */
1529         NULL,
1530         NULL
1531     }
1532 };
1533
1534 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest);
1535
1536 /* Gets the value named value from the registry key
1537  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
1538  * (or from rootKey\userPrefix\... if userPrefix is not NULL) into path, which
1539  * is assumed to be MAX_PATH WCHARs in length.
1540  * If it exists, expands the value and writes the expanded value to
1541  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
1542  * Returns successful error code if the value was retrieved from the registry,
1543  * and a failure otherwise.
1544  */
1545 static HRESULT _SHGetUserShellFolderPath(HKEY rootKey, LPCWSTR userPrefix,
1546  LPCWSTR value, LPWSTR path)
1547 {
1548     HRESULT hr;
1549     WCHAR shellFolderPath[MAX_PATH], userShellFolderPath[MAX_PATH];
1550     LPCWSTR pShellFolderPath, pUserShellFolderPath;
1551     DWORD dwType, dwPathLen = MAX_PATH;
1552     HKEY userShellFolderKey, shellFolderKey;
1553
1554     TRACE("%p,%s,%s,%p\n",rootKey, debugstr_w(userPrefix), debugstr_w(value),
1555      path);
1556
1557     if (userPrefix)
1558     {
1559         strcpyW(shellFolderPath, userPrefix);
1560         PathAddBackslashW(shellFolderPath);
1561         strcatW(shellFolderPath, szSHFolders);
1562         pShellFolderPath = shellFolderPath;
1563         strcpyW(userShellFolderPath, userPrefix);
1564         PathAddBackslashW(userShellFolderPath);
1565         strcatW(userShellFolderPath, szSHUserFolders);
1566         pUserShellFolderPath = userShellFolderPath;
1567     }
1568     else
1569     {
1570         pUserShellFolderPath = szSHUserFolders;
1571         pShellFolderPath = szSHFolders;
1572     }
1573
1574     if (RegCreateKeyW(rootKey, pShellFolderPath, &shellFolderKey))
1575     {
1576         TRACE("Failed to create %s\n", debugstr_w(pShellFolderPath));
1577         return E_FAIL;
1578     }
1579     if (RegCreateKeyW(rootKey, pUserShellFolderPath, &userShellFolderKey))
1580     {
1581         TRACE("Failed to create %s\n",
1582          debugstr_w(pUserShellFolderPath));
1583         RegCloseKey(shellFolderKey);
1584         return E_FAIL;
1585     }
1586
1587     if (!RegQueryValueExW(userShellFolderKey, value, NULL, &dwType,
1588      (LPBYTE)path, &dwPathLen) && (dwType == REG_EXPAND_SZ || dwType == REG_SZ))
1589     {
1590         LONG ret;
1591
1592         path[dwPathLen / sizeof(WCHAR)] = '\0';
1593         if (dwType == REG_EXPAND_SZ && path[0] == '%')
1594         {
1595             WCHAR szTemp[MAX_PATH];
1596
1597             _SHExpandEnvironmentStrings(path, szTemp);
1598             lstrcpynW(path, szTemp, MAX_PATH);
1599         }
1600         ret = RegSetValueExW(shellFolderKey, value, 0, REG_SZ, (LPBYTE)path,
1601          (strlenW(path) + 1) * sizeof(WCHAR));
1602         if (ret != ERROR_SUCCESS)
1603             hr = HRESULT_FROM_WIN32(ret);
1604         else
1605             hr = S_OK;
1606     }
1607     else
1608         hr = E_FAIL;
1609     RegCloseKey(shellFolderKey);
1610     RegCloseKey(userShellFolderKey);
1611     TRACE("returning 0x%08x\n", hr);
1612     return hr;
1613 }
1614
1615 /* Gets a 'semi-expanded' default value of the CSIDL with index folder into
1616  * pszPath, based on the entries in CSIDL_Data.  By semi-expanded, I mean:
1617  * - The entry's szDefaultPath may be either a string value or an integer
1618  *   resource identifier.  In the latter case, the string value of the resource
1619  *   is written.
1620  * - Depending on the entry's type, the path may begin with an (unexpanded)
1621  *   environment variable name.  The caller is responsible for expanding
1622  *   environment strings if so desired.
1623  *   The types that are prepended with environment variables are:
1624  *   CSIDL_Type_User:     %USERPROFILE%
1625  *   CSIDL_Type_AllUsers: %ALLUSERSPROFILE%
1626  *   CSIDL_Type_CurrVer:  %SystemDrive%
1627  *   (Others might make sense too, but as yet are unneeded.)
1628  */
1629 static HRESULT _SHGetDefaultValue(BYTE folder, LPWSTR pszPath)
1630 {
1631     HRESULT hr;
1632     WCHAR resourcePath[MAX_PATH];
1633     LPCWSTR pDefaultPath = NULL;
1634
1635     TRACE("0x%02x,%p\n", folder, pszPath);
1636
1637     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1638         return E_INVALIDARG;
1639     if (!pszPath)
1640         return E_INVALIDARG;
1641
1642     if (!is_win64)
1643     {
1644         BOOL is_wow64;
1645
1646         switch (folder)
1647         {
1648         case CSIDL_PROGRAM_FILES:
1649         case CSIDL_PROGRAM_FILESX86:
1650             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1651             folder = is_wow64 ? CSIDL_PROGRAM_FILESX86 : CSIDL_PROGRAM_FILES;
1652             break;
1653         case CSIDL_PROGRAM_FILES_COMMON:
1654         case CSIDL_PROGRAM_FILES_COMMONX86:
1655             IsWow64Process( GetCurrentProcess(), &is_wow64 );
1656             folder = is_wow64 ? CSIDL_PROGRAM_FILES_COMMONX86 : CSIDL_PROGRAM_FILES_COMMON;
1657             break;
1658         }
1659     }
1660
1661     if (CSIDL_Data[folder].szDefaultPath &&
1662      IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath))
1663     {
1664         if (LoadStringW(shell32_hInstance,
1665          LOWORD(CSIDL_Data[folder].szDefaultPath), resourcePath, MAX_PATH))
1666         {
1667             hr = S_OK;
1668             pDefaultPath = resourcePath;
1669         }
1670         else
1671         {
1672             FIXME("(%d,%s), LoadString failed, missing translation?\n", folder,
1673              debugstr_w(pszPath));
1674             hr = E_FAIL;
1675         }
1676     }
1677     else
1678     {
1679         hr = S_OK;
1680         pDefaultPath = CSIDL_Data[folder].szDefaultPath;
1681     }
1682     if (SUCCEEDED(hr))
1683     {
1684         switch (CSIDL_Data[folder].type)
1685         {
1686             case CSIDL_Type_User:
1687                 strcpyW(pszPath, UserProfileW);
1688                 break;
1689             case CSIDL_Type_AllUsers:
1690                 strcpyW(pszPath, AllUsersProfileW);
1691                 break;
1692             case CSIDL_Type_CurrVer:
1693                 strcpyW(pszPath, SystemDriveW);
1694                 break;
1695             default:
1696                 ; /* no corresponding env. var, do nothing */
1697         }
1698         if (pDefaultPath)
1699         {
1700             PathAddBackslashW(pszPath);
1701             strcatW(pszPath, pDefaultPath);
1702         }
1703     }
1704     TRACE("returning 0x%08x\n", hr);
1705     return hr;
1706 }
1707
1708 /* Gets the (unexpanded) value of the folder with index folder into pszPath.
1709  * The folder's type is assumed to be CSIDL_Type_CurrVer.  Its default value
1710  * can be overridden in the HKLM\\szCurrentVersion key.
1711  * If dwFlags has SHGFP_TYPE_DEFAULT set or if the value isn't overridden in
1712  * the registry, uses _SHGetDefaultValue to get the value.
1713  */
1714 static HRESULT _SHGetCurrentVersionPath(DWORD dwFlags, BYTE folder,
1715  LPWSTR pszPath)
1716 {
1717     HRESULT hr;
1718
1719     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1720
1721     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1722         return E_INVALIDARG;
1723     if (CSIDL_Data[folder].type != CSIDL_Type_CurrVer)
1724         return E_INVALIDARG;
1725     if (!pszPath)
1726         return E_INVALIDARG;
1727
1728     if (dwFlags & SHGFP_TYPE_DEFAULT)
1729         hr = _SHGetDefaultValue(folder, pszPath);
1730     else
1731     {
1732         HKEY hKey;
1733
1734         if (RegCreateKeyW(HKEY_LOCAL_MACHINE, szCurrentVersion, &hKey))
1735             hr = E_FAIL;
1736         else
1737         {
1738             DWORD dwType, dwPathLen = MAX_PATH * sizeof(WCHAR);
1739
1740             if (RegQueryValueExW(hKey, CSIDL_Data[folder].szValueName, NULL,
1741              &dwType, (LPBYTE)pszPath, &dwPathLen) ||
1742              (dwType != REG_SZ && dwType != REG_EXPAND_SZ))
1743             {
1744                 hr = _SHGetDefaultValue(folder, pszPath);
1745                 dwType = REG_EXPAND_SZ;
1746                 switch (folder)
1747                 {
1748                 case CSIDL_PROGRAM_FILESX86:
1749                 case CSIDL_PROGRAM_FILES_COMMONX86:
1750                     /* these two should never be set on 32-bit setups */
1751                     if (!is_win64)
1752                     {
1753                         BOOL is_wow64;
1754                         IsWow64Process( GetCurrentProcess(), &is_wow64 );
1755                         if (!is_wow64) break;
1756                     }
1757                     /* fall through */
1758                 default:
1759                     RegSetValueExW(hKey, CSIDL_Data[folder].szValueName, 0, dwType,
1760                                    (LPBYTE)pszPath, (strlenW(pszPath)+1)*sizeof(WCHAR));
1761                 }
1762             }
1763             else
1764             {
1765                 pszPath[dwPathLen / sizeof(WCHAR)] = '\0';
1766                 hr = S_OK;
1767             }
1768             RegCloseKey(hKey);
1769         }
1770     }
1771     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1772     return hr;
1773 }
1774
1775 static LPWSTR _GetUserSidStringFromToken(HANDLE Token)
1776 {
1777     char InfoBuffer[64];
1778     PTOKEN_USER UserInfo;
1779     DWORD InfoSize;
1780     LPWSTR SidStr;
1781
1782     UserInfo = (PTOKEN_USER) InfoBuffer;
1783     if (! GetTokenInformation(Token, TokenUser, InfoBuffer, sizeof(InfoBuffer),
1784                               &InfoSize))
1785     {
1786         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1787             return NULL;
1788         UserInfo = HeapAlloc(GetProcessHeap(), 0, InfoSize);
1789         if (UserInfo == NULL)
1790             return NULL;
1791         if (! GetTokenInformation(Token, TokenUser, UserInfo, InfoSize,
1792                                   &InfoSize))
1793         {
1794             HeapFree(GetProcessHeap(), 0, UserInfo);
1795             return NULL;
1796         }
1797     }
1798
1799     if (! ConvertSidToStringSidW(UserInfo->User.Sid, &SidStr))
1800         SidStr = NULL;
1801
1802     if (UserInfo != (PTOKEN_USER) InfoBuffer)
1803         HeapFree(GetProcessHeap(), 0, UserInfo);
1804
1805     return SidStr;
1806 }
1807
1808 /* Gets the user's path (unexpanded) for the CSIDL with index folder:
1809  * If SHGFP_TYPE_DEFAULT is set, calls _SHGetDefaultValue for it.  Otherwise
1810  * calls _SHGetUserShellFolderPath for it.  Where it looks depends on hToken:
1811  * - if hToken is -1, looks in HKEY_USERS\.Default
1812  * - otherwise looks first in HKEY_CURRENT_USER, followed by HKEY_LOCAL_MACHINE
1813  *   if HKEY_CURRENT_USER doesn't contain any entries.  If both fail, finally
1814  *   calls _SHGetDefaultValue for it.
1815  */
1816 static HRESULT _SHGetUserProfilePath(HANDLE hToken, DWORD dwFlags, BYTE folder,
1817  LPWSTR pszPath)
1818 {
1819     HRESULT hr;
1820
1821     TRACE("%p,0x%08x,0x%02x,%p\n", hToken, dwFlags, folder, pszPath);
1822
1823     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1824         return E_INVALIDARG;
1825     if (CSIDL_Data[folder].type != CSIDL_Type_User)
1826         return E_INVALIDARG;
1827     if (!pszPath)
1828         return E_INVALIDARG;
1829
1830     if (dwFlags & SHGFP_TYPE_DEFAULT)
1831     {
1832         if (hToken != NULL && hToken != (HANDLE)-1)
1833         {
1834             FIXME("unsupported for user other than current or default\n");
1835             return E_FAIL;
1836         }
1837         hr = _SHGetDefaultValue(folder, pszPath);
1838     }
1839     else
1840     {
1841         LPCWSTR userPrefix = NULL;
1842         HKEY hRootKey;
1843
1844         if (hToken == (HANDLE)-1)
1845         {
1846             hRootKey = HKEY_USERS;
1847             userPrefix = DefaultW;
1848         }
1849         else if (hToken == NULL)
1850             hRootKey = HKEY_CURRENT_USER;
1851         else
1852         {
1853             hRootKey = HKEY_USERS;
1854             userPrefix = _GetUserSidStringFromToken(hToken);
1855             if (userPrefix == NULL)
1856             {
1857                 hr = E_FAIL;
1858                 goto error;
1859             }
1860         }
1861         hr = _SHGetUserShellFolderPath(hRootKey, userPrefix,
1862          CSIDL_Data[folder].szValueName, pszPath);
1863         if (FAILED(hr) && hRootKey != HKEY_LOCAL_MACHINE)
1864             hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1865              CSIDL_Data[folder].szValueName, pszPath);
1866         if (FAILED(hr))
1867             hr = _SHGetDefaultValue(folder, pszPath);
1868         if (userPrefix != NULL && userPrefix != DefaultW)
1869             LocalFree((HLOCAL) userPrefix);
1870     }
1871 error:
1872     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1873     return hr;
1874 }
1875
1876 /* Gets the (unexpanded) path for the CSIDL with index folder.  If dwFlags has
1877  * SHGFP_TYPE_DEFAULT set, calls _SHGetDefaultValue.  Otherwise calls
1878  * _SHGetUserShellFolderPath for it, looking only in HKEY_LOCAL_MACHINE.
1879  * If this fails, falls back to _SHGetDefaultValue.
1880  */
1881 static HRESULT _SHGetAllUsersProfilePath(DWORD dwFlags, BYTE folder,
1882  LPWSTR pszPath)
1883 {
1884     HRESULT hr;
1885
1886     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1887
1888     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1889         return E_INVALIDARG;
1890     if (CSIDL_Data[folder].type != CSIDL_Type_AllUsers)
1891         return E_INVALIDARG;
1892     if (!pszPath)
1893         return E_INVALIDARG;
1894
1895     if (dwFlags & SHGFP_TYPE_DEFAULT)
1896         hr = _SHGetDefaultValue(folder, pszPath);
1897     else
1898     {
1899         hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1900          CSIDL_Data[folder].szValueName, pszPath);
1901         if (FAILED(hr))
1902             hr = _SHGetDefaultValue(folder, pszPath);
1903     }
1904     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1905     return hr;
1906 }
1907
1908 static HRESULT _SHOpenProfilesKey(PHKEY pKey)
1909 {
1910     LONG lRet;
1911     DWORD disp;
1912
1913     lRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ProfileListW, 0, NULL, 0,
1914      KEY_ALL_ACCESS, NULL, pKey, &disp);
1915     return HRESULT_FROM_WIN32(lRet);
1916 }
1917
1918 /* Reads the value named szValueName from the key profilesKey (assumed to be
1919  * opened by _SHOpenProfilesKey) into szValue, which is assumed to be MAX_PATH
1920  * WCHARs in length.  If it doesn't exist, returns szDefault (and saves
1921  * szDefault to the registry).
1922  */
1923 static HRESULT _SHGetProfilesValue(HKEY profilesKey, LPCWSTR szValueName,
1924  LPWSTR szValue, LPCWSTR szDefault)
1925 {
1926     HRESULT hr;
1927     DWORD type, dwPathLen = MAX_PATH * sizeof(WCHAR);
1928     LONG lRet;
1929
1930     TRACE("%p,%s,%p,%s\n", profilesKey, debugstr_w(szValueName), szValue,
1931      debugstr_w(szDefault));
1932     lRet = RegQueryValueExW(profilesKey, szValueName, NULL, &type,
1933      (LPBYTE)szValue, &dwPathLen);
1934     if (!lRet && (type == REG_SZ || type == REG_EXPAND_SZ) && dwPathLen
1935      && *szValue)
1936     {
1937         dwPathLen /= sizeof(WCHAR);
1938         szValue[dwPathLen] = '\0';
1939         hr = S_OK;
1940     }
1941     else
1942     {
1943         /* Missing or invalid value, set a default */
1944         lstrcpynW(szValue, szDefault, MAX_PATH);
1945         TRACE("Setting missing value %s to %s\n", debugstr_w(szValueName),
1946                                                   debugstr_w(szValue));
1947         lRet = RegSetValueExW(profilesKey, szValueName, 0, REG_EXPAND_SZ,
1948                               (LPBYTE)szValue,
1949                               (strlenW(szValue) + 1) * sizeof(WCHAR));
1950         if (lRet)
1951             hr = HRESULT_FROM_WIN32(lRet);
1952         else
1953             hr = S_OK;
1954     }
1955     TRACE("returning 0x%08x (output value is %s)\n", hr, debugstr_w(szValue));
1956     return hr;
1957 }
1958
1959 /* Attempts to expand environment variables from szSrc into szDest, which is
1960  * assumed to be MAX_PATH characters in length.  Before referring to the
1961  * environment, handles a few variables directly, because the environment
1962  * variables may not be set when this is called (as during Wine's installation
1963  * when default values are being written to the registry).
1964  * The directly handled environment variables, and their source, are:
1965  * - ALLUSERSPROFILE, USERPROFILE: reads from the registry
1966  * - SystemDrive: uses GetSystemDirectoryW and uses the drive portion of its
1967  *   path
1968  * If one of the directly handled environment variables is expanded, only
1969  * expands a single variable, and only in the beginning of szSrc.
1970  */
1971 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest)
1972 {
1973     HRESULT hr;
1974     WCHAR szTemp[MAX_PATH], szProfilesPrefix[MAX_PATH] = { 0 };
1975     HKEY key = NULL;
1976
1977     TRACE("%s, %p\n", debugstr_w(szSrc), szDest);
1978
1979     if (!szSrc || !szDest) return E_INVALIDARG;
1980
1981     /* short-circuit if there's nothing to expand */
1982     if (szSrc[0] != '%')
1983     {
1984         strcpyW(szDest, szSrc);
1985         hr = S_OK;
1986         goto end;
1987     }
1988     /* Get the profile prefix, we'll probably be needing it */
1989     hr = _SHOpenProfilesKey(&key);
1990     if (SUCCEEDED(hr))
1991     {
1992         WCHAR def_val[MAX_PATH];
1993
1994         /* get the system drive */
1995         GetSystemDirectoryW(def_val, MAX_PATH);
1996         if (def_val[1] == ':') strcpyW( def_val + 3, szDefaultProfileDirW );
1997         else FIXME("non-drive system paths unsupported\n");
1998
1999         hr = _SHGetProfilesValue(key, ProfilesDirectoryW, szProfilesPrefix, def_val );
2000     }
2001
2002     *szDest = 0;
2003     strcpyW(szTemp, szSrc);
2004     while (SUCCEEDED(hr) && szTemp[0] == '%')
2005     {
2006         if (!strncmpiW(szTemp, AllUsersProfileW, strlenW(AllUsersProfileW)))
2007         {
2008             WCHAR szAllUsers[MAX_PATH];
2009
2010             strcpyW(szDest, szProfilesPrefix);
2011             hr = _SHGetProfilesValue(key, AllUsersProfileValueW,
2012              szAllUsers, AllUsersW);
2013             PathAppendW(szDest, szAllUsers);
2014             PathAppendW(szDest, szTemp + strlenW(AllUsersProfileW));
2015         }
2016         else if (!strncmpiW(szTemp, UserProfileW, strlenW(UserProfileW)))
2017         {
2018             WCHAR userName[MAX_PATH];
2019             DWORD userLen = MAX_PATH;
2020
2021             strcpyW(szDest, szProfilesPrefix);
2022             GetUserNameW(userName, &userLen);
2023             PathAppendW(szDest, userName);
2024             PathAppendW(szDest, szTemp + strlenW(UserProfileW));
2025         }
2026         else if (!strncmpiW(szTemp, SystemDriveW, strlenW(SystemDriveW)))
2027         {
2028             GetSystemDirectoryW(szDest, MAX_PATH);
2029             if (szDest[1] != ':')
2030             {
2031                 FIXME("non-drive system paths unsupported\n");
2032                 hr = E_FAIL;
2033             }
2034             else
2035             {
2036                 strcpyW(szDest + 3, szTemp + strlenW(SystemDriveW) + 1);
2037                 hr = S_OK;
2038             }
2039         }
2040         else
2041         {
2042             DWORD ret = ExpandEnvironmentStringsW(szSrc, szDest, MAX_PATH);
2043
2044             if (ret > MAX_PATH)
2045                 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
2046             else if (ret == 0)
2047                 hr = HRESULT_FROM_WIN32(GetLastError());
2048             else
2049                 hr = S_OK;
2050         }
2051         if (SUCCEEDED(hr) && szDest[0] == '%')
2052             strcpyW(szTemp, szDest);
2053         else
2054         {
2055             /* terminate loop */
2056             szTemp[0] = '\0';
2057         }
2058     }
2059 end:
2060     if (key)
2061         RegCloseKey(key);
2062     TRACE("returning 0x%08x (input was %s, output is %s)\n", hr,
2063      debugstr_w(szSrc), debugstr_w(szDest));
2064     return hr;
2065 }
2066
2067 /*************************************************************************
2068  * SHGetFolderPathW                     [SHELL32.@]
2069  *
2070  * Convert nFolder to path.  
2071  *
2072  * RETURNS
2073  *  Success: S_OK
2074  *  Failure: standard HRESULT error codes.
2075  *
2076  * NOTES
2077  * Most values can be overridden in either
2078  * HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
2079  * or in the same location in HKLM.
2080  * The "Shell Folders" registry key was used in NT4 and earlier systems.
2081  * Beginning with Windows 2000, the "User Shell Folders" key is used, so
2082  * changes made to it are made to the former key too.  This synchronization is
2083  * done on-demand: not until someone requests the value of one of these paths
2084  * (by calling one of the SHGet functions) is the value synchronized.
2085  * Furthermore, the HKCU paths take precedence over the HKLM paths.
2086  */
2087 HRESULT WINAPI SHGetFolderPathW(
2088         HWND hwndOwner,    /* [I] owner window */
2089         int nFolder,       /* [I] CSIDL identifying the folder */
2090         HANDLE hToken,     /* [I] access token */
2091         DWORD dwFlags,     /* [I] which path to return */
2092         LPWSTR pszPath)    /* [O] converted path */
2093 {
2094     HRESULT hr =  SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, NULL, pszPath);
2095     if(HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
2096         hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
2097     return hr;
2098 }
2099
2100 HRESULT WINAPI SHGetFolderPathAndSubDirA(
2101         HWND hwndOwner,    /* [I] owner window */
2102         int nFolder,       /* [I] CSIDL identifying the folder */
2103         HANDLE hToken,     /* [I] access token */
2104         DWORD dwFlags,     /* [I] which path to return */
2105         LPCSTR pszSubPath, /* [I] sub directory of the specified folder */
2106         LPSTR pszPath)     /* [O] converted path */
2107 {
2108     int length;
2109     HRESULT hr = S_OK;
2110     LPWSTR pszSubPathW = NULL;
2111     LPWSTR pszPathW = NULL;
2112     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2113
2114     if(pszPath) {
2115         pszPathW = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
2116         if(!pszPathW) {
2117             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2118             goto cleanup;
2119         }
2120     }
2121     TRACE("%08x,%08x,%s\n",nFolder, dwFlags, debugstr_w(pszSubPathW));
2122
2123     /* SHGetFolderPathAndSubDirW does not distinguish if pszSubPath isn't
2124      * set (null), or an empty string.therefore call it without the parameter set
2125      * if pszSubPath is an empty string
2126      */
2127     if (pszSubPath && pszSubPath[0]) {
2128         length = MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, NULL, 0);
2129         pszSubPathW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR));
2130         if(!pszSubPathW) {
2131             hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
2132             goto cleanup;
2133         }
2134         MultiByteToWideChar(CP_ACP, 0, pszSubPath, -1, pszSubPathW, length);
2135     }
2136
2137     hr = SHGetFolderPathAndSubDirW(hwndOwner, nFolder, hToken, dwFlags, pszSubPathW, pszPathW);
2138
2139     if (SUCCEEDED(hr) && pszPath)
2140         WideCharToMultiByte(CP_ACP, 0, pszPathW, -1, pszPath, MAX_PATH, NULL, NULL);
2141
2142 cleanup:
2143     HeapFree(GetProcessHeap(), 0, pszPathW);
2144     HeapFree(GetProcessHeap(), 0, pszSubPathW);
2145     return hr;
2146 }
2147
2148 /*************************************************************************
2149  * SHGetFolderPathAndSubDirW            [SHELL32.@]
2150  */
2151 HRESULT WINAPI SHGetFolderPathAndSubDirW(
2152         HWND hwndOwner,    /* [I] owner window */
2153         int nFolder,       /* [I] CSIDL identifying the folder */
2154         HANDLE hToken,     /* [I] access token */
2155         DWORD dwFlags,     /* [I] which path to return */
2156         LPCWSTR pszSubPath,/* [I] sub directory of the specified folder */
2157         LPWSTR pszPath)    /* [O] converted path */
2158 {
2159     HRESULT    hr;
2160     WCHAR      szBuildPath[MAX_PATH], szTemp[MAX_PATH];
2161     DWORD      folder = nFolder & CSIDL_FOLDER_MASK;
2162     CSIDL_Type type;
2163     int        ret;
2164     
2165     TRACE("%p,%p,nFolder=0x%04x,%s\n", hwndOwner,pszPath,nFolder,debugstr_w(pszSubPath));
2166
2167     /* Windows always NULL-terminates the resulting path regardless of success
2168      * or failure, so do so first
2169      */
2170     if (pszPath)
2171         *pszPath = '\0';
2172
2173     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
2174         return E_INVALIDARG;
2175     if ((SHGFP_TYPE_CURRENT != dwFlags) && (SHGFP_TYPE_DEFAULT != dwFlags))
2176         return E_INVALIDARG;
2177     szTemp[0] = 0;
2178     type = CSIDL_Data[folder].type;
2179     switch (type)
2180     {
2181         case CSIDL_Type_Disallowed:
2182             hr = E_INVALIDARG;
2183             break;
2184         case CSIDL_Type_NonExistent:
2185             hr = S_FALSE;
2186             break;
2187         case CSIDL_Type_WindowsPath:
2188             GetWindowsDirectoryW(szTemp, MAX_PATH);
2189             if (CSIDL_Data[folder].szDefaultPath &&
2190              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2191              *CSIDL_Data[folder].szDefaultPath)
2192             {
2193                 PathAddBackslashW(szTemp);
2194                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2195             }
2196             hr = S_OK;
2197             break;
2198         case CSIDL_Type_SystemPath:
2199             GetSystemDirectoryW(szTemp, MAX_PATH);
2200             if (CSIDL_Data[folder].szDefaultPath &&
2201              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2202              *CSIDL_Data[folder].szDefaultPath)
2203             {
2204                 PathAddBackslashW(szTemp);
2205                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2206             }
2207             hr = S_OK;
2208             break;
2209         case CSIDL_Type_SystemX86Path:
2210             if (!GetSystemWow64DirectoryW(szTemp, MAX_PATH)) GetSystemDirectoryW(szTemp, MAX_PATH);
2211             if (CSIDL_Data[folder].szDefaultPath &&
2212              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
2213              *CSIDL_Data[folder].szDefaultPath)
2214             {
2215                 PathAddBackslashW(szTemp);
2216                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
2217             }
2218             hr = S_OK;
2219             break;
2220         case CSIDL_Type_CurrVer:
2221             hr = _SHGetCurrentVersionPath(dwFlags, folder, szTemp);
2222             break;
2223         case CSIDL_Type_User:
2224             hr = _SHGetUserProfilePath(hToken, dwFlags, folder, szTemp);
2225             break;
2226         case CSIDL_Type_AllUsers:
2227             hr = _SHGetAllUsersProfilePath(dwFlags, folder, szTemp);
2228             break;
2229         default:
2230             FIXME("bogus type %d, please fix\n", type);
2231             hr = E_INVALIDARG;
2232             break;
2233     }
2234
2235     /* Expand environment strings if necessary */
2236     if (*szTemp == '%')
2237         hr = _SHExpandEnvironmentStrings(szTemp, szBuildPath);
2238     else
2239         strcpyW(szBuildPath, szTemp);
2240
2241     if (FAILED(hr)) goto end;
2242
2243     if(pszSubPath) {
2244         /* make sure the new path does not exceed th bufferlength
2245          * rememebr to backslash and the termination */
2246         if(MAX_PATH < (lstrlenW(szBuildPath) + lstrlenW(pszSubPath) + 2)) {
2247             hr = HRESULT_FROM_WIN32(ERROR_FILENAME_EXCED_RANGE);
2248             goto end;
2249         }
2250         PathAppendW(szBuildPath, pszSubPath);
2251         PathRemoveBackslashW(szBuildPath);
2252     }
2253     /* Copy the path if it's available before we might return */
2254     if (SUCCEEDED(hr) && pszPath)
2255         strcpyW(pszPath, szBuildPath);
2256
2257     /* if we don't care about existing directories we are ready */
2258     if(nFolder & CSIDL_FLAG_DONT_VERIFY) goto end;
2259
2260     if (PathFileExistsW(szBuildPath)) goto end;
2261
2262     /* not existing but we are not allowed to create it.  The return value
2263      * is verified against shell32 version 6.0.
2264      */
2265     if (!(nFolder & CSIDL_FLAG_CREATE))
2266     {
2267         hr = HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND);
2268         goto end;
2269     }
2270
2271     /* create directory/directories */
2272     ret = SHCreateDirectoryExW(hwndOwner, szBuildPath, NULL);
2273     if (ret && ret != ERROR_ALREADY_EXISTS)
2274     {
2275         ERR("Failed to create directory %s.\n", debugstr_w(szBuildPath));
2276         hr = E_FAIL;
2277         goto end;
2278     }
2279
2280     TRACE("Created missing system directory %s\n", debugstr_w(szBuildPath));
2281 end:
2282     TRACE("returning 0x%08x (final path is %s)\n", hr, debugstr_w(szBuildPath));
2283     return hr;
2284 }
2285
2286 /*************************************************************************
2287  * SHGetFolderPathA                     [SHELL32.@]
2288  *
2289  * See SHGetFolderPathW.
2290  */
2291 HRESULT WINAPI SHGetFolderPathA(
2292         HWND hwndOwner,
2293         int nFolder,
2294         HANDLE hToken,
2295         DWORD dwFlags,
2296         LPSTR pszPath)
2297 {
2298     WCHAR szTemp[MAX_PATH];
2299     HRESULT hr;
2300
2301     TRACE("%p,%p,nFolder=0x%04x\n",hwndOwner,pszPath,nFolder);
2302
2303     if (pszPath)
2304         *pszPath = '\0';
2305     hr = SHGetFolderPathW(hwndOwner, nFolder, hToken, dwFlags, szTemp);
2306     if (SUCCEEDED(hr) && pszPath)
2307         WideCharToMultiByte(CP_ACP, 0, szTemp, -1, pszPath, MAX_PATH, NULL,
2308          NULL);
2309
2310     return hr;
2311 }
2312
2313 /* For each folder in folders, if its value has not been set in the registry,
2314  * calls _SHGetUserProfilePath or _SHGetAllUsersProfilePath (depending on the
2315  * folder's type) to get the unexpanded value first.
2316  * Writes the unexpanded value to User Shell Folders, and queries it with
2317  * SHGetFolderPathW to force the creation of the directory if it doesn't
2318  * already exist.  SHGetFolderPathW also returns the expanded value, which
2319  * this then writes to Shell Folders.
2320  */
2321 static HRESULT _SHRegisterFolders(HKEY hRootKey, HANDLE hToken,
2322  LPCWSTR szUserShellFolderPath, LPCWSTR szShellFolderPath, const UINT folders[],
2323  UINT foldersLen)
2324 {
2325     UINT i;
2326     WCHAR path[MAX_PATH];
2327     HRESULT hr = S_OK;
2328     HKEY hUserKey = NULL, hKey = NULL;
2329     DWORD dwType, dwPathLen;
2330     LONG ret;
2331
2332     TRACE("%p,%p,%s,%p,%u\n", hRootKey, hToken,
2333      debugstr_w(szUserShellFolderPath), folders, foldersLen);
2334
2335     ret = RegCreateKeyW(hRootKey, szUserShellFolderPath, &hUserKey);
2336     if (ret)
2337         hr = HRESULT_FROM_WIN32(ret);
2338     else
2339     {
2340         ret = RegCreateKeyW(hRootKey, szShellFolderPath, &hKey);
2341         if (ret)
2342             hr = HRESULT_FROM_WIN32(ret);
2343     }
2344     for (i = 0; SUCCEEDED(hr) && i < foldersLen; i++)
2345     {
2346         dwPathLen = MAX_PATH * sizeof(WCHAR);
2347         if (RegQueryValueExW(hUserKey, CSIDL_Data[folders[i]].szValueName, NULL,
2348          &dwType, (LPBYTE)path, &dwPathLen) || (dwType != REG_SZ &&
2349          dwType != REG_EXPAND_SZ))
2350         {
2351             *path = '\0';
2352             if (CSIDL_Data[folders[i]].type == CSIDL_Type_User)
2353                 _SHGetUserProfilePath(hToken, SHGFP_TYPE_DEFAULT, folders[i],
2354                  path);
2355             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_AllUsers)
2356                 _SHGetAllUsersProfilePath(SHGFP_TYPE_DEFAULT, folders[i], path);
2357             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_WindowsPath)
2358             {
2359                 GetWindowsDirectoryW(path, MAX_PATH);
2360                 if (CSIDL_Data[folders[i]].szDefaultPath &&
2361                     !IS_INTRESOURCE(CSIDL_Data[folders[i]].szDefaultPath))
2362                 {
2363                     PathAddBackslashW(path);
2364                     strcatW(path, CSIDL_Data[folders[i]].szDefaultPath);
2365                 }
2366             }
2367             else
2368                 hr = E_FAIL;
2369             if (*path)
2370             {
2371                 ret = RegSetValueExW(hUserKey,
2372                  CSIDL_Data[folders[i]].szValueName, 0, REG_EXPAND_SZ,
2373                  (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2374                 if (ret)
2375                     hr = HRESULT_FROM_WIN32(ret);
2376                 else
2377                 {
2378                     hr = SHGetFolderPathW(NULL, folders[i] | CSIDL_FLAG_CREATE,
2379                      hToken, SHGFP_TYPE_DEFAULT, path);
2380                     ret = RegSetValueExW(hKey,
2381                      CSIDL_Data[folders[i]].szValueName, 0, REG_SZ,
2382                      (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
2383                     if (ret)
2384                         hr = HRESULT_FROM_WIN32(ret);
2385                 }
2386             }
2387         }
2388     }
2389     if (hUserKey)
2390         RegCloseKey(hUserKey);
2391     if (hKey)
2392         RegCloseKey(hKey);
2393
2394     TRACE("returning 0x%08x\n", hr);
2395     return hr;
2396 }
2397
2398 static HRESULT _SHRegisterUserShellFolders(BOOL bDefault)
2399 {
2400     static const UINT folders[] = {
2401      CSIDL_PROGRAMS,
2402      CSIDL_PERSONAL,
2403      CSIDL_FAVORITES,
2404      CSIDL_APPDATA,
2405      CSIDL_STARTUP,
2406      CSIDL_RECENT,
2407      CSIDL_SENDTO,
2408      CSIDL_STARTMENU,
2409      CSIDL_MYMUSIC,
2410      CSIDL_MYVIDEO,
2411      CSIDL_DESKTOPDIRECTORY,
2412      CSIDL_NETHOOD,
2413      CSIDL_TEMPLATES,
2414      CSIDL_PRINTHOOD,
2415      CSIDL_LOCAL_APPDATA,
2416      CSIDL_INTERNET_CACHE,
2417      CSIDL_COOKIES,
2418      CSIDL_HISTORY,
2419      CSIDL_MYPICTURES,
2420      CSIDL_FONTS
2421     };
2422     WCHAR userShellFolderPath[MAX_PATH], shellFolderPath[MAX_PATH];
2423     LPCWSTR pUserShellFolderPath, pShellFolderPath;
2424     HRESULT hr = S_OK;
2425     HKEY hRootKey;
2426     HANDLE hToken;
2427
2428     TRACE("%s\n", bDefault ? "TRUE" : "FALSE");
2429     if (bDefault)
2430     {
2431         hToken = (HANDLE)-1;
2432         hRootKey = HKEY_USERS;
2433         strcpyW(userShellFolderPath, DefaultW);
2434         PathAddBackslashW(userShellFolderPath);
2435         strcatW(userShellFolderPath, szSHUserFolders);
2436         pUserShellFolderPath = userShellFolderPath;
2437         strcpyW(shellFolderPath, DefaultW);
2438         PathAddBackslashW(shellFolderPath);
2439         strcatW(shellFolderPath, szSHFolders);
2440         pShellFolderPath = shellFolderPath;
2441     }
2442     else
2443     {
2444         hToken = NULL;
2445         hRootKey = HKEY_CURRENT_USER;
2446         pUserShellFolderPath = szSHUserFolders;
2447         pShellFolderPath = szSHFolders;
2448     }
2449
2450     hr = _SHRegisterFolders(hRootKey, hToken, pUserShellFolderPath,
2451      pShellFolderPath, folders, sizeof(folders) / sizeof(folders[0]));
2452     TRACE("returning 0x%08x\n", hr);
2453     return hr;
2454 }
2455
2456 static HRESULT _SHRegisterCommonShellFolders(void)
2457 {
2458     static const UINT folders[] = {
2459      CSIDL_COMMON_STARTMENU,
2460      CSIDL_COMMON_PROGRAMS,
2461      CSIDL_COMMON_STARTUP,
2462      CSIDL_COMMON_DESKTOPDIRECTORY,
2463      CSIDL_COMMON_FAVORITES,
2464      CSIDL_COMMON_APPDATA,
2465      CSIDL_COMMON_TEMPLATES,
2466      CSIDL_COMMON_DOCUMENTS,
2467      CSIDL_COMMON_ADMINTOOLS,
2468      CSIDL_COMMON_MUSIC,
2469      CSIDL_COMMON_PICTURES,
2470      CSIDL_COMMON_VIDEO,
2471     };
2472     HRESULT hr;
2473
2474     TRACE("\n");
2475     hr = _SHRegisterFolders(HKEY_LOCAL_MACHINE, NULL, szSHUserFolders,
2476      szSHFolders, folders, sizeof(folders) / sizeof(folders[0]));
2477     TRACE("returning 0x%08x\n", hr);
2478     return hr;
2479 }
2480
2481 /******************************************************************************
2482  * _SHAppendToUnixPath  [Internal]
2483  *
2484  * Helper function for _SHCreateSymbolicLinks. Appends pwszSubPath (or the 
2485  * corresponding resource, if IS_INTRESOURCE) to the unix base path 'szBasePath' 
2486  * and replaces backslashes with slashes.
2487  *
2488  * PARAMS
2489  *  szBasePath  [IO] The unix base path, which will be appended to (CP_UNXICP).
2490  *  pwszSubPath [I]  Sub-path or resource id (use MAKEINTRESOURCEW).
2491  *
2492  * RETURNS
2493  *  Success: TRUE,
2494  *  Failure: FALSE
2495  */
2496 static inline BOOL _SHAppendToUnixPath(char *szBasePath, LPCWSTR pwszSubPath) {
2497     WCHAR wszSubPath[MAX_PATH];
2498     int cLen = strlen(szBasePath);
2499     char *pBackslash;
2500
2501     if (IS_INTRESOURCE(pwszSubPath)) {
2502         if (!LoadStringW(shell32_hInstance, LOWORD(pwszSubPath), wszSubPath, MAX_PATH)) {
2503             /* Fall back to hard coded defaults. */
2504             switch (LOWORD(pwszSubPath)) {
2505                 case IDS_PERSONAL:
2506                     lstrcpyW(wszSubPath, PersonalW);
2507                     break;
2508                 case IDS_MYMUSIC:
2509                     lstrcpyW(wszSubPath, My_MusicW);
2510                     break;
2511                 case IDS_MYPICTURES:
2512                     lstrcpyW(wszSubPath, My_PicturesW);
2513                     break;
2514                 case IDS_MYVIDEO:
2515                     lstrcpyW(wszSubPath, My_VideoW);
2516                     break;
2517                 default:
2518                     ERR("LoadString(%d) failed!\n", LOWORD(pwszSubPath));
2519                     return FALSE;
2520             }
2521         }
2522     } else {
2523         lstrcpyW(wszSubPath, pwszSubPath);
2524     }
2525  
2526     if (szBasePath[cLen-1] != '/') szBasePath[cLen++] = '/';
2527  
2528     if (!WideCharToMultiByte(CP_UNIXCP, 0, wszSubPath, -1, szBasePath + cLen,
2529                              FILENAME_MAX - cLen, NULL, NULL))
2530     {
2531         return FALSE;
2532     }
2533  
2534     pBackslash = szBasePath + cLen;
2535     while ((pBackslash = strchr(pBackslash, '\\'))) *pBackslash = '/';
2536  
2537     return TRUE;
2538 }
2539
2540 /******************************************************************************
2541  * _SHCreateSymbolicLinks  [Internal]
2542  * 
2543  * Sets up symbol links for various shell folders to point into the users home
2544  * directory. We do an educated guess about what the user would probably want:
2545  * - If there is a 'My Documents' directory in $HOME, the user probably wants
2546  *   wine's 'My Documents' to point there. Furthermore, we imply that the user
2547  *   is a Windows lover and has no problem with wine creating 'My Pictures',
2548  *   'My Music' and 'My Video' subfolders under '$HOME/My Documents', if those
2549  *   do not already exits. We put appropriate symbolic links in place for those,
2550  *   too.
2551  * - If there is no 'My Documents' directory in $HOME, we let 'My Documents'
2552  *   point directly to $HOME. We assume the user to be a unix hacker who does not
2553  *   want wine to create anything anywhere besides the .wine directory. So, if
2554  *   there already is a 'My Music' directory in $HOME, we symlink the 'My Music'
2555  *   shell folder to it. But if not, then we check XDG_MUSIC_DIR - "well known"
2556  *   directory, and try to link to that. If that fails, then we symlink to
2557  *   $HOME directly. The same holds fo 'My Pictures' and 'My Video'.
2558  * - The Desktop shell folder is symlinked to XDG_DESKTOP_DIR. If that does not
2559  *   exist, then we try '$HOME/Desktop'. If that does not exist, then we leave
2560  *   it alone.
2561  * ('My Music',... above in fact means LoadString(IDS_MYMUSIC))
2562  */
2563 static void _SHCreateSymbolicLinks(void)
2564 {
2565     UINT aidsMyStuff[] = { IDS_MYPICTURES, IDS_MYVIDEO, IDS_MYMUSIC }, i;
2566     int acsidlMyStuff[] = { CSIDL_MYPICTURES, CSIDL_MYVIDEO, CSIDL_MYMUSIC };
2567     static const char * const xdg_dirs[] = { "PICTURES", "VIDEOS", "MUSIC", "DESKTOP" };
2568     static const unsigned int num = sizeof(xdg_dirs) / sizeof(xdg_dirs[0]);
2569     WCHAR wszTempPath[MAX_PATH];
2570     char szPersonalTarget[FILENAME_MAX], *pszPersonal;
2571     char szMyStuffTarget[FILENAME_MAX], *pszMyStuff;
2572     char szDesktopTarget[FILENAME_MAX], *pszDesktop;
2573     struct stat statFolder;
2574     const char *pszHome;
2575     HRESULT hr;
2576     char ** xdg_results;
2577     char * xdg_desktop_dir;
2578
2579     /* Create all necessary profile sub-dirs up to 'My Documents' and get the unix path. */
2580     hr = SHGetFolderPathW(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL,
2581                           SHGFP_TYPE_DEFAULT, wszTempPath);
2582     if (FAILED(hr)) return;
2583     pszPersonal = wine_get_unix_file_name(wszTempPath);
2584     if (!pszPersonal) return;
2585
2586     hr = XDG_UserDirLookup(xdg_dirs, num, &xdg_results);
2587     if (FAILED(hr)) xdg_results = NULL;
2588
2589     pszHome = getenv("HOME");
2590     if (pszHome && !stat(pszHome, &statFolder) && S_ISDIR(statFolder.st_mode)) {
2591         strcpy(szPersonalTarget, pszHome);
2592         if (_SHAppendToUnixPath(szPersonalTarget, MAKEINTRESOURCEW(IDS_PERSONAL)) &&
2593             !stat(szPersonalTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2594         {
2595             /* '$HOME/My Documents' exists. Create 'My Pictures', 'My Videos' and 
2596              * 'My Music' subfolders or fail silently if they already exist. */
2597             for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2598                 strcpy(szMyStuffTarget, szPersonalTarget);
2599                 if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2600                     mkdir(szMyStuffTarget, 0777);
2601             }
2602         } 
2603         else
2604         {
2605             /* '$HOME/My Documents' doesn't exists, but '$HOME' does. */ 
2606             strcpy(szPersonalTarget, pszHome);
2607         }
2608
2609         /* Replace 'My Documents' directory with a symlink of fail silently if not empty. */
2610         rmdir(pszPersonal);
2611         symlink(szPersonalTarget, pszPersonal);
2612     }
2613     else
2614     {
2615         /* '$HOME' doesn't exist. Create 'My Pictures', 'My Videos' and 'My Music' subdirs
2616          * in '%USERPROFILE%\\My Documents' or fail silently if they already exist. */
2617         strcpy(szPersonalTarget, pszPersonal);
2618         for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2619             strcpy(szMyStuffTarget, szPersonalTarget);
2620             if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2621                 mkdir(szMyStuffTarget, 0777);
2622         }
2623     }
2624
2625     /* Create symbolic links for 'My Pictures', 'My Video' and 'My Music'. */
2626     for (i=0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2627         /* Create the current 'My Whatever' folder and get it's unix path. */
2628         hr = SHGetFolderPathW(NULL, acsidlMyStuff[i]|CSIDL_FLAG_CREATE, NULL,
2629                               SHGFP_TYPE_DEFAULT, wszTempPath);
2630         if (FAILED(hr)) continue;
2631         pszMyStuff = wine_get_unix_file_name(wszTempPath);
2632         if (!pszMyStuff) continue;
2633         
2634         strcpy(szMyStuffTarget, szPersonalTarget);
2635         if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])) &&
2636             !stat(szMyStuffTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2637         {
2638             /* If there's a 'My Whatever' directory where 'My Documents' links to, link to it. */
2639             rmdir(pszMyStuff);
2640             symlink(szMyStuffTarget, pszMyStuff);
2641         } 
2642         else
2643         {
2644             rmdir(pszMyStuff);
2645             if (xdg_results && xdg_results[i])
2646             {
2647                 /* the folder specified by XDG_XXX_DIR exists, link to it. */
2648                 symlink(xdg_results[i], pszMyStuff);
2649             }
2650             else
2651             {
2652                 /* Else link to where 'My Documents' itself links to. */
2653                 symlink(szPersonalTarget, pszMyStuff);
2654             }
2655         }
2656         HeapFree(GetProcessHeap(), 0, pszMyStuff);
2657     }
2658
2659     /* Last but not least, the Desktop folder */
2660     if (pszHome)
2661         strcpy(szDesktopTarget, pszHome);
2662     else
2663         strcpy(szDesktopTarget, pszPersonal);
2664     HeapFree(GetProcessHeap(), 0, pszPersonal);
2665
2666     xdg_desktop_dir = xdg_results ? xdg_results[num - 1] : NULL;
2667     if (xdg_desktop_dir ||
2668         (_SHAppendToUnixPath(szDesktopTarget, DesktopW) &&
2669         !stat(szDesktopTarget, &statFolder) && S_ISDIR(statFolder.st_mode)))
2670     {
2671         hr = SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, NULL,
2672                               SHGFP_TYPE_DEFAULT, wszTempPath);
2673         if (SUCCEEDED(hr) && (pszDesktop = wine_get_unix_file_name(wszTempPath))) 
2674         {
2675             rmdir(pszDesktop);
2676             if (xdg_desktop_dir)
2677                 symlink(xdg_desktop_dir, pszDesktop);
2678             else
2679                 symlink(szDesktopTarget, pszDesktop);
2680             HeapFree(GetProcessHeap(), 0, pszDesktop);
2681         }
2682     }
2683
2684     /* Free resources allocated by XDG_UserDirLookup() */
2685     if (xdg_results)
2686     {
2687         for (i = 0; i < num; i++)
2688             HeapFree(GetProcessHeap(), 0, xdg_results[i]);
2689         HeapFree(GetProcessHeap(), 0, xdg_results);
2690     }
2691 }
2692
2693 /******************************************************************************
2694  * create_extra_folders  [Internal]
2695  *
2696  * Create some extra folders that don't have a standard CSIDL definition.
2697  */
2698 static HRESULT create_extra_folders(void)
2699 {
2700     static const WCHAR environW[] = {'E','n','v','i','r','o','n','m','e','n','t',0};
2701     static const WCHAR TempW[]    = {'T','e','m','p',0};
2702     static const WCHAR TEMPW[]    = {'T','E','M','P',0};
2703     static const WCHAR TMPW[]     = {'T','M','P',0};
2704     WCHAR path[MAX_PATH+5];
2705     HRESULT hr;
2706     HKEY hkey;
2707     DWORD type, size, ret;
2708
2709     ret = RegCreateKeyW( HKEY_CURRENT_USER, environW, &hkey );
2710     if (ret) return HRESULT_FROM_WIN32( ret );
2711
2712     /* FIXME: should be under AppData, but we don't want spaces in the temp path */
2713     hr = SHGetFolderPathAndSubDirW( 0, CSIDL_PROFILE | CSIDL_FLAG_CREATE, NULL,
2714                                     SHGFP_TYPE_DEFAULT, TempW, path );
2715     if (SUCCEEDED(hr))
2716     {
2717         size = sizeof(path);
2718         if (RegQueryValueExW( hkey, TEMPW, NULL, &type, (LPBYTE)path, &size ))
2719             RegSetValueExW( hkey, TEMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2720         size = sizeof(path);
2721         if (RegQueryValueExW( hkey, TMPW, NULL, &type, (LPBYTE)path, &size ))
2722             RegSetValueExW( hkey, TMPW, 0, REG_SZ, (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR) );
2723     }
2724     RegCloseKey( hkey );
2725     return hr;
2726 }
2727
2728
2729 /* Register the default values in the registry, as some apps seem to depend
2730  * on their presence.  The set registered was taken from Windows XP.
2731  */
2732 HRESULT SHELL_RegisterShellFolders(void)
2733 {
2734     HRESULT hr;
2735
2736     /* Set up '$HOME' targeted symlinks for 'My Documents', 'My Pictures',
2737      * 'My Video', 'My Music' and 'Desktop' in advance, so that the
2738      * _SHRegister*ShellFolders() functions will find everything nice and clean
2739      * and thus will not attempt to create them in the profile directory. */
2740     _SHCreateSymbolicLinks();
2741     
2742     hr = _SHRegisterUserShellFolders(TRUE);
2743     if (SUCCEEDED(hr))
2744         hr = _SHRegisterUserShellFolders(FALSE);
2745     if (SUCCEEDED(hr))
2746         hr = _SHRegisterCommonShellFolders();
2747     if (SUCCEEDED(hr))
2748         hr = create_extra_folders();
2749     return hr;
2750 }
2751
2752 /*************************************************************************
2753  * SHGetSpecialFolderPathA [SHELL32.@]
2754  */
2755 BOOL WINAPI SHGetSpecialFolderPathA (
2756         HWND hwndOwner,
2757         LPSTR szPath,
2758         int nFolder,
2759         BOOL bCreate)
2760 {
2761         return (SHGetFolderPathA(
2762                 hwndOwner,
2763                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2764                 NULL,
2765                 0,
2766                 szPath)) == S_OK ? TRUE : FALSE;
2767 }
2768
2769 /*************************************************************************
2770  * SHGetSpecialFolderPathW
2771  */
2772 BOOL WINAPI SHGetSpecialFolderPathW (
2773         HWND hwndOwner,
2774         LPWSTR szPath,
2775         int nFolder,
2776         BOOL bCreate)
2777 {
2778         return (SHGetFolderPathW(
2779                 hwndOwner,
2780                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2781                 NULL,
2782                 0,
2783                 szPath)) == S_OK ? TRUE : FALSE;
2784 }
2785
2786 /*************************************************************************
2787  * SHGetSpecialFolderPath (SHELL32.175)
2788  */
2789 BOOL WINAPI SHGetSpecialFolderPathAW (
2790         HWND hwndOwner,
2791         LPVOID szPath,
2792         int nFolder,
2793         BOOL bCreate)
2794
2795 {
2796         if (SHELL_OsIsUnicode())
2797           return SHGetSpecialFolderPathW (hwndOwner, szPath, nFolder, bCreate);
2798         return SHGetSpecialFolderPathA (hwndOwner, szPath, nFolder, bCreate);
2799 }
2800
2801 /*************************************************************************
2802  * SHGetFolderLocation [SHELL32.@]
2803  *
2804  * Gets the folder locations from the registry and creates a pidl.
2805  *
2806  * PARAMS
2807  *   hwndOwner  [I]
2808  *   nFolder    [I] CSIDL_xxxxx
2809  *   hToken     [I] token representing user, or NULL for current user, or -1 for
2810  *                  default user
2811  *   dwReserved [I] must be zero
2812  *   ppidl      [O] PIDL of a special folder
2813  *
2814  * RETURNS
2815  *  Success: S_OK
2816  *  Failure: Standard OLE-defined error result, S_FALSE or E_INVALIDARG
2817  *
2818  * NOTES
2819  *  Creates missing reg keys and directories.
2820  *  Mostly forwards to SHGetFolderPathW, but a few values of nFolder return
2821  *  virtual folders that are handled here.
2822  */
2823 HRESULT WINAPI SHGetFolderLocation(
2824         HWND hwndOwner,
2825         int nFolder,
2826         HANDLE hToken,
2827         DWORD dwReserved,
2828         LPITEMIDLIST *ppidl)
2829 {
2830     HRESULT hr = E_INVALIDARG;
2831
2832     TRACE("%p 0x%08x %p 0x%08x %p\n",
2833      hwndOwner, nFolder, hToken, dwReserved, ppidl);
2834     
2835     if (!ppidl)
2836         return E_INVALIDARG;
2837     if (dwReserved)
2838         return E_INVALIDARG;
2839
2840     /* The virtual folders' locations are not user-dependent */
2841     *ppidl = NULL;
2842     switch (nFolder & CSIDL_FOLDER_MASK)
2843     {
2844         case CSIDL_DESKTOP:
2845             *ppidl = _ILCreateDesktop();
2846             break;
2847
2848         case CSIDL_PERSONAL:
2849             *ppidl = _ILCreateMyDocuments();
2850             break;
2851
2852         case CSIDL_INTERNET:
2853             *ppidl = _ILCreateIExplore();
2854             break;
2855
2856         case CSIDL_CONTROLS:
2857             *ppidl = _ILCreateControlPanel();
2858             break;
2859
2860         case CSIDL_PRINTERS:
2861             *ppidl = _ILCreatePrinters();
2862             break;
2863
2864         case CSIDL_BITBUCKET:
2865             *ppidl = _ILCreateBitBucket();
2866             break;
2867
2868         case CSIDL_DRIVES:
2869             *ppidl = _ILCreateMyComputer();
2870             break;
2871
2872         case CSIDL_NETWORK:
2873             *ppidl = _ILCreateNetwork();
2874             break;
2875
2876         default:
2877         {
2878             WCHAR szPath[MAX_PATH];
2879
2880             hr = SHGetFolderPathW(hwndOwner, nFolder, hToken,
2881              SHGFP_TYPE_CURRENT, szPath);
2882             if (SUCCEEDED(hr))
2883             {
2884                 DWORD attributes=0;
2885
2886                 TRACE("Value=%s\n", debugstr_w(szPath));
2887                 hr = SHILCreateFromPathW(szPath, ppidl, &attributes);
2888             }
2889             else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
2890             {
2891                 /* unlike SHGetFolderPath, SHGetFolderLocation in shell32
2892                  * version 6.0 returns E_FAIL for nonexistent paths
2893                  */
2894                 hr = E_FAIL;
2895             }
2896         }
2897     }
2898     if(*ppidl)
2899         hr = NOERROR;
2900
2901     TRACE("-- (new pidl %p)\n",*ppidl);
2902     return hr;
2903 }
2904
2905 /*************************************************************************
2906  * SHGetSpecialFolderLocation           [SHELL32.@]
2907  *
2908  * NOTES
2909  *   In NT5, SHGetSpecialFolderLocation needs the <winntdir>/Recent
2910  *   directory.
2911  */
2912 HRESULT WINAPI SHGetSpecialFolderLocation(
2913         HWND hwndOwner,
2914         INT nFolder,
2915         LPITEMIDLIST * ppidl)
2916 {
2917     HRESULT hr = E_INVALIDARG;
2918
2919     TRACE("(%p,0x%x,%p)\n", hwndOwner,nFolder,ppidl);
2920
2921     if (!ppidl)
2922         return E_INVALIDARG;
2923
2924     hr = SHGetFolderLocation(hwndOwner, nFolder, NULL, 0, ppidl);
2925     return hr;
2926 }
2927
2928 static int csidl_from_id( const KNOWNFOLDERID *id )
2929 {
2930     int i;
2931     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
2932         if (IsEqualGUID( CSIDL_Data[i].id, id )) return i;
2933     return -1;
2934 }
2935
2936 /*************************************************************************
2937  * SHGetKnownFolderPath           [SHELL32.@]
2938  */
2939 HRESULT WINAPI SHGetKnownFolderPath(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, PWSTR *path)
2940 {
2941     HRESULT hr;
2942     WCHAR folder[MAX_PATH];
2943     int index = csidl_from_id( rfid );
2944
2945     TRACE("%s, 0x%08x, %p, %p\n", debugstr_guid(rfid), flags, token, path);
2946
2947     if (index < 0)
2948         return E_INVALIDARG;
2949
2950     if (flags & KF_FLAG_CREATE)
2951         index |= CSIDL_FLAG_CREATE;
2952
2953     if (flags & KF_FLAG_DONT_VERIFY)
2954         index |= CSIDL_FLAG_DONT_VERIFY;
2955
2956     if (flags & KF_FLAG_NO_ALIAS)
2957         index |= CSIDL_FLAG_NO_ALIAS;
2958
2959     if (flags & KF_FLAG_INIT)
2960         index |= CSIDL_FLAG_PER_USER_INIT;
2961
2962     if (flags & ~(KF_FLAG_CREATE|KF_FLAG_DONT_VERIFY|KF_FLAG_NO_ALIAS|KF_FLAG_INIT))
2963     {
2964         FIXME("flags 0x%08x not supported\n", flags);
2965         return E_INVALIDARG;
2966     }
2967
2968     hr = SHGetFolderPathW( NULL, index, token, 0, folder );
2969     if (SUCCEEDED(hr))
2970     {
2971         *path = CoTaskMemAlloc( (strlenW( folder ) + 1) * sizeof(WCHAR) );
2972         if (!*path)
2973             return E_OUTOFMEMORY;
2974         strcpyW( *path, folder );
2975     }
2976     return hr;
2977 }
2978
2979 /*************************************************************************
2980  * SHGetFolderPathEx           [SHELL32.@]
2981  */
2982 HRESULT WINAPI SHGetFolderPathEx(REFKNOWNFOLDERID rfid, DWORD flags, HANDLE token, LPWSTR path, DWORD len)
2983 {
2984     HRESULT hr;
2985     WCHAR *buffer;
2986
2987     TRACE("%s, 0x%08x, %p, %p, %u\n", debugstr_guid(rfid), flags, token, path, len);
2988
2989     if (!path || !len) return E_INVALIDARG;
2990
2991     hr = SHGetKnownFolderPath( rfid, flags, token, &buffer );
2992     if (SUCCEEDED( hr ))
2993     {
2994         if (strlenW( buffer ) + 1 > len)
2995         {
2996             CoTaskMemFree( buffer );
2997             return HRESULT_FROM_WIN32( ERROR_INSUFFICIENT_BUFFER );
2998         }
2999         strcpyW( path, buffer );
3000         CoTaskMemFree( buffer );
3001     }
3002     return hr;
3003 }
3004
3005 struct knownfolder
3006 {
3007     const struct IKnownFolderVtbl *vtbl;
3008     LONG refs;
3009     KNOWNFOLDERID id;
3010 };
3011
3012 static inline struct knownfolder *impl_from_IKnownFolder( IKnownFolder *iface )
3013 {
3014     return (struct knownfolder *)((char *)iface - FIELD_OFFSET( struct knownfolder, vtbl ));
3015 }
3016
3017 static ULONG WINAPI knownfolder_AddRef(
3018     IKnownFolder *iface )
3019 {
3020     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3021     return InterlockedIncrement( &knownfolder->refs );
3022 }
3023
3024 static ULONG WINAPI knownfolder_Release(
3025     IKnownFolder *iface )
3026 {
3027     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3028     LONG refs = InterlockedDecrement( &knownfolder->refs );
3029     if (!refs)
3030     {
3031         TRACE("destroying %p\n", knownfolder);
3032         HeapFree( GetProcessHeap(), 0, knownfolder );
3033     }
3034     return refs;
3035 }
3036
3037 static HRESULT WINAPI knownfolder_QueryInterface(
3038     IKnownFolder *iface,
3039     REFIID riid,
3040     void **ppv )
3041 {
3042     struct knownfolder *This = impl_from_IKnownFolder( iface );
3043
3044     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3045
3046     if ( IsEqualGUID( riid, &IID_IKnownFolder ) ||
3047          IsEqualGUID( riid, &IID_IUnknown ) )
3048     {
3049         *ppv = iface;
3050     }
3051     else
3052     {
3053         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3054         return E_NOINTERFACE;
3055     }
3056     IKnownFolder_AddRef( iface );
3057     return S_OK;
3058 }
3059
3060 static HRESULT knowfolder_set_id(
3061     IKnownFolder *iface,
3062     const KNOWNFOLDERID *kfid)
3063 {
3064     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3065
3066     TRACE("%s\n", debugstr_guid(kfid));
3067
3068     knownfolder->id = *kfid;
3069     return S_OK;
3070 }
3071
3072 static HRESULT WINAPI knownfolder_GetId(
3073     IKnownFolder *iface,
3074     KNOWNFOLDERID *pkfid)
3075 {
3076     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3077
3078     TRACE("%p\n", pkfid);
3079
3080     *pkfid = knownfolder->id;
3081     return S_OK;
3082 }
3083
3084 static HRESULT WINAPI knownfolder_GetCategory(
3085     IKnownFolder *iface,
3086     KF_CATEGORY *pCategory)
3087 {
3088     FIXME("%p\n", pCategory);
3089     return E_NOTIMPL;
3090 }
3091
3092 static HRESULT WINAPI knownfolder_GetShellItem(
3093     IKnownFolder *iface,
3094     DWORD dwFlags,
3095     REFIID riid,
3096     void **ppv)
3097 {
3098     FIXME("0x%08x, %s, %p\n", dwFlags, debugstr_guid(riid), ppv);
3099     return E_NOTIMPL;
3100 }
3101
3102 static HRESULT WINAPI knownfolder_GetPath(
3103     IKnownFolder *iface,
3104     DWORD dwFlags,
3105     LPWSTR *ppszPath)
3106 {
3107     struct knownfolder *knownfolder = impl_from_IKnownFolder( iface );
3108
3109     TRACE("0x%08x, %p\n", dwFlags, ppszPath);
3110     return SHGetKnownFolderPath( &knownfolder->id, dwFlags, NULL, ppszPath );
3111 }
3112
3113 static HRESULT WINAPI knownfolder_SetPath(
3114     IKnownFolder *iface,
3115     DWORD dwFlags,
3116     LPCWSTR pszPath)
3117 {
3118     FIXME("0x%08x, %p\n", dwFlags, debugstr_w(pszPath));
3119     return E_NOTIMPL;
3120 }
3121
3122 static HRESULT WINAPI knownfolder_GetIDList(
3123     IKnownFolder *iface,
3124     DWORD dwFlags,
3125     PIDLIST_ABSOLUTE *ppidl)
3126 {
3127     FIXME("0x%08x, %p\n", dwFlags, ppidl);
3128     return E_NOTIMPL;
3129 }
3130
3131 static HRESULT WINAPI knownfolder_GetFolderType(
3132     IKnownFolder *iface,
3133     FOLDERTYPEID *pftid)
3134 {
3135     FIXME("%p\n", pftid);
3136     return E_NOTIMPL;
3137 }
3138
3139 static HRESULT WINAPI knownfolder_GetRedirectionCapabilities(
3140     IKnownFolder *iface,
3141     KF_REDIRECTION_CAPABILITIES *pCapabilities)
3142 {
3143     FIXME("%p\n", pCapabilities);
3144     return E_NOTIMPL;
3145 }
3146
3147 static HRESULT WINAPI knownfolder_GetFolderDefinition(
3148     IKnownFolder *iface,
3149     KNOWNFOLDER_DEFINITION *pKFD)
3150 {
3151     FIXME("%p\n", pKFD);
3152     return E_NOTIMPL;
3153 }
3154
3155 static const struct IKnownFolderVtbl knownfolder_vtbl =
3156 {
3157     knownfolder_QueryInterface,
3158     knownfolder_AddRef,
3159     knownfolder_Release,
3160     knownfolder_GetId,
3161     knownfolder_GetCategory,
3162     knownfolder_GetShellItem,
3163     knownfolder_GetPath,
3164     knownfolder_SetPath,
3165     knownfolder_GetIDList,
3166     knownfolder_GetFolderType,
3167     knownfolder_GetRedirectionCapabilities,
3168     knownfolder_GetFolderDefinition
3169 };
3170
3171 static HRESULT knownfolder_create( void **ppv )
3172 {
3173     struct knownfolder *kf;
3174
3175     kf = HeapAlloc( GetProcessHeap(), 0, sizeof(*kf) );
3176     if (!kf) return E_OUTOFMEMORY;
3177
3178     kf->vtbl = &knownfolder_vtbl;
3179     kf->refs = 1;
3180     memset( &kf->id, 0, sizeof(kf->id) );
3181
3182     *ppv = &kf->vtbl;
3183
3184     TRACE("returning iface %p\n", *ppv);
3185     return S_OK;
3186 }
3187
3188 struct foldermanager
3189 {
3190     const struct IKnownFolderManagerVtbl *vtbl;
3191     LONG refs;
3192     UINT num_ids;
3193     KNOWNFOLDERID *ids;
3194 };
3195
3196 static inline struct foldermanager *impl_from_IKnownFolderManager( IKnownFolderManager *iface )
3197 {
3198     return (struct foldermanager *)((char *)iface - FIELD_OFFSET( struct foldermanager, vtbl ));
3199 }
3200
3201 static ULONG WINAPI foldermanager_AddRef(
3202     IKnownFolderManager *iface )
3203 {
3204     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3205     return InterlockedIncrement( &foldermanager->refs );
3206 }
3207
3208 static ULONG WINAPI foldermanager_Release(
3209     IKnownFolderManager *iface )
3210 {
3211     struct foldermanager *foldermanager = impl_from_IKnownFolderManager( iface );
3212     LONG refs = InterlockedDecrement( &foldermanager->refs );
3213     if (!refs)
3214     {
3215         TRACE("destroying %p\n", foldermanager);
3216         HeapFree( GetProcessHeap(), 0, foldermanager->ids );
3217         HeapFree( GetProcessHeap(), 0, foldermanager );
3218     }
3219     return refs;
3220 }
3221
3222 static HRESULT WINAPI foldermanager_QueryInterface(
3223     IKnownFolderManager *iface,
3224     REFIID riid,
3225     void **ppv )
3226 {
3227     struct foldermanager *This = impl_from_IKnownFolderManager( iface );
3228
3229     TRACE("%p %s %p\n", This, debugstr_guid( riid ), ppv );
3230
3231     if ( IsEqualGUID( riid, &IID_IKnownFolderManager ) ||
3232          IsEqualGUID( riid, &IID_IUnknown ) )
3233     {
3234         *ppv = iface;
3235     }
3236     else
3237     {
3238         FIXME("interface %s not implemented\n", debugstr_guid(riid));
3239         return E_NOINTERFACE;
3240     }
3241     IKnownFolderManager_AddRef( iface );
3242     return S_OK;
3243 }
3244
3245 static HRESULT WINAPI foldermanager_FolderIdFromCsidl(
3246     IKnownFolderManager *iface,
3247     int nCsidl,
3248     KNOWNFOLDERID *pfid)
3249 {
3250     TRACE("%d, %p\n", nCsidl, pfid);
3251
3252     if (nCsidl >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
3253         return E_INVALIDARG;
3254     *pfid = *CSIDL_Data[nCsidl].id;
3255     return S_OK;
3256 }
3257
3258 static HRESULT WINAPI foldermanager_FolderIdToCsidl(
3259     IKnownFolderManager *iface,
3260     REFKNOWNFOLDERID rfid,
3261     int *pnCsidl)
3262 {
3263     int csidl;
3264
3265     TRACE("%s, %p\n", debugstr_guid(rfid), pnCsidl);
3266
3267     csidl = csidl_from_id( rfid );
3268     if (csidl == -1) return E_INVALIDARG;
3269     *pnCsidl = csidl;
3270     return S_OK;
3271 }
3272
3273 static HRESULT WINAPI foldermanager_GetFolderIds(
3274     IKnownFolderManager *iface,
3275     KNOWNFOLDERID **ppKFId,
3276     UINT *pCount)
3277 {
3278     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3279
3280     TRACE("%p, %p\n", ppKFId, pCount);
3281
3282     *ppKFId = fm->ids;
3283     *pCount = fm->num_ids;
3284     return S_OK;
3285 }
3286
3287 static BOOL is_knownfolder( struct foldermanager *fm, const KNOWNFOLDERID *id )
3288 {
3289     UINT i;
3290
3291     for (i = 0; i < fm->num_ids; i++)
3292         if (IsEqualGUID( &fm->ids[i], id )) return TRUE;
3293
3294     return FALSE;
3295 }
3296
3297 static HRESULT WINAPI foldermanager_GetFolder(
3298     IKnownFolderManager *iface,
3299     REFKNOWNFOLDERID rfid,
3300     IKnownFolder **ppkf)
3301 {
3302     struct foldermanager *fm = impl_from_IKnownFolderManager( iface );
3303     HRESULT hr;
3304
3305     TRACE("%s, %p\n", debugstr_guid(rfid), ppkf);
3306
3307     if (!is_knownfolder( fm, rfid ))
3308     {
3309         WARN("unknown folder\n");
3310         return E_INVALIDARG;
3311     }
3312     hr = knownfolder_create( (void **)ppkf );
3313     if (SUCCEEDED( hr ))
3314         hr = knowfolder_set_id( *ppkf, rfid );
3315
3316     return hr;
3317 }
3318
3319 static HRESULT WINAPI foldermanager_GetFolderByName(
3320     IKnownFolderManager *iface,
3321     LPCWSTR pszCanonicalName,
3322     IKnownFolder **ppkf)
3323 {
3324     FIXME("%s, %p\n", debugstr_w(pszCanonicalName), ppkf);
3325     return E_NOTIMPL;
3326 }
3327
3328 static HRESULT WINAPI foldermanager_RegisterFolder(
3329     IKnownFolderManager *iface,
3330     REFKNOWNFOLDERID rfid,
3331     KNOWNFOLDER_DEFINITION const *pKFD)
3332 {
3333     FIXME("%p, %p\n", rfid, pKFD);
3334     return E_NOTIMPL;
3335 }
3336
3337 static HRESULT WINAPI foldermanager_UnregisterFolder(
3338     IKnownFolderManager *iface,
3339     REFKNOWNFOLDERID rfid)
3340 {
3341     FIXME("%p\n", rfid);
3342     return E_NOTIMPL;
3343 }
3344
3345 static HRESULT WINAPI foldermanager_FindFolderFromPath(
3346     IKnownFolderManager *iface,
3347     LPCWSTR pszPath,
3348     FFFP_MODE mode,
3349     IKnownFolder **ppkf)
3350 {
3351     FIXME("%s, 0x%08x, %p\n", debugstr_w(pszPath), mode, ppkf);
3352     return E_NOTIMPL;
3353 }
3354
3355 static HRESULT WINAPI foldermanager_FindFolderFromIDList(
3356     IKnownFolderManager *iface,
3357     PCIDLIST_ABSOLUTE pidl,
3358     IKnownFolder **ppkf)
3359 {
3360     FIXME("%p, %p\n", pidl, ppkf);
3361     return E_NOTIMPL;
3362 }
3363
3364 static HRESULT WINAPI foldermanager_Redirect(
3365     IKnownFolderManager *iface,
3366     REFKNOWNFOLDERID rfid,
3367     HWND hwnd,
3368     KF_REDIRECT_FLAGS flags,
3369     LPCWSTR pszTargetPath,
3370     UINT cFolders,
3371     KNOWNFOLDERID const *pExclusion,
3372     LPWSTR *ppszError)
3373 {
3374     FIXME("%p, %p, 0x%08x, %s, %u, %p, %p\n", rfid, hwnd, flags,
3375           debugstr_w(pszTargetPath), cFolders, pExclusion, ppszError);
3376     return E_NOTIMPL;
3377 }
3378
3379 static const struct IKnownFolderManagerVtbl foldermanager_vtbl =
3380 {
3381     foldermanager_QueryInterface,
3382     foldermanager_AddRef,
3383     foldermanager_Release,
3384     foldermanager_FolderIdFromCsidl,
3385     foldermanager_FolderIdToCsidl,
3386     foldermanager_GetFolderIds,
3387     foldermanager_GetFolder,
3388     foldermanager_GetFolderByName,
3389     foldermanager_RegisterFolder,
3390     foldermanager_UnregisterFolder,
3391     foldermanager_FindFolderFromPath,
3392     foldermanager_FindFolderFromIDList,
3393     foldermanager_Redirect
3394 };
3395
3396 static HRESULT foldermanager_create( void **ppv )
3397 {
3398     UINT i, j;
3399     struct foldermanager *fm;
3400
3401     fm = HeapAlloc( GetProcessHeap(), 0, sizeof(*fm) );
3402     if (!fm) return E_OUTOFMEMORY;
3403
3404     fm->vtbl = &foldermanager_vtbl;
3405     fm->refs = 1;
3406     fm->num_ids = 0;
3407
3408     for (i = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3409     {
3410         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL )) fm->num_ids++;
3411     }
3412     fm->ids = HeapAlloc( GetProcessHeap(), 0, fm->num_ids * sizeof(KNOWNFOLDERID) );
3413     if (!fm->ids)
3414     {
3415         HeapFree( GetProcessHeap(), 0, fm );
3416         return E_OUTOFMEMORY;
3417     }
3418     for (i = j = 0; i < sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]); i++)
3419     {
3420         if (!IsEqualGUID( CSIDL_Data[i].id, &GUID_NULL ))
3421         {
3422             fm->ids[j] = *CSIDL_Data[i].id;
3423             j++;
3424         }
3425     }
3426     TRACE("found %u known folders\n", fm->num_ids);
3427     *ppv = &fm->vtbl;
3428
3429     TRACE("returning iface %p\n", *ppv);
3430     return S_OK;
3431 }
3432
3433 HRESULT WINAPI KnownFolderManager_Constructor( IUnknown *punk, REFIID riid, void **ppv )
3434 {
3435     TRACE("%p, %s, %p\n", punk, debugstr_guid(riid), ppv);
3436
3437     if (!ppv)
3438         return E_POINTER;
3439     if (punk)
3440         return CLASS_E_NOAGGREGATION;
3441
3442     return foldermanager_create( ppv );
3443 }