shell32: Support getting the shell folder path for users other than the current user...
[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 #include "config.h"
28 #include "wine/port.h"
29
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include "wine/debug.h"
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winnls.h"
38 #include "winreg.h"
39 #include "wingdi.h"
40 #include "winuser.h"
41
42 #include "shlobj.h"
43 #include "shresdef.h"
44 #include "shell32_main.h"
45 #include "undocshell.h"
46 #include "pidl.h"
47 #include "wine/unicode.h"
48 #include "shlwapi.h"
49 #include "xdg.h"
50 #include "sddl.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(shell);
53
54 /*
55         ########## Combining and Constructing paths ##########
56 */
57
58 /*************************************************************************
59  * PathAppend           [SHELL32.36]
60  */
61 BOOL WINAPI PathAppendAW(
62         LPVOID lpszPath1,
63         LPCVOID lpszPath2)
64 {
65         if (SHELL_OsIsUnicode())
66           return PathAppendW(lpszPath1, lpszPath2);
67         return PathAppendA(lpszPath1, lpszPath2);
68 }
69
70 /*************************************************************************
71  * PathCombine   [SHELL32.37]
72  */
73 LPVOID WINAPI PathCombineAW(
74         LPVOID szDest,
75         LPCVOID lpszDir,
76         LPCVOID lpszFile)
77 {
78         if (SHELL_OsIsUnicode())
79           return PathCombineW( szDest, lpszDir, lpszFile );
80         return PathCombineA( szDest, lpszDir, lpszFile );
81 }
82
83 /*************************************************************************
84  * PathAddBackslash             [SHELL32.32]
85  */
86 LPVOID WINAPI PathAddBackslashAW(LPVOID lpszPath)
87 {
88         if(SHELL_OsIsUnicode())
89           return PathAddBackslashW(lpszPath);
90         return PathAddBackslashA(lpszPath);
91 }
92
93 /*************************************************************************
94  * PathBuildRoot                [SHELL32.30]
95  */
96 LPVOID WINAPI PathBuildRootAW(LPVOID lpszPath, int drive)
97 {
98         if(SHELL_OsIsUnicode())
99           return PathBuildRootW(lpszPath, drive);
100         return PathBuildRootA(lpszPath, drive);
101 }
102
103 /*
104         Extracting Component Parts
105 */
106
107 /*************************************************************************
108  * PathFindFileName     [SHELL32.34]
109  */
110 LPVOID WINAPI PathFindFileNameAW(LPCVOID lpszPath)
111 {
112         if(SHELL_OsIsUnicode())
113           return PathFindFileNameW(lpszPath);
114         return PathFindFileNameA(lpszPath);
115 }
116
117 /*************************************************************************
118  * PathFindExtension            [SHELL32.31]
119  */
120 LPVOID WINAPI PathFindExtensionAW(LPCVOID lpszPath)
121 {
122         if (SHELL_OsIsUnicode())
123           return PathFindExtensionW(lpszPath);
124         return PathFindExtensionA(lpszPath);
125
126 }
127
128 /*************************************************************************
129  * PathGetExtensionA            [internal]
130  *
131  * NOTES
132  *  exported by ordinal
133  *  return value points to the first char after the dot
134  */
135 static LPSTR PathGetExtensionA(LPCSTR lpszPath)
136 {
137         TRACE("(%s)\n",lpszPath);
138
139         lpszPath = PathFindExtensionA(lpszPath);
140         return (LPSTR)(*lpszPath?(lpszPath+1):lpszPath);
141 }
142
143 /*************************************************************************
144  * PathGetExtensionW            [internal]
145  */
146 static LPWSTR PathGetExtensionW(LPCWSTR lpszPath)
147 {
148         TRACE("(%s)\n",debugstr_w(lpszPath));
149
150         lpszPath = PathFindExtensionW(lpszPath);
151         return (LPWSTR)(*lpszPath?(lpszPath+1):lpszPath);
152 }
153
154 /*************************************************************************
155  * PathGetExtension             [SHELL32.158]
156  */
157 LPVOID WINAPI PathGetExtensionAW(LPCVOID lpszPath,DWORD void1, DWORD void2)
158 {
159         if (SHELL_OsIsUnicode())
160           return PathGetExtensionW(lpszPath);
161         return PathGetExtensionA(lpszPath);
162 }
163
164 /*************************************************************************
165  * PathGetArgs  [SHELL32.52]
166  */
167 LPVOID WINAPI PathGetArgsAW(LPVOID lpszPath)
168 {
169         if (SHELL_OsIsUnicode())
170           return PathGetArgsW(lpszPath);
171         return PathGetArgsA(lpszPath);
172 }
173
174 /*************************************************************************
175  * PathGetDriveNumber   [SHELL32.57]
176  */
177 int WINAPI PathGetDriveNumberAW(LPVOID lpszPath)
178 {
179         if (SHELL_OsIsUnicode())
180           return PathGetDriveNumberW(lpszPath);
181         return PathGetDriveNumberA(lpszPath);
182 }
183
184 /*************************************************************************
185  * PathRemoveFileSpec [SHELL32.35]
186  */
187 BOOL WINAPI PathRemoveFileSpecAW(LPVOID lpszPath)
188 {
189         if (SHELL_OsIsUnicode())
190           return PathRemoveFileSpecW(lpszPath);
191         return PathRemoveFileSpecA(lpszPath);
192 }
193
194 /*************************************************************************
195  * PathStripPath        [SHELL32.38]
196  */
197 void WINAPI PathStripPathAW(LPVOID lpszPath)
198 {
199         if (SHELL_OsIsUnicode())
200             PathStripPathW(lpszPath);
201         else
202             PathStripPathA(lpszPath);
203 }
204
205 /*************************************************************************
206  * PathStripToRoot      [SHELL32.50]
207  */
208 BOOL WINAPI PathStripToRootAW(LPVOID lpszPath)
209 {
210         if (SHELL_OsIsUnicode())
211           return PathStripToRootW(lpszPath);
212         return PathStripToRootA(lpszPath);
213 }
214
215 /*************************************************************************
216  * PathRemoveArgs       [SHELL32.251]
217  */
218 void WINAPI PathRemoveArgsAW(LPVOID lpszPath)
219 {
220         if (SHELL_OsIsUnicode())
221             PathRemoveArgsW(lpszPath);
222         else
223             PathRemoveArgsA(lpszPath);
224 }
225
226 /*************************************************************************
227  * PathRemoveExtension  [SHELL32.250]
228  */
229 void WINAPI PathRemoveExtensionAW(LPVOID lpszPath)
230 {
231         if (SHELL_OsIsUnicode())
232             PathRemoveExtensionW(lpszPath);
233         else
234             PathRemoveExtensionA(lpszPath);
235 }
236
237
238 /*
239         Path Manipulations
240 */
241
242 /*************************************************************************
243  * PathGetShortPathA [internal]
244  */
245 static void PathGetShortPathA(LPSTR pszPath)
246 {
247         CHAR path[MAX_PATH];
248
249         TRACE("%s\n", pszPath);
250
251         if (GetShortPathNameA(pszPath, path, MAX_PATH))
252         {
253           lstrcpyA(pszPath, path);
254         }
255 }
256
257 /*************************************************************************
258  * PathGetShortPathW [internal]
259  */
260 static void PathGetShortPathW(LPWSTR pszPath)
261 {
262         WCHAR path[MAX_PATH];
263
264         TRACE("%s\n", debugstr_w(pszPath));
265
266         if (GetShortPathNameW(pszPath, path, MAX_PATH))
267         {
268           lstrcpyW(pszPath, path);
269         }
270 }
271
272 /*************************************************************************
273  * PathGetShortPath [SHELL32.92]
274  */
275 VOID WINAPI PathGetShortPathAW(LPVOID pszPath)
276 {
277         if(SHELL_OsIsUnicode())
278           PathGetShortPathW(pszPath);
279         PathGetShortPathA(pszPath);
280 }
281
282 /*************************************************************************
283  * PathRemoveBlanks [SHELL32.33]
284  */
285 void WINAPI PathRemoveBlanksAW(LPVOID str)
286 {
287         if(SHELL_OsIsUnicode())
288             PathRemoveBlanksW(str);
289         else
290             PathRemoveBlanksA(str);
291 }
292
293 /*************************************************************************
294  * PathQuoteSpaces [SHELL32.55]
295  */
296 VOID WINAPI PathQuoteSpacesAW (LPVOID lpszPath)
297 {
298         if(SHELL_OsIsUnicode())
299             PathQuoteSpacesW(lpszPath);
300         else
301             PathQuoteSpacesA(lpszPath);
302 }
303
304 /*************************************************************************
305  * PathUnquoteSpaces [SHELL32.56]
306  */
307 VOID WINAPI PathUnquoteSpacesAW(LPVOID str)
308 {
309         if(SHELL_OsIsUnicode())
310           PathUnquoteSpacesW(str);
311         else
312           PathUnquoteSpacesA(str);
313 }
314
315 /*************************************************************************
316  * PathParseIconLocation        [SHELL32.249]
317  */
318 int WINAPI PathParseIconLocationAW (LPVOID lpszPath)
319 {
320         if(SHELL_OsIsUnicode())
321           return PathParseIconLocationW(lpszPath);
322         return PathParseIconLocationA(lpszPath);
323 }
324
325 /*
326         ########## Path Testing ##########
327 */
328 /*************************************************************************
329  * PathIsUNC            [SHELL32.39]
330  */
331 BOOL WINAPI PathIsUNCAW (LPCVOID lpszPath)
332 {
333         if (SHELL_OsIsUnicode())
334           return PathIsUNCW( lpszPath );
335         return PathIsUNCA( lpszPath );
336 }
337
338 /*************************************************************************
339  *  PathIsRelative      [SHELL32.40]
340  */
341 BOOL WINAPI PathIsRelativeAW (LPCVOID lpszPath)
342 {
343         if (SHELL_OsIsUnicode())
344           return PathIsRelativeW( lpszPath );
345         return PathIsRelativeA( lpszPath );
346 }
347
348 /*************************************************************************
349  * PathIsRoot           [SHELL32.29]
350  */
351 BOOL WINAPI PathIsRootAW(LPCVOID lpszPath)
352 {
353         if (SHELL_OsIsUnicode())
354           return PathIsRootW(lpszPath);
355         return PathIsRootA(lpszPath);
356 }
357
358 /*************************************************************************
359  *  PathIsExeA          [internal]
360  */
361 static BOOL PathIsExeA (LPCSTR lpszPath)
362 {
363         LPCSTR lpszExtension = PathGetExtensionA(lpszPath);
364         int i;
365         static const char * const lpszExtensions[] =
366             {"exe", "com", "pif", "cmd", "bat", "scf", "scr", NULL };
367
368         TRACE("path=%s\n",lpszPath);
369
370         for(i=0; lpszExtensions[i]; i++)
371           if (!lstrcmpiA(lpszExtension,lpszExtensions[i])) return TRUE;
372
373         return FALSE;
374 }
375
376 /*************************************************************************
377  *  PathIsExeW          [internal]
378  */
379 static BOOL PathIsExeW (LPCWSTR lpszPath)
380 {
381         LPCWSTR lpszExtension = PathGetExtensionW(lpszPath);
382         int i;
383         static const WCHAR lpszExtensions[][4] =
384             {{'e','x','e','\0'}, {'c','o','m','\0'}, {'p','i','f','\0'},
385              {'c','m','d','\0'}, {'b','a','t','\0'}, {'s','c','f','\0'},
386              {'s','c','r','\0'}, {'\0'} };
387
388         TRACE("path=%s\n",debugstr_w(lpszPath));
389
390         for(i=0; lpszExtensions[i][0]; i++)
391           if (!strcmpiW(lpszExtension,lpszExtensions[i])) return TRUE;
392
393         return FALSE;
394 }
395
396 /*************************************************************************
397  *  PathIsExe           [SHELL32.43]
398  */
399 BOOL WINAPI PathIsExeAW (LPCVOID path)
400 {
401         if (SHELL_OsIsUnicode())
402           return PathIsExeW (path);
403         return PathIsExeA(path);
404 }
405
406 /*************************************************************************
407  * PathIsDirectory      [SHELL32.159]
408  */
409 BOOL WINAPI PathIsDirectoryAW (LPCVOID lpszPath)
410 {
411         if (SHELL_OsIsUnicode())
412           return PathIsDirectoryW (lpszPath);
413         return PathIsDirectoryA (lpszPath);
414 }
415
416 /*************************************************************************
417  * PathFileExists       [SHELL32.45]
418  */
419 BOOL WINAPI PathFileExistsAW (LPCVOID lpszPath)
420 {
421         if (SHELL_OsIsUnicode())
422           return PathFileExistsW (lpszPath);
423         return PathFileExistsA (lpszPath);
424 }
425
426 /*************************************************************************
427  * PathMatchSpec        [SHELL32.46]
428  */
429 BOOL WINAPI PathMatchSpecAW(LPVOID name, LPVOID mask)
430 {
431         if (SHELL_OsIsUnicode())
432           return PathMatchSpecW( name, mask );
433         return PathMatchSpecA( name, mask );
434 }
435
436 /*************************************************************************
437  * PathIsSameRoot       [SHELL32.650]
438  */
439 BOOL WINAPI PathIsSameRootAW(LPCVOID lpszPath1, LPCVOID lpszPath2)
440 {
441         if (SHELL_OsIsUnicode())
442           return PathIsSameRootW(lpszPath1, lpszPath2);
443         return PathIsSameRootA(lpszPath1, lpszPath2);
444 }
445
446 /*************************************************************************
447  * IsLFNDriveA          [SHELL32.41]
448  */
449 BOOL WINAPI IsLFNDriveA(LPCSTR lpszPath)
450 {
451     DWORD       fnlen;
452
453     if (!GetVolumeInformationA(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
454         return FALSE;
455     return fnlen > 12;
456 }
457
458 /*************************************************************************
459  * IsLFNDriveW          [SHELL32.42]
460  */
461 BOOL WINAPI IsLFNDriveW(LPCWSTR lpszPath)
462 {
463     DWORD       fnlen;
464
465     if (!GetVolumeInformationW(lpszPath, NULL, 0, NULL, &fnlen, NULL, NULL, 0))
466         return FALSE;
467     return fnlen > 12;
468 }
469
470 /*************************************************************************
471  * IsLFNDrive           [SHELL32.119]
472  */
473 BOOL WINAPI IsLFNDriveAW(LPCVOID lpszPath)
474 {
475         if (SHELL_OsIsUnicode())
476           return IsLFNDriveW(lpszPath);
477         return IsLFNDriveA(lpszPath);
478 }
479
480 /*
481         ########## Creating Something Unique ##########
482 */
483 /*************************************************************************
484  * PathMakeUniqueNameA  [internal]
485  */
486 BOOL WINAPI PathMakeUniqueNameA(
487         LPSTR lpszBuffer,
488         DWORD dwBuffSize,
489         LPCSTR lpszShortName,
490         LPCSTR lpszLongName,
491         LPCSTR lpszPathName)
492 {
493         FIXME("%p %u %s %s %s stub\n",
494          lpszBuffer, dwBuffSize, debugstr_a(lpszShortName),
495          debugstr_a(lpszLongName), debugstr_a(lpszPathName));
496         return TRUE;
497 }
498
499 /*************************************************************************
500  * PathMakeUniqueNameW  [internal]
501  */
502 BOOL WINAPI PathMakeUniqueNameW(
503         LPWSTR lpszBuffer,
504         DWORD dwBuffSize,
505         LPCWSTR lpszShortName,
506         LPCWSTR lpszLongName,
507         LPCWSTR lpszPathName)
508 {
509         FIXME("%p %u %s %s %s stub\n",
510          lpszBuffer, dwBuffSize, debugstr_w(lpszShortName),
511          debugstr_w(lpszLongName), debugstr_w(lpszPathName));
512         return TRUE;
513 }
514
515 /*************************************************************************
516  * PathMakeUniqueName   [SHELL32.47]
517  */
518 BOOL WINAPI PathMakeUniqueNameAW(
519         LPVOID lpszBuffer,
520         DWORD dwBuffSize,
521         LPCVOID lpszShortName,
522         LPCVOID lpszLongName,
523         LPCVOID lpszPathName)
524 {
525         if (SHELL_OsIsUnicode())
526           return PathMakeUniqueNameW(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
527         return PathMakeUniqueNameA(lpszBuffer,dwBuffSize, lpszShortName,lpszLongName,lpszPathName);
528 }
529
530 /*************************************************************************
531  * PathYetAnotherMakeUniqueName [SHELL32.75]
532  *
533  * NOTES
534  *     exported by ordinal
535  */
536 BOOL WINAPI PathYetAnotherMakeUniqueName(
537         LPWSTR lpszBuffer,
538         LPCWSTR lpszPathName,
539         LPCWSTR lpszShortName,
540         LPCWSTR lpszLongName)
541 {
542     FIXME("(%p, %s, %s ,%s):stub.\n",
543           lpszBuffer, debugstr_w(lpszPathName), debugstr_w(lpszShortName), debugstr_w(lpszLongName));
544     return TRUE;
545 }
546
547
548 /*
549         ########## cleaning and resolving paths ##########
550  */
551
552 /*************************************************************************
553  * PathFindOnPath       [SHELL32.145]
554  */
555 BOOL WINAPI PathFindOnPathAW(LPVOID sFile, LPCVOID *sOtherDirs)
556 {
557         if (SHELL_OsIsUnicode())
558           return PathFindOnPathW(sFile, (LPCWSTR *)sOtherDirs);
559         return PathFindOnPathA(sFile, (LPCSTR *)sOtherDirs);
560 }
561
562 /*************************************************************************
563  * PathCleanupSpec      [SHELL32.171]
564  *
565  * lpszFile is changed in place.
566  */
567 int WINAPI PathCleanupSpec( LPCWSTR lpszPathW, LPWSTR lpszFileW )
568 {
569     int i = 0;
570     DWORD rc = 0;
571     int length = 0;
572
573     if (SHELL_OsIsUnicode())
574     {
575         LPWSTR p = lpszFileW;
576
577         TRACE("Cleanup %s\n",debugstr_w(lpszFileW));
578
579         if (lpszPathW)
580             length = strlenW(lpszPathW);
581
582         while (*p)
583         {
584             int gct = PathGetCharTypeW(*p);
585             if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
586             {
587                 lpszFileW[i]='-';
588                 rc |= PCS_REPLACEDCHAR;
589             }
590             else
591                 lpszFileW[i]=*p;
592             i++;
593             p++;
594             if (length + i == MAX_PATH)
595             {
596                 rc |= PCS_FATAL | PCS_PATHTOOLONG;
597                 break;
598             }
599         }
600         lpszFileW[i]=0;
601     }
602     else
603     {
604         LPSTR lpszFileA = (LPSTR)lpszFileW;
605         LPCSTR lpszPathA = (LPCSTR)lpszPathW;
606         LPSTR p = lpszFileA;
607
608         TRACE("Cleanup %s\n",debugstr_a(lpszFileA));
609
610         if (lpszPathA)
611             length = strlen(lpszPathA);
612
613         while (*p)
614         {
615             int gct = PathGetCharTypeA(*p);
616             if (gct == GCT_INVALID || gct == GCT_WILD || gct == GCT_SEPARATOR)
617             {
618                 lpszFileA[i]='-';
619                 rc |= PCS_REPLACEDCHAR;
620             }
621             else
622                 lpszFileA[i]=*p;
623             i++;
624             p++;
625             if (length + i == MAX_PATH)
626             {
627                 rc |= PCS_FATAL | PCS_PATHTOOLONG;
628                 break;
629             }
630         }
631         lpszFileA[i]=0;
632     }
633     return rc;
634 }
635
636 /*************************************************************************
637  * PathQualifyA         [SHELL32]
638  */
639 BOOL WINAPI PathQualifyA(LPCSTR pszPath)
640 {
641         FIXME("%s\n",pszPath);
642         return 0;
643 }
644
645 /*************************************************************************
646  * PathQualifyW         [SHELL32]
647  */
648 BOOL WINAPI PathQualifyW(LPCWSTR pszPath)
649 {
650         FIXME("%s\n",debugstr_w(pszPath));
651         return 0;
652 }
653
654 /*************************************************************************
655  * PathQualify  [SHELL32.49]
656  */
657 BOOL WINAPI PathQualifyAW(LPCVOID pszPath)
658 {
659         if (SHELL_OsIsUnicode())
660           return PathQualifyW(pszPath);
661         return PathQualifyA(pszPath);
662 }
663
664 /*************************************************************************
665  * PathResolveA [SHELL32.51]
666  */
667 BOOL WINAPI PathResolveA(
668         LPSTR lpszPath,
669         LPCSTR *alpszPaths,
670         DWORD dwFlags)
671 {
672         FIXME("(%s,%p,0x%08x),stub!\n",
673           lpszPath, *alpszPaths, dwFlags);
674         return 0;
675 }
676
677 /*************************************************************************
678  * PathResolveW [SHELL32]
679  */
680 BOOL WINAPI PathResolveW(
681         LPWSTR lpszPath,
682         LPCWSTR *alpszPaths,
683         DWORD dwFlags)
684 {
685         FIXME("(%s,%p,0x%08x),stub!\n",
686           debugstr_w(lpszPath), debugstr_w(*alpszPaths), dwFlags);
687         return 0;
688 }
689
690 /*************************************************************************
691  * PathResolve [SHELL32.51]
692  */
693 BOOL WINAPI PathResolveAW(
694         LPVOID lpszPath,
695         LPCVOID *alpszPaths,
696         DWORD dwFlags)
697 {
698         if (SHELL_OsIsUnicode())
699           return PathResolveW(lpszPath, (LPCWSTR*)alpszPaths, dwFlags);
700         return PathResolveA(lpszPath, (LPCSTR*)alpszPaths, dwFlags);
701 }
702
703 /*************************************************************************
704 *       PathProcessCommandA     [SHELL32.653]
705 */
706 LONG WINAPI PathProcessCommandA (
707         LPCSTR lpszPath,
708         LPSTR lpszBuff,
709         DWORD dwBuffSize,
710         DWORD dwFlags)
711 {
712         FIXME("%s %p 0x%04x 0x%04x stub\n",
713         lpszPath, lpszBuff, dwBuffSize, dwFlags);
714         if(!lpszPath) return -1;
715         if(lpszBuff) strcpy(lpszBuff, lpszPath);
716         return strlen(lpszPath);
717 }
718
719 /*************************************************************************
720 *       PathProcessCommandW
721 */
722 LONG WINAPI PathProcessCommandW (
723         LPCWSTR lpszPath,
724         LPWSTR lpszBuff,
725         DWORD dwBuffSize,
726         DWORD dwFlags)
727 {
728         FIXME("(%s, %p, 0x%04x, 0x%04x) stub\n",
729         debugstr_w(lpszPath), lpszBuff, dwBuffSize, dwFlags);
730         if(!lpszPath) return -1;
731         if(lpszBuff) strcpyW(lpszBuff, lpszPath);
732         return strlenW(lpszPath);
733 }
734
735 /*************************************************************************
736 *       PathProcessCommand (SHELL32.653)
737 */
738 LONG WINAPI PathProcessCommandAW (
739         LPCVOID lpszPath,
740         LPVOID lpszBuff,
741         DWORD dwBuffSize,
742         DWORD dwFlags)
743 {
744         if (SHELL_OsIsUnicode())
745           return PathProcessCommandW(lpszPath, lpszBuff, dwBuffSize, dwFlags);
746         return PathProcessCommandA(lpszPath, lpszBuff, dwBuffSize, dwFlags);
747 }
748
749 /*
750         ########## special ##########
751 */
752
753 /*************************************************************************
754  * PathSetDlgItemPath (SHELL32.48)
755  */
756 VOID WINAPI PathSetDlgItemPathAW(HWND hDlg, int id, LPCVOID pszPath)
757 {
758         if (SHELL_OsIsUnicode())
759             PathSetDlgItemPathW(hDlg, id, pszPath);
760         else
761             PathSetDlgItemPathA(hDlg, id, pszPath);
762 }
763
764 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'};
765 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'};
766 static const WCHAR AppDataW[] = {'A','p','p','D','a','t','a','\0'};
767 static const WCHAR CacheW[] = {'C','a','c','h','e','\0'};
768 static const WCHAR CD_BurningW[] = {'C','D',' ','B','u','r','n','i','n','g','\0'};
769 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'};
770 static const WCHAR Common_AppDataW[] = {'C','o','m','m','o','n',' ','A','p','p','D','a','t','a','\0'};
771 static const WCHAR Common_DesktopW[] = {'C','o','m','m','o','n',' ','D','e','s','k','t','o','p','\0'};
772 static const WCHAR Common_DocumentsW[] = {'C','o','m','m','o','n',' ','D','o','c','u','m','e','n','t','s','\0'};
773 static const WCHAR CommonFilesDirW[] = {'C','o','m','m','o','n','F','i','l','e','s','D','i','r','\0'};
774 static const WCHAR CommonMusicW[] = {'C','o','m','m','o','n','M','u','s','i','c','\0'};
775 static const WCHAR CommonPicturesW[] = {'C','o','m','m','o','n','P','i','c','t','u','r','e','s','\0'};
776 static const WCHAR Common_ProgramsW[] = {'C','o','m','m','o','n',' ','P','r','o','g','r','a','m','s','\0'};
777 static const WCHAR Common_StartUpW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t','U','p','\0'};
778 static const WCHAR Common_Start_MenuW[] = {'C','o','m','m','o','n',' ','S','t','a','r','t',' ','M','e','n','u','\0'};
779 static const WCHAR Common_TemplatesW[] = {'C','o','m','m','o','n',' ','T','e','m','p','l','a','t','e','s','\0'};
780 static const WCHAR CommonVideoW[] = {'C','o','m','m','o','n','V','i','d','e','o','\0'};
781 static const WCHAR CookiesW[] = {'C','o','o','k','i','e','s','\0'};
782 static const WCHAR DesktopW[] = {'D','e','s','k','t','o','p','\0'};
783 static const WCHAR FavoritesW[] = {'F','a','v','o','r','i','t','e','s','\0'};
784 static const WCHAR FontsW[] = {'F','o','n','t','s','\0'};
785 static const WCHAR HistoryW[] = {'H','i','s','t','o','r','y','\0'};
786 static const WCHAR Local_AppDataW[] = {'L','o','c','a','l',' ','A','p','p','D','a','t','a','\0'};
787 static const WCHAR My_MusicW[] = {'M','y',' ','M','u','s','i','c','\0'};
788 static const WCHAR My_PicturesW[] = {'M','y',' ','P','i','c','t','u','r','e','s','\0'};
789 static const WCHAR My_VideoW[] = {'M','y',' ','V','i','d','e','o','s','\0'};
790 static const WCHAR NetHoodW[] = {'N','e','t','H','o','o','d','\0'};
791 static const WCHAR PersonalW[] = {'P','e','r','s','o','n','a','l','\0'};
792 static const WCHAR PrintHoodW[] = {'P','r','i','n','t','H','o','o','d','\0'};
793 static const WCHAR ProgramFilesDirW[] = {'P','r','o','g','r','a','m','F','i','l','e','s','D','i','r','\0'};
794 static const WCHAR ProgramsW[] = {'P','r','o','g','r','a','m','s','\0'};
795 static const WCHAR RecentW[] = {'R','e','c','e','n','t','\0'};
796 static const WCHAR ResourcesW[] = {'R','e','s','o','u','r','c','e','s','\0'};
797 static const WCHAR SendToW[] = {'S','e','n','d','T','o','\0'};
798 static const WCHAR StartUpW[] = {'S','t','a','r','t','U','p','\0'};
799 static const WCHAR Start_MenuW[] = {'S','t','a','r','t',' ','M','e','n','u','\0'};
800 static const WCHAR TemplatesW[] = {'T','e','m','p','l','a','t','e','s','\0'};
801 static const WCHAR DefaultW[] = {'.','D','e','f','a','u','l','t','\0'};
802 static const WCHAR AllUsersProfileW[] = {'%','A','L','L','U','S','E','R','S','P','R','O','F','I','L','E','%','\0'};
803 static const WCHAR UserProfileW[] = {'%','U','S','E','R','P','R','O','F','I','L','E','%','\0'};
804 static const WCHAR SystemDriveW[] = {'%','S','y','s','t','e','m','D','r','i','v','e','%','\0'};
805 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};
806 static const WCHAR ProfilesDirectoryW[] = {'P','r','o','f','i','l','e','s','D','i','r','e','c','t','o','r','y',0};
807 static const WCHAR AllUsersProfileValueW[] = {'A','l','l','U','s','e','r','s','P','r','o','f','i','l','e','\0'};
808 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'};
809 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'};
810 /* This defaults to L"Documents and Settings" on Windows 2000/XP, but we're
811  * acting more Windows 9x-like for now.
812  */
813 static const WCHAR szDefaultProfileDirW[] = {'p','r','o','f','i','l','e','s','\0'};
814 static const WCHAR AllUsersW[] = {'A','l','l',' ','U','s','e','r','s','\0'};
815
816 typedef enum _CSIDL_Type {
817     CSIDL_Type_User,
818     CSIDL_Type_AllUsers,
819     CSIDL_Type_CurrVer,
820     CSIDL_Type_Disallowed,
821     CSIDL_Type_NonExistent,
822     CSIDL_Type_WindowsPath,
823     CSIDL_Type_SystemPath,
824 } CSIDL_Type;
825
826 typedef struct
827 {
828     CSIDL_Type type;
829     LPCWSTR    szValueName;
830     LPCWSTR    szDefaultPath; /* fallback string or resource ID */
831 } CSIDL_DATA;
832
833 static const CSIDL_DATA CSIDL_Data[] =
834 {
835     { /* 0x00 - CSIDL_DESKTOP */
836         CSIDL_Type_User,
837         DesktopW,
838         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
839     },
840     { /* 0x01 - CSIDL_INTERNET */
841         CSIDL_Type_Disallowed,
842         NULL,
843         NULL
844     },
845     { /* 0x02 - CSIDL_PROGRAMS */
846         CSIDL_Type_User,
847         ProgramsW,
848         MAKEINTRESOURCEW(IDS_PROGRAMS)
849     },
850     { /* 0x03 - CSIDL_CONTROLS (.CPL files) */
851         CSIDL_Type_SystemPath,
852         NULL,
853         NULL
854     },
855     { /* 0x04 - CSIDL_PRINTERS */
856         CSIDL_Type_SystemPath,
857         NULL,
858         NULL
859     },
860     { /* 0x05 - CSIDL_PERSONAL */
861         CSIDL_Type_User,
862         PersonalW,
863         MAKEINTRESOURCEW(IDS_PERSONAL)
864     },
865     { /* 0x06 - CSIDL_FAVORITES */
866         CSIDL_Type_User,
867         FavoritesW,
868         MAKEINTRESOURCEW(IDS_FAVORITES)
869     },
870     { /* 0x07 - CSIDL_STARTUP */
871         CSIDL_Type_User,
872         StartUpW,
873         MAKEINTRESOURCEW(IDS_STARTUP)
874     },
875     { /* 0x08 - CSIDL_RECENT */
876         CSIDL_Type_User,
877         RecentW,
878         MAKEINTRESOURCEW(IDS_RECENT)
879     },
880     { /* 0x09 - CSIDL_SENDTO */
881         CSIDL_Type_User,
882         SendToW,
883         MAKEINTRESOURCEW(IDS_SENDTO)
884     },
885     { /* 0x0a - CSIDL_BITBUCKET - Recycle Bin */
886         CSIDL_Type_Disallowed,
887         NULL,
888         NULL,
889     },
890     { /* 0x0b - CSIDL_STARTMENU */
891         CSIDL_Type_User,
892         Start_MenuW,
893         MAKEINTRESOURCEW(IDS_STARTMENU)
894     },
895     { /* 0x0c - CSIDL_MYDOCUMENTS */
896         CSIDL_Type_Disallowed, /* matches WinXP--can't get its path */
897         NULL,
898         NULL
899     },
900     { /* 0x0d - CSIDL_MYMUSIC */
901         CSIDL_Type_User,
902         My_MusicW,
903         MAKEINTRESOURCEW(IDS_MYMUSIC)
904     },
905     { /* 0x0e - CSIDL_MYVIDEO */
906         CSIDL_Type_User,
907         My_VideoW,
908         MAKEINTRESOURCEW(IDS_MYVIDEO)
909     },
910     { /* 0x0f - unassigned */
911         CSIDL_Type_Disallowed,
912         NULL,
913         NULL,
914     },
915     { /* 0x10 - CSIDL_DESKTOPDIRECTORY */
916         CSIDL_Type_User,
917         DesktopW,
918         MAKEINTRESOURCEW(IDS_DESKTOPDIRECTORY)
919     },
920     { /* 0x11 - CSIDL_DRIVES */
921         CSIDL_Type_Disallowed,
922         NULL,
923         NULL,
924     },
925     { /* 0x12 - CSIDL_NETWORK */
926         CSIDL_Type_Disallowed,
927         NULL,
928         NULL,
929     },
930     { /* 0x13 - CSIDL_NETHOOD */
931         CSIDL_Type_User,
932         NetHoodW,
933         MAKEINTRESOURCEW(IDS_NETHOOD)
934     },
935     { /* 0x14 - CSIDL_FONTS */
936         CSIDL_Type_WindowsPath,
937         FontsW,
938         FontsW
939     },
940     { /* 0x15 - CSIDL_TEMPLATES */
941         CSIDL_Type_User,
942         TemplatesW,
943         MAKEINTRESOURCEW(IDS_TEMPLATES)
944     },
945     { /* 0x16 - CSIDL_COMMON_STARTMENU */
946         CSIDL_Type_AllUsers,
947         Common_Start_MenuW,
948         MAKEINTRESOURCEW(IDS_STARTMENU)
949     },
950     { /* 0x17 - CSIDL_COMMON_PROGRAMS */
951         CSIDL_Type_AllUsers,
952         Common_ProgramsW,
953         MAKEINTRESOURCEW(IDS_PROGRAMS)
954     },
955     { /* 0x18 - CSIDL_COMMON_STARTUP */
956         CSIDL_Type_AllUsers,
957         Common_StartUpW,
958         MAKEINTRESOURCEW(IDS_STARTUP)
959     },
960     { /* 0x19 - CSIDL_COMMON_DESKTOPDIRECTORY */
961         CSIDL_Type_AllUsers,
962         Common_DesktopW,
963         MAKEINTRESOURCEW(IDS_DESKTOP)
964     },
965     { /* 0x1a - CSIDL_APPDATA */
966         CSIDL_Type_User,
967         AppDataW,
968         MAKEINTRESOURCEW(IDS_APPDATA)
969     },
970     { /* 0x1b - CSIDL_PRINTHOOD */
971         CSIDL_Type_User,
972         PrintHoodW,
973         MAKEINTRESOURCEW(IDS_PRINTHOOD)
974     },
975     { /* 0x1c - CSIDL_LOCAL_APPDATA */
976         CSIDL_Type_User,
977         Local_AppDataW,
978         MAKEINTRESOURCEW(IDS_LOCAL_APPDATA)
979     },
980     { /* 0x1d - CSIDL_ALTSTARTUP */
981         CSIDL_Type_NonExistent,
982         NULL,
983         NULL
984     },
985     { /* 0x1e - CSIDL_COMMON_ALTSTARTUP */
986         CSIDL_Type_NonExistent,
987         NULL,
988         NULL
989     },
990     { /* 0x1f - CSIDL_COMMON_FAVORITES */
991         CSIDL_Type_AllUsers,
992         FavoritesW,
993         MAKEINTRESOURCEW(IDS_FAVORITES)
994     },
995     { /* 0x20 - CSIDL_INTERNET_CACHE */
996         CSIDL_Type_User,
997         CacheW,
998         MAKEINTRESOURCEW(IDS_INTERNET_CACHE)
999     },
1000     { /* 0x21 - CSIDL_COOKIES */
1001         CSIDL_Type_User,
1002         CookiesW,
1003         MAKEINTRESOURCEW(IDS_COOKIES)
1004     },
1005     { /* 0x22 - CSIDL_HISTORY */
1006         CSIDL_Type_User,
1007         HistoryW,
1008         MAKEINTRESOURCEW(IDS_HISTORY)
1009     },
1010     { /* 0x23 - CSIDL_COMMON_APPDATA */
1011         CSIDL_Type_AllUsers,
1012         Common_AppDataW,
1013         MAKEINTRESOURCEW(IDS_APPDATA)
1014     },
1015     { /* 0x24 - CSIDL_WINDOWS */
1016         CSIDL_Type_WindowsPath,
1017         NULL,
1018         NULL
1019     },
1020     { /* 0x25 - CSIDL_SYSTEM */
1021         CSIDL_Type_SystemPath,
1022         NULL,
1023         NULL
1024     },
1025     { /* 0x26 - CSIDL_PROGRAM_FILES */
1026         CSIDL_Type_CurrVer,
1027         ProgramFilesDirW,
1028         MAKEINTRESOURCEW(IDS_PROGRAM_FILES)
1029     },
1030     { /* 0x27 - CSIDL_MYPICTURES */
1031         CSIDL_Type_User,
1032         My_PicturesW,
1033         MAKEINTRESOURCEW(IDS_MYPICTURES)
1034     },
1035     { /* 0x28 - CSIDL_PROFILE */
1036         CSIDL_Type_User,
1037         NULL,
1038         NULL
1039     },
1040     { /* 0x29 - CSIDL_SYSTEMX86 */
1041         CSIDL_Type_NonExistent,
1042         NULL,
1043         NULL
1044     },
1045     { /* 0x2a - CSIDL_PROGRAM_FILESX86 */
1046         CSIDL_Type_NonExistent,
1047         NULL,
1048         NULL
1049     },
1050     { /* 0x2b - CSIDL_PROGRAM_FILES_COMMON */
1051         CSIDL_Type_CurrVer,
1052         CommonFilesDirW,
1053         MAKEINTRESOURCEW(IDS_PROGRAM_FILES_COMMON)
1054     },
1055     { /* 0x2c - CSIDL_PROGRAM_FILES_COMMONX86 */
1056         CSIDL_Type_NonExistent,
1057         NULL,
1058         NULL
1059     },
1060     { /* 0x2d - CSIDL_COMMON_TEMPLATES */
1061         CSIDL_Type_AllUsers,
1062         Common_TemplatesW,
1063         MAKEINTRESOURCEW(IDS_TEMPLATES)
1064     },
1065     { /* 0x2e - CSIDL_COMMON_DOCUMENTS */
1066         CSIDL_Type_AllUsers,
1067         Common_DocumentsW,
1068         MAKEINTRESOURCEW(IDS_COMMON_DOCUMENTS)
1069     },
1070     { /* 0x2f - CSIDL_COMMON_ADMINTOOLS */
1071         CSIDL_Type_AllUsers,
1072         Common_Administrative_ToolsW,
1073         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1074     },
1075     { /* 0x30 - CSIDL_ADMINTOOLS */
1076         CSIDL_Type_User,
1077         Administrative_ToolsW,
1078         MAKEINTRESOURCEW(IDS_ADMINTOOLS)
1079     },
1080     { /* 0x31 - CSIDL_CONNECTIONS */
1081         CSIDL_Type_Disallowed,
1082         NULL,
1083         NULL
1084     },
1085     { /* 0x32 - unassigned */
1086         CSIDL_Type_Disallowed,
1087         NULL,
1088         NULL
1089     },
1090     { /* 0x33 - unassigned */
1091         CSIDL_Type_Disallowed,
1092         NULL,
1093         NULL
1094     },
1095     { /* 0x34 - unassigned */
1096         CSIDL_Type_Disallowed,
1097         NULL,
1098         NULL
1099     },
1100     { /* 0x35 - CSIDL_COMMON_MUSIC */
1101         CSIDL_Type_AllUsers,
1102         CommonMusicW,
1103         MAKEINTRESOURCEW(IDS_COMMON_MUSIC)
1104     },
1105     { /* 0x36 - CSIDL_COMMON_PICTURES */
1106         CSIDL_Type_AllUsers,
1107         CommonPicturesW,
1108         MAKEINTRESOURCEW(IDS_COMMON_PICTURES)
1109     },
1110     { /* 0x37 - CSIDL_COMMON_VIDEO */
1111         CSIDL_Type_AllUsers,
1112         CommonVideoW,
1113         MAKEINTRESOURCEW(IDS_COMMON_VIDEO)
1114     },
1115     { /* 0x38 - CSIDL_RESOURCES */
1116         CSIDL_Type_WindowsPath,
1117         NULL,
1118         ResourcesW
1119     },
1120     { /* 0x39 - CSIDL_RESOURCES_LOCALIZED */
1121         CSIDL_Type_NonExistent,
1122         NULL,
1123         NULL
1124     },
1125     { /* 0x3a - CSIDL_COMMON_OEM_LINKS */
1126         CSIDL_Type_NonExistent,
1127         NULL,
1128         NULL
1129     },
1130     { /* 0x3b - CSIDL_CDBURN_AREA */
1131         CSIDL_Type_User,
1132         CD_BurningW,
1133         MAKEINTRESOURCEW(IDS_CDBURN_AREA)
1134     },
1135     { /* 0x3c unassigned */
1136         CSIDL_Type_Disallowed,
1137         NULL,
1138         NULL
1139     },
1140     { /* 0x3d - CSIDL_COMPUTERSNEARME */
1141         CSIDL_Type_Disallowed, /* FIXME */
1142         NULL,
1143         NULL
1144     },
1145     { /* 0x3e - CSIDL_PROFILES */
1146         CSIDL_Type_Disallowed, /* oddly, this matches WinXP */
1147         NULL,
1148         NULL
1149     }
1150 };
1151
1152 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest);
1153
1154 /* Gets the value named value from the registry key
1155  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
1156  * (or from rootKey\userPrefix\... if userPrefix is not NULL) into path, which
1157  * is assumed to be MAX_PATH WCHARs in length.
1158  * If it exists, expands the value and writes the expanded value to
1159  * rootKey\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
1160  * Returns successful error code if the value was retrieved from the registry,
1161  * and a failure otherwise.
1162  */
1163 static HRESULT _SHGetUserShellFolderPath(HKEY rootKey, LPCWSTR userPrefix,
1164  LPCWSTR value, LPWSTR path)
1165 {
1166     HRESULT hr;
1167     WCHAR shellFolderPath[MAX_PATH], userShellFolderPath[MAX_PATH];
1168     LPCWSTR pShellFolderPath, pUserShellFolderPath;
1169     DWORD dwType, dwPathLen = MAX_PATH;
1170     HKEY userShellFolderKey, shellFolderKey;
1171
1172     TRACE("%p,%s,%s,%p\n",rootKey, debugstr_w(userPrefix), debugstr_w(value),
1173      path);
1174
1175     if (userPrefix)
1176     {
1177         strcpyW(shellFolderPath, userPrefix);
1178         PathAddBackslashW(shellFolderPath);
1179         strcatW(shellFolderPath, szSHFolders);
1180         pShellFolderPath = shellFolderPath;
1181         strcpyW(userShellFolderPath, userPrefix);
1182         PathAddBackslashW(userShellFolderPath);
1183         strcatW(userShellFolderPath, szSHUserFolders);
1184         pUserShellFolderPath = userShellFolderPath;
1185     }
1186     else
1187     {
1188         pUserShellFolderPath = szSHUserFolders;
1189         pShellFolderPath = szSHFolders;
1190     }
1191
1192     if (RegCreateKeyW(rootKey, pShellFolderPath, &shellFolderKey))
1193     {
1194         TRACE("Failed to create %s\n", debugstr_w(pShellFolderPath));
1195         return E_FAIL;
1196     }
1197     if (RegCreateKeyW(rootKey, pUserShellFolderPath, &userShellFolderKey))
1198     {
1199         TRACE("Failed to create %s\n",
1200          debugstr_w(pUserShellFolderPath));
1201         RegCloseKey(shellFolderKey);
1202         return E_FAIL;
1203     }
1204
1205     if (!RegQueryValueExW(userShellFolderKey, value, NULL, &dwType,
1206      (LPBYTE)path, &dwPathLen) && (dwType == REG_EXPAND_SZ || dwType == REG_SZ))
1207     {
1208         LONG ret;
1209
1210         path[dwPathLen / sizeof(WCHAR)] = '\0';
1211         if (dwType == REG_EXPAND_SZ && path[0] == '%')
1212         {
1213             WCHAR szTemp[MAX_PATH];
1214
1215             _SHExpandEnvironmentStrings(path, szTemp);
1216             lstrcpynW(path, szTemp, MAX_PATH);
1217         }
1218         ret = RegSetValueExW(shellFolderKey, value, 0, REG_SZ, (LPBYTE)path,
1219          (strlenW(path) + 1) * sizeof(WCHAR));
1220         if (ret != ERROR_SUCCESS)
1221             hr = HRESULT_FROM_WIN32(ret);
1222         else
1223             hr = S_OK;
1224     }
1225     else
1226         hr = E_FAIL;
1227     RegCloseKey(shellFolderKey);
1228     RegCloseKey(userShellFolderKey);
1229     TRACE("returning 0x%08x\n", hr);
1230     return hr;
1231 }
1232
1233 /* Gets a 'semi-expanded' default value of the CSIDL with index folder into
1234  * pszPath, based on the entries in CSIDL_Data.  By semi-expanded, I mean:
1235  * - The entry's szDefaultPath may be either a string value or an integer
1236  *   resource identifier.  In the latter case, the string value of the resource
1237  *   is written.
1238  * - Depending on the entry's type, the path may begin with an (unexpanded)
1239  *   environment variable name.  The caller is responsible for expanding
1240  *   environment strings if so desired.
1241  *   The types that are prepended with environment variables are:
1242  *   CSIDL_Type_User:     %USERPROFILE%
1243  *   CSIDL_Type_AllUsers: %ALLUSERSPROFILE%
1244  *   CSIDL_Type_CurrVer:  %SystemDrive%
1245  *   (Others might make sense too, but as yet are unneeded.)
1246  */
1247 static HRESULT _SHGetDefaultValue(BYTE folder, LPWSTR pszPath)
1248 {
1249     HRESULT hr;
1250     WCHAR resourcePath[MAX_PATH];
1251     LPCWSTR pDefaultPath = NULL;
1252
1253     TRACE("0x%02x,%p\n", folder, pszPath);
1254
1255     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1256         return E_INVALIDARG;
1257     if (!pszPath)
1258         return E_INVALIDARG;
1259
1260     if (CSIDL_Data[folder].szDefaultPath &&
1261      IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath))
1262     {
1263         if (LoadStringW(shell32_hInstance,
1264          LOWORD(CSIDL_Data[folder].szDefaultPath), resourcePath, MAX_PATH))
1265         {
1266             hr = S_OK;
1267             pDefaultPath = resourcePath;
1268         }
1269         else
1270         {
1271             FIXME("(%d,%s), LoadString failed, missing translation?\n", folder,
1272              debugstr_w(pszPath));
1273             hr = E_FAIL;
1274         }
1275     }
1276     else
1277     {
1278         hr = S_OK;
1279         pDefaultPath = CSIDL_Data[folder].szDefaultPath;
1280     }
1281     if (SUCCEEDED(hr))
1282     {
1283         switch (CSIDL_Data[folder].type)
1284         {
1285             case CSIDL_Type_User:
1286                 strcpyW(pszPath, UserProfileW);
1287                 break;
1288             case CSIDL_Type_AllUsers:
1289                 strcpyW(pszPath, AllUsersProfileW);
1290                 break;
1291             case CSIDL_Type_CurrVer:
1292                 strcpyW(pszPath, SystemDriveW);
1293                 break;
1294             default:
1295                 ; /* no corresponding env. var, do nothing */
1296         }
1297         if (pDefaultPath)
1298         {
1299             PathAddBackslashW(pszPath);
1300             strcatW(pszPath, pDefaultPath);
1301         }
1302     }
1303     TRACE("returning 0x%08x\n", hr);
1304     return hr;
1305 }
1306
1307 /* Gets the (unexpanded) value of the folder with index folder into pszPath.
1308  * The folder's type is assumed to be CSIDL_Type_CurrVer.  Its default value
1309  * can be overridden in the HKLM\\szCurrentVersion key.
1310  * If dwFlags has SHGFP_TYPE_DEFAULT set or if the value isn't overridden in
1311  * the registry, uses _SHGetDefaultValue to get the value.
1312  */
1313 static HRESULT _SHGetCurrentVersionPath(DWORD dwFlags, BYTE folder,
1314  LPWSTR pszPath)
1315 {
1316     HRESULT hr;
1317
1318     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1319
1320     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1321         return E_INVALIDARG;
1322     if (CSIDL_Data[folder].type != CSIDL_Type_CurrVer)
1323         return E_INVALIDARG;
1324     if (!pszPath)
1325         return E_INVALIDARG;
1326
1327     if (dwFlags & SHGFP_TYPE_DEFAULT)
1328         hr = _SHGetDefaultValue(folder, pszPath);
1329     else
1330     {
1331         HKEY hKey;
1332
1333         if (RegCreateKeyW(HKEY_LOCAL_MACHINE, szCurrentVersion, &hKey))
1334             hr = E_FAIL;
1335         else
1336         {
1337             DWORD dwType, dwPathLen = MAX_PATH * sizeof(WCHAR);
1338
1339             if (RegQueryValueExW(hKey, CSIDL_Data[folder].szValueName, NULL,
1340              &dwType, (LPBYTE)pszPath, &dwPathLen) ||
1341              (dwType != REG_SZ && dwType != REG_EXPAND_SZ))
1342             {
1343                 hr = _SHGetDefaultValue(folder, pszPath);
1344                 dwType = REG_EXPAND_SZ;
1345                 RegSetValueExW(hKey, CSIDL_Data[folder].szValueName, 0, dwType,
1346                  (LPBYTE)pszPath, (strlenW(pszPath)+1)*sizeof(WCHAR));
1347             }
1348             else
1349             {
1350                 pszPath[dwPathLen / sizeof(WCHAR)] = '\0';
1351                 hr = S_OK;
1352             }
1353             RegCloseKey(hKey);
1354         }
1355     }
1356     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1357     return hr;
1358 }
1359
1360 static LPWSTR _GetUserSidStringFromToken(HANDLE Token)
1361 {
1362     char InfoBuffer[64];
1363     PTOKEN_USER UserInfo;
1364     DWORD InfoSize;
1365     LPWSTR SidStr;
1366
1367     UserInfo = (PTOKEN_USER) InfoBuffer;
1368     if (! GetTokenInformation(Token, TokenUser, InfoBuffer, sizeof(InfoBuffer),
1369                               &InfoSize))
1370     {
1371         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1372             return NULL;
1373         UserInfo = HeapAlloc(GetProcessHeap(), 0, InfoSize);
1374         if (UserInfo == NULL)
1375             return NULL;
1376         if (! GetTokenInformation(Token, TokenUser, UserInfo, InfoSize,
1377                                   &InfoSize))
1378         {
1379             HeapFree(GetProcessHeap(), 0, UserInfo);
1380             return NULL;
1381         }
1382     }
1383
1384     if (! ConvertSidToStringSidW(UserInfo->User.Sid, &SidStr))
1385         SidStr = NULL;
1386
1387     if (UserInfo != (PTOKEN_USER) InfoBuffer)
1388         HeapFree(GetProcessHeap(), 0, UserInfo);
1389
1390     return SidStr;
1391 }
1392
1393 /* Gets the user's path (unexpanded) for the CSIDL with index folder:
1394  * If SHGFP_TYPE_DEFAULT is set, calls _SHGetDefaultValue for it.  Otherwise
1395  * calls _SHGetUserShellFolderPath for it.  Where it looks depends on hToken:
1396  * - if hToken is -1, looks in HKEY_USERS\.Default
1397  * - otherwise looks first in HKEY_CURRENT_USER, followed by HKEY_LOCAL_MACHINE
1398  *   if HKEY_CURRENT_USER doesn't contain any entries.  If both fail, finally
1399  *   calls _SHGetDefaultValue for it.
1400  */
1401 static HRESULT _SHGetUserProfilePath(HANDLE hToken, DWORD dwFlags, BYTE folder,
1402  LPWSTR pszPath)
1403 {
1404     HRESULT hr;
1405
1406     TRACE("%p,0x%08x,0x%02x,%p\n", hToken, dwFlags, folder, pszPath);
1407
1408     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1409         return E_INVALIDARG;
1410     if (CSIDL_Data[folder].type != CSIDL_Type_User)
1411         return E_INVALIDARG;
1412     if (!pszPath)
1413         return E_INVALIDARG;
1414
1415     if (dwFlags & SHGFP_TYPE_DEFAULT)
1416     {
1417         if (hToken != NULL && hToken != (HANDLE)-1)
1418         {
1419             FIXME("unsupported for user other than current or default\n");
1420             return E_FAIL;
1421         }
1422         hr = _SHGetDefaultValue(folder, pszPath);
1423     }
1424     else
1425     {
1426         LPCWSTR userPrefix = NULL;
1427         HKEY hRootKey;
1428
1429         if (hToken == (HANDLE)-1)
1430         {
1431             hRootKey = HKEY_USERS;
1432             userPrefix = DefaultW;
1433         }
1434         else if (hToken == NULL)
1435             hRootKey = HKEY_CURRENT_USER;
1436         else
1437         {
1438             hRootKey = HKEY_USERS;
1439             userPrefix = _GetUserSidStringFromToken(hToken);
1440             if (userPrefix == NULL)
1441             {
1442                 hr = E_FAIL;
1443                 goto error;
1444             }
1445         }
1446         hr = _SHGetUserShellFolderPath(hRootKey, userPrefix,
1447          CSIDL_Data[folder].szValueName, pszPath);
1448         if (FAILED(hr) && hRootKey != HKEY_LOCAL_MACHINE)
1449             hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1450              CSIDL_Data[folder].szValueName, pszPath);
1451         if (FAILED(hr))
1452             hr = _SHGetDefaultValue(folder, pszPath);
1453         if (userPrefix != NULL && userPrefix != DefaultW)
1454             LocalFree((HLOCAL) userPrefix);
1455     }
1456 error:
1457     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1458     return hr;
1459 }
1460
1461 /* Gets the (unexpanded) path for the CSIDL with index folder.  If dwFlags has
1462  * SHGFP_TYPE_DEFAULT set, calls _SHGetDefaultValue.  Otherwise calls
1463  * _SHGetUserShellFolderPath for it, looking only in HKEY_LOCAL_MACHINE.
1464  * If this fails, falls back to _SHGetDefaultValue.
1465  */
1466 static HRESULT _SHGetAllUsersProfilePath(DWORD dwFlags, BYTE folder,
1467  LPWSTR pszPath)
1468 {
1469     HRESULT hr;
1470
1471     TRACE("0x%08x,0x%02x,%p\n", dwFlags, folder, pszPath);
1472
1473     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1474         return E_INVALIDARG;
1475     if (CSIDL_Data[folder].type != CSIDL_Type_AllUsers)
1476         return E_INVALIDARG;
1477     if (!pszPath)
1478         return E_INVALIDARG;
1479
1480     if (dwFlags & SHGFP_TYPE_DEFAULT)
1481         hr = _SHGetDefaultValue(folder, pszPath);
1482     else
1483     {
1484         hr = _SHGetUserShellFolderPath(HKEY_LOCAL_MACHINE, NULL,
1485          CSIDL_Data[folder].szValueName, pszPath);
1486         if (FAILED(hr))
1487             hr = _SHGetDefaultValue(folder, pszPath);
1488     }
1489     TRACE("returning 0x%08x (output path is %s)\n", hr, debugstr_w(pszPath));
1490     return hr;
1491 }
1492
1493 static HRESULT _SHOpenProfilesKey(PHKEY pKey)
1494 {
1495     LONG lRet;
1496     DWORD disp;
1497
1498     lRet = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ProfileListW, 0, NULL, 0,
1499      KEY_ALL_ACCESS, NULL, pKey, &disp);
1500     return HRESULT_FROM_WIN32(lRet);
1501 }
1502
1503 /* Reads the value named szValueName from the key profilesKey (assumed to be
1504  * opened by _SHOpenProfilesKey) into szValue, which is assumed to be MAX_PATH
1505  * WCHARs in length.  If it doesn't exist, returns szDefault (and saves
1506  * szDefault to the registry).
1507  */
1508 static HRESULT _SHGetProfilesValue(HKEY profilesKey, LPCWSTR szValueName,
1509  LPWSTR szValue, LPCWSTR szDefault)
1510 {
1511     HRESULT hr;
1512     DWORD type, dwPathLen = MAX_PATH * sizeof(WCHAR);
1513     LONG lRet;
1514
1515     TRACE("%p,%s,%p,%s\n", profilesKey, debugstr_w(szValueName), szValue,
1516      debugstr_w(szDefault));
1517     lRet = RegQueryValueExW(profilesKey, szValueName, NULL, &type,
1518      (LPBYTE)szValue, &dwPathLen);
1519     if (!lRet && (type == REG_SZ || type == REG_EXPAND_SZ) && dwPathLen
1520      && *szValue)
1521     {
1522         dwPathLen /= sizeof(WCHAR);
1523         szValue[dwPathLen] = '\0';
1524         hr = S_OK;
1525     }
1526     else
1527     {
1528         /* Missing or invalid value, set a default */
1529         lstrcpynW(szValue, szDefault, MAX_PATH);
1530         TRACE("Setting missing value %s to %s\n", debugstr_w(szValueName),
1531                                                   debugstr_w(szValue));
1532         lRet = RegSetValueExW(profilesKey, szValueName, 0, REG_EXPAND_SZ,
1533                               (LPBYTE)szValue,
1534                               (strlenW(szValue) + 1) * sizeof(WCHAR));
1535         if (lRet)
1536             hr = HRESULT_FROM_WIN32(lRet);
1537         else
1538             hr = S_OK;
1539     }
1540     TRACE("returning 0x%08x (output value is %s)\n", hr, debugstr_w(szValue));
1541     return hr;
1542 }
1543
1544 /* Attempts to expand environment variables from szSrc into szDest, which is
1545  * assumed to be MAX_PATH characters in length.  Before referring to the
1546  * environment, handles a few variables directly, because the environment
1547  * variables may not be set when this is called (as during Wine's installation
1548  * when default values are being written to the registry).
1549  * The directly handled environment variables, and their source, are:
1550  * - ALLUSERSPROFILE, USERPROFILE: reads from the registry
1551  * - SystemDrive: uses GetSystemDirectoryW and uses the drive portion of its
1552  *   path
1553  * If one of the directly handled environment variables is expanded, only
1554  * expands a single variable, and only in the beginning of szSrc.
1555  */
1556 static HRESULT _SHExpandEnvironmentStrings(LPCWSTR szSrc, LPWSTR szDest)
1557 {
1558     HRESULT hr;
1559     WCHAR szTemp[MAX_PATH], szProfilesPrefix[MAX_PATH] = { 0 };
1560     HKEY key = NULL;
1561
1562     TRACE("%s, %p\n", debugstr_w(szSrc), szDest);
1563
1564     if (!szSrc || !szDest) return E_INVALIDARG;
1565
1566     /* short-circuit if there's nothing to expand */
1567     if (szSrc[0] != '%')
1568     {
1569         strcpyW(szDest, szSrc);
1570         hr = S_OK;
1571         goto end;
1572     }
1573     /* Get the profile prefix, we'll probably be needing it */
1574     hr = _SHOpenProfilesKey(&key);
1575     if (SUCCEEDED(hr))
1576     {
1577         WCHAR szDefaultProfilesPrefix[MAX_PATH];
1578
1579         GetWindowsDirectoryW(szDefaultProfilesPrefix, MAX_PATH);
1580         PathAddBackslashW(szDefaultProfilesPrefix);
1581         PathAppendW(szDefaultProfilesPrefix, szDefaultProfileDirW);
1582         hr = _SHGetProfilesValue(key, ProfilesDirectoryW, szProfilesPrefix,
1583          szDefaultProfilesPrefix);
1584     }
1585
1586     *szDest = 0;
1587     strcpyW(szTemp, szSrc);
1588     while (SUCCEEDED(hr) && szTemp[0] == '%')
1589     {
1590         if (!strncmpiW(szTemp, AllUsersProfileW, strlenW(AllUsersProfileW)))
1591         {
1592             WCHAR szAllUsers[MAX_PATH];
1593
1594             strcpyW(szDest, szProfilesPrefix);
1595             hr = _SHGetProfilesValue(key, AllUsersProfileValueW,
1596              szAllUsers, AllUsersW);
1597             PathAppendW(szDest, szAllUsers);
1598             PathAppendW(szDest, szTemp + strlenW(AllUsersProfileW));
1599         }
1600         else if (!strncmpiW(szTemp, UserProfileW, strlenW(UserProfileW)))
1601         {
1602             WCHAR userName[MAX_PATH];
1603             DWORD userLen = MAX_PATH;
1604
1605             strcpyW(szDest, szProfilesPrefix);
1606             GetUserNameW(userName, &userLen);
1607             PathAppendW(szDest, userName);
1608             PathAppendW(szDest, szTemp + strlenW(UserProfileW));
1609         }
1610         else if (!strncmpiW(szTemp, SystemDriveW, strlenW(SystemDriveW)))
1611         {
1612             GetSystemDirectoryW(szDest, MAX_PATH);
1613             if (szDest[1] != ':')
1614             {
1615                 FIXME("non-drive system paths unsupported\n");
1616                 hr = E_FAIL;
1617             }
1618             else
1619             {
1620                 strcpyW(szDest + 3, szTemp + strlenW(SystemDriveW) + 1);
1621                 hr = S_OK;
1622             }
1623         }
1624         else
1625         {
1626             DWORD ret = ExpandEnvironmentStringsW(szSrc, szDest, MAX_PATH);
1627
1628             if (ret > MAX_PATH)
1629                 hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
1630             else if (ret == 0)
1631                 hr = HRESULT_FROM_WIN32(GetLastError());
1632             else
1633                 hr = S_OK;
1634         }
1635         if (SUCCEEDED(hr) && szDest[0] == '%')
1636             strcpyW(szTemp, szDest);
1637         else
1638         {
1639             /* terminate loop */
1640             szTemp[0] = '\0';
1641         }
1642     }
1643 end:
1644     if (key)
1645         RegCloseKey(key);
1646     TRACE("returning 0x%08x (input was %s, output is %s)\n", hr,
1647      debugstr_w(szSrc), debugstr_w(szDest));
1648     return hr;
1649 }
1650
1651 /*************************************************************************
1652  * SHGetFolderPathW                     [SHELL32.@]
1653  *
1654  * Convert nFolder to path.  
1655  *
1656  * RETURNS
1657  *  Success: S_OK
1658  *  Failure: standard HRESULT error codes.
1659  *
1660  * NOTES
1661  * Most values can be overridden in either
1662  * HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
1663  * or in the same location in HKLM.
1664  * The "Shell Folders" registry key was used in NT4 and earlier systems.
1665  * Beginning with Windows 2000, the "User Shell Folders" key is used, so
1666  * changes made to it are made to the former key too.  This synchronization is
1667  * done on-demand: not until someone requests the value of one of these paths
1668  * (by calling one of the SHGet functions) is the value synchronized.
1669  * Furthermore, the HKCU paths take precedence over the HKLM paths.
1670  */
1671 HRESULT WINAPI SHGetFolderPathW(
1672         HWND hwndOwner,    /* [I] owner window */
1673         int nFolder,       /* [I] CSIDL identifying the folder */
1674         HANDLE hToken,     /* [I] access token */
1675         DWORD dwFlags,     /* [I] which path to return */
1676         LPWSTR pszPath)    /* [O] converted path */
1677 {
1678     HRESULT    hr;
1679     WCHAR      szBuildPath[MAX_PATH], szTemp[MAX_PATH];
1680     DWORD      folder = nFolder & CSIDL_FOLDER_MASK;
1681     CSIDL_Type type;
1682     int        ret;
1683     
1684     TRACE("%p,%p,nFolder=0x%04x\n", hwndOwner,pszPath,nFolder);
1685
1686     /* Windows always NULL-terminates the resulting path regardless of success
1687      * or failure, so do so first
1688      */
1689     if (pszPath)
1690         *pszPath = '\0';
1691     if (folder >= sizeof(CSIDL_Data) / sizeof(CSIDL_Data[0]))
1692         return E_INVALIDARG;
1693     szTemp[0] = 0;
1694     type = CSIDL_Data[folder].type;
1695     switch (type)
1696     {
1697         case CSIDL_Type_Disallowed:
1698             hr = E_INVALIDARG;
1699             break;
1700         case CSIDL_Type_NonExistent:
1701             hr = S_FALSE;
1702             break;
1703         case CSIDL_Type_WindowsPath:
1704             GetWindowsDirectoryW(szTemp, MAX_PATH);
1705             if (CSIDL_Data[folder].szDefaultPath &&
1706              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
1707              *CSIDL_Data[folder].szDefaultPath)
1708             {
1709                 PathAddBackslashW(szTemp);
1710                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
1711             }
1712             hr = S_OK;
1713             break;
1714         case CSIDL_Type_SystemPath:
1715             GetSystemDirectoryW(szTemp, MAX_PATH);
1716             if (CSIDL_Data[folder].szDefaultPath &&
1717              !IS_INTRESOURCE(CSIDL_Data[folder].szDefaultPath) &&
1718              *CSIDL_Data[folder].szDefaultPath)
1719             {
1720                 PathAddBackslashW(szTemp);
1721                 strcatW(szTemp, CSIDL_Data[folder].szDefaultPath);
1722             }
1723             hr = S_OK;
1724             break;
1725         case CSIDL_Type_CurrVer:
1726             hr = _SHGetCurrentVersionPath(dwFlags, folder, szTemp);
1727             break;
1728         case CSIDL_Type_User:
1729             hr = _SHGetUserProfilePath(hToken, dwFlags, folder, szTemp);
1730             break;
1731         case CSIDL_Type_AllUsers:
1732             hr = _SHGetAllUsersProfilePath(dwFlags, folder, szTemp);
1733             break;
1734         default:
1735             FIXME("bogus type %d, please fix\n", type);
1736             hr = E_INVALIDARG;
1737             break;
1738     }
1739
1740     /* Expand environment strings if necessary */
1741     if (*szTemp == '%')
1742         hr = _SHExpandEnvironmentStrings(szTemp, szBuildPath);
1743     else
1744         strcpyW(szBuildPath, szTemp);
1745     /* Copy the path if it's available before we might return */
1746     if (SUCCEEDED(hr) && pszPath)
1747         strcpyW(pszPath, szBuildPath);
1748
1749     if (FAILED(hr)) goto end;
1750
1751     /* if we don't care about existing directories we are ready */
1752     if(nFolder & CSIDL_FLAG_DONT_VERIFY) goto end;
1753
1754     if (PathFileExistsW(szBuildPath)) goto end;
1755
1756     /* not existing but we are not allowed to create it.  The return value
1757      * is verified against shell32 version 6.0.
1758      */
1759     if (!(nFolder & CSIDL_FLAG_CREATE))
1760     {
1761         hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
1762         goto end;
1763     }
1764
1765     /* create directory/directories */
1766     ret = SHCreateDirectoryExW(hwndOwner, szBuildPath, NULL);
1767     if (ret && ret != ERROR_ALREADY_EXISTS)
1768     {
1769         ERR("Failed to create directory %s.\n", debugstr_w(szBuildPath));
1770         hr = E_FAIL;
1771         goto end;
1772     }
1773
1774     TRACE("Created missing system directory %s\n", debugstr_w(szBuildPath));
1775 end:
1776     TRACE("returning 0x%08x (final path is %s)\n", hr, debugstr_w(szBuildPath));
1777     return hr;
1778 }
1779
1780 /*************************************************************************
1781  * SHGetFolderPathA                     [SHELL32.@]
1782  *
1783  * See SHGetFolderPathW.
1784  */
1785 HRESULT WINAPI SHGetFolderPathA(
1786         HWND hwndOwner,
1787         int nFolder,
1788         HANDLE hToken,
1789         DWORD dwFlags,
1790         LPSTR pszPath)
1791 {
1792     WCHAR szTemp[MAX_PATH];
1793     HRESULT hr;
1794
1795     TRACE("%p,%p,nFolder=0x%04x\n",hwndOwner,pszPath,nFolder);
1796
1797     if (pszPath)
1798         *pszPath = '\0';
1799     hr = SHGetFolderPathW(hwndOwner, nFolder, hToken, dwFlags, szTemp);
1800     if (SUCCEEDED(hr) && pszPath)
1801         WideCharToMultiByte(CP_ACP, 0, szTemp, -1, pszPath, MAX_PATH, NULL,
1802          NULL);
1803
1804     return hr;
1805 }
1806
1807 /* For each folder in folders, if its value has not been set in the registry,
1808  * calls _SHGetUserProfilePath or _SHGetAllUsersProfilePath (depending on the
1809  * folder's type) to get the unexpanded value first.
1810  * Writes the unexpanded value to User Shell Folders, and queries it with
1811  * SHGetFolderPathW to force the creation of the directory if it doesn't
1812  * already exist.  SHGetFolderPathW also returns the expanded value, which
1813  * this then writes to Shell Folders.
1814  */
1815 static HRESULT _SHRegisterFolders(HKEY hRootKey, HANDLE hToken,
1816  LPCWSTR szUserShellFolderPath, LPCWSTR szShellFolderPath, const UINT folders[],
1817  UINT foldersLen)
1818 {
1819     UINT i;
1820     WCHAR path[MAX_PATH];
1821     HRESULT hr = S_OK;
1822     HKEY hUserKey = NULL, hKey = NULL;
1823     DWORD dwType, dwPathLen;
1824     LONG ret;
1825
1826     TRACE("%p,%p,%s,%p,%u\n", hRootKey, hToken,
1827      debugstr_w(szUserShellFolderPath), folders, foldersLen);
1828
1829     ret = RegCreateKeyW(hRootKey, szUserShellFolderPath, &hUserKey);
1830     if (ret)
1831         hr = HRESULT_FROM_WIN32(ret);
1832     else
1833     {
1834         ret = RegCreateKeyW(hRootKey, szShellFolderPath, &hKey);
1835         if (ret)
1836             hr = HRESULT_FROM_WIN32(ret);
1837     }
1838     for (i = 0; SUCCEEDED(hr) && i < foldersLen; i++)
1839     {
1840         dwPathLen = MAX_PATH * sizeof(WCHAR);
1841         if (RegQueryValueExW(hUserKey, CSIDL_Data[folders[i]].szValueName, NULL,
1842          &dwType, (LPBYTE)path, &dwPathLen) || (dwType != REG_SZ &&
1843          dwType != REG_EXPAND_SZ))
1844         {
1845             *path = '\0';
1846             if (CSIDL_Data[folders[i]].type == CSIDL_Type_User)
1847                 _SHGetUserProfilePath(hToken, SHGFP_TYPE_DEFAULT, folders[i],
1848                  path);
1849             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_AllUsers)
1850                 _SHGetAllUsersProfilePath(SHGFP_TYPE_DEFAULT, folders[i], path);
1851             else if (CSIDL_Data[folders[i]].type == CSIDL_Type_WindowsPath)
1852                 GetWindowsDirectoryW(path, MAX_PATH);
1853             else
1854                 hr = E_FAIL;
1855             if (*path)
1856             {
1857                 ret = RegSetValueExW(hUserKey,
1858                  CSIDL_Data[folders[i]].szValueName, 0, REG_EXPAND_SZ,
1859                  (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
1860                 if (ret)
1861                     hr = HRESULT_FROM_WIN32(ret);
1862                 else
1863                 {
1864                     hr = SHGetFolderPathW(NULL, folders[i] | CSIDL_FLAG_CREATE,
1865                      hToken, SHGFP_TYPE_DEFAULT, path);
1866                     ret = RegSetValueExW(hKey,
1867                      CSIDL_Data[folders[i]].szValueName, 0, REG_SZ,
1868                      (LPBYTE)path, (strlenW(path) + 1) * sizeof(WCHAR));
1869                     if (ret)
1870                         hr = HRESULT_FROM_WIN32(ret);
1871                 }
1872             }
1873         }
1874     }
1875     if (hUserKey)
1876         RegCloseKey(hUserKey);
1877     if (hKey)
1878         RegCloseKey(hKey);
1879
1880     TRACE("returning 0x%08x\n", hr);
1881     return hr;
1882 }
1883
1884 static HRESULT _SHRegisterUserShellFolders(BOOL bDefault)
1885 {
1886     static const UINT folders[] = {
1887      CSIDL_PROGRAMS,
1888      CSIDL_PERSONAL,
1889      CSIDL_FAVORITES,
1890      CSIDL_APPDATA,
1891      CSIDL_STARTUP,
1892      CSIDL_RECENT,
1893      CSIDL_SENDTO,
1894      CSIDL_STARTMENU,
1895      CSIDL_MYMUSIC,
1896      CSIDL_MYVIDEO,
1897      CSIDL_DESKTOPDIRECTORY,
1898      CSIDL_NETHOOD,
1899      CSIDL_TEMPLATES,
1900      CSIDL_PRINTHOOD,
1901      CSIDL_LOCAL_APPDATA,
1902      CSIDL_INTERNET_CACHE,
1903      CSIDL_COOKIES,
1904      CSIDL_HISTORY,
1905      CSIDL_MYPICTURES,
1906      CSIDL_FONTS
1907     };
1908     WCHAR userShellFolderPath[MAX_PATH], shellFolderPath[MAX_PATH];
1909     LPCWSTR pUserShellFolderPath, pShellFolderPath;
1910     HRESULT hr = S_OK;
1911     HKEY hRootKey;
1912     HANDLE hToken;
1913
1914     TRACE("%s\n", bDefault ? "TRUE" : "FALSE");
1915     if (bDefault)
1916     {
1917         hToken = (HANDLE)-1;
1918         hRootKey = HKEY_USERS;
1919         strcpyW(userShellFolderPath, DefaultW);
1920         PathAddBackslashW(userShellFolderPath);
1921         strcatW(userShellFolderPath, szSHUserFolders);
1922         pUserShellFolderPath = userShellFolderPath;
1923         strcpyW(shellFolderPath, DefaultW);
1924         PathAddBackslashW(shellFolderPath);
1925         strcatW(shellFolderPath, szSHFolders);
1926         pShellFolderPath = shellFolderPath;
1927     }
1928     else
1929     {
1930         hToken = NULL;
1931         hRootKey = HKEY_CURRENT_USER;
1932         pUserShellFolderPath = szSHUserFolders;
1933         pShellFolderPath = szSHFolders;
1934     }
1935
1936     hr = _SHRegisterFolders(hRootKey, hToken, pUserShellFolderPath,
1937      pShellFolderPath, folders, sizeof(folders) / sizeof(folders[0]));
1938     TRACE("returning 0x%08x\n", hr);
1939     return hr;
1940 }
1941
1942 static HRESULT _SHRegisterCommonShellFolders(void)
1943 {
1944     static const UINT folders[] = {
1945      CSIDL_COMMON_STARTMENU,
1946      CSIDL_COMMON_PROGRAMS,
1947      CSIDL_COMMON_STARTUP,
1948      CSIDL_COMMON_DESKTOPDIRECTORY,
1949      CSIDL_COMMON_FAVORITES,
1950      CSIDL_COMMON_APPDATA,
1951      CSIDL_COMMON_TEMPLATES,
1952      CSIDL_COMMON_DOCUMENTS,
1953     };
1954     HRESULT hr;
1955
1956     TRACE("\n");
1957     hr = _SHRegisterFolders(HKEY_LOCAL_MACHINE, NULL, szSHUserFolders,
1958      szSHFolders, folders, sizeof(folders) / sizeof(folders[0]));
1959     TRACE("returning 0x%08x\n", hr);
1960     return hr;
1961 }
1962
1963 /******************************************************************************
1964  * _SHAppendToUnixPath  [Internal]
1965  *
1966  * Helper function for _SHCreateSymbolicLinks. Appends pwszSubPath (or the 
1967  * corresponding resource, if IS_INTRESOURCE) to the unix base path 'szBasePath' 
1968  * and replaces backslashes with slashes.
1969  *
1970  * PARAMS
1971  *  szBasePath  [IO] The unix base path, which will be appended to (CP_UNXICP).
1972  *  pwszSubPath [I]  Sub-path or resource id (use MAKEINTRESOURCEW).
1973  *
1974  * RETURNS
1975  *  Success: TRUE,
1976  *  Failure: FALSE
1977  */
1978 static inline BOOL _SHAppendToUnixPath(char *szBasePath, LPCWSTR pwszSubPath) {
1979     WCHAR wszSubPath[MAX_PATH];
1980     int cLen = strlen(szBasePath);
1981     char *pBackslash;
1982
1983     if (IS_INTRESOURCE(pwszSubPath)) {
1984         if (!LoadStringW(shell32_hInstance, LOWORD(pwszSubPath), wszSubPath, MAX_PATH)) {
1985             /* Fall back to hard coded defaults. */
1986             switch (LOWORD(pwszSubPath)) {
1987                 case IDS_PERSONAL:
1988                     lstrcpyW(wszSubPath, PersonalW);
1989                     break;
1990                 case IDS_MYMUSIC:
1991                     lstrcpyW(wszSubPath, My_MusicW);
1992                     break;
1993                 case IDS_MYPICTURES:
1994                     lstrcpyW(wszSubPath, My_PicturesW);
1995                     break;
1996                 case IDS_MYVIDEO:
1997                     lstrcpyW(wszSubPath, My_VideoW);
1998                     break;
1999                 default:
2000                     ERR("LoadString(%d) failed!\n", LOWORD(pwszSubPath));
2001                     return FALSE;
2002             }
2003         }
2004     } else {
2005         lstrcpyW(wszSubPath, pwszSubPath);
2006     }
2007  
2008     if (szBasePath[cLen-1] != '/') szBasePath[cLen++] = '/';
2009  
2010     if (!WideCharToMultiByte(CP_UNIXCP, 0, wszSubPath, -1, szBasePath + cLen,
2011                              FILENAME_MAX - cLen, NULL, NULL))
2012     {
2013         return FALSE;
2014     }
2015  
2016     pBackslash = szBasePath + cLen;
2017     while ((pBackslash = strchr(pBackslash, '\\'))) *pBackslash = '/';
2018  
2019     return TRUE;
2020 }
2021
2022 /******************************************************************************
2023  * _SHCreateSymbolicLinks  [Internal]
2024  * 
2025  * Sets up symbol links for various shell folders to point into the users home
2026  * directory. We do an educated guess about what the user would probably want:
2027  * - If there is a 'My Documents' directory in $HOME, the user probably wants
2028  *   wine's 'My Documents' to point there. Furthermore, we imply that the user
2029  *   is a Windows lover and has no problem with wine creating 'My Pictures',
2030  *   'My Music' and 'My Video' subfolders under '$HOME/My Documents', if those
2031  *   do not already exits. We put appropriate symbolic links in place for those,
2032  *   too.
2033  * - If there is no 'My Documents' directory in $HOME, we let 'My Documents'
2034  *   point directly to $HOME. We assume the user to be a unix hacker who does not
2035  *   want wine to create anything anywhere besides the .wine directory. So, if
2036  *   there already is a 'My Music' directory in $HOME, we symlink the 'My Music'
2037  *   shell folder to it. But if not, then we check XDG_MUSIC_DIR - "well known"
2038  *   directory, and try to link to that. If that fails, then we symlink to
2039  *   $HOME directly. The same holds fo 'My Pictures' and 'My Video'.
2040  * - The Desktop shell folder is symlinked to XDG_DESKTOP_DIR. If that does not
2041  *   exist, then we try '$HOME/Desktop'. If that does not exist, then we leave
2042  *   it alone.
2043  * ('My Music',... above in fact means LoadString(IDS_MYMUSIC))
2044  */
2045 static void _SHCreateSymbolicLinks(void)
2046 {
2047     UINT aidsMyStuff[] = { IDS_MYPICTURES, IDS_MYVIDEO, IDS_MYMUSIC }, i;
2048     int acsidlMyStuff[] = { CSIDL_MYPICTURES, CSIDL_MYVIDEO, CSIDL_MYMUSIC };
2049     static const char * xdg_dirs[] = { "PICTURES", "VIDEOS", "MUSIC", "DESKTOP" };
2050     WCHAR wszTempPath[MAX_PATH];
2051     char szPersonalTarget[FILENAME_MAX], *pszPersonal;
2052     char szMyStuffTarget[FILENAME_MAX], *pszMyStuff;
2053     char szDesktopTarget[FILENAME_MAX], *pszDesktop;
2054     struct stat statFolder;
2055     const char *pszHome;
2056     HRESULT hr;
2057     const unsigned int num = sizeof(xdg_dirs) / sizeof(xdg_dirs[0]);
2058     char ** xdg_results = NULL;
2059     char * xdg_desktop_dir;
2060
2061     /* Create all necessary profile sub-dirs up to 'My Documents' and get the unix path. */
2062     hr = SHGetFolderPathW(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL,
2063                           SHGFP_TYPE_DEFAULT, wszTempPath);
2064     if (FAILED(hr)) return;
2065     pszPersonal = wine_get_unix_file_name(wszTempPath);
2066     if (!pszPersonal) return;
2067
2068     XDG_UserDirLookup(xdg_dirs, num, &xdg_results);
2069
2070     pszHome = getenv("HOME");
2071     if (pszHome && !stat(pszHome, &statFolder) && S_ISDIR(statFolder.st_mode)) {
2072         strcpy(szPersonalTarget, pszHome);
2073         if (_SHAppendToUnixPath(szPersonalTarget, MAKEINTRESOURCEW(IDS_PERSONAL)) &&
2074             !stat(szPersonalTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2075         {
2076             /* '$HOME/My Documents' exists. Create 'My Pictures', 'My Videos' and 
2077              * 'My Music' subfolders or fail silently if they already exist. */
2078             for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2079                 strcpy(szMyStuffTarget, szPersonalTarget);
2080                 if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2081                     mkdir(szMyStuffTarget, 0777);
2082             }
2083         } 
2084         else
2085         {
2086             /* '$HOME/My Documents' doesn't exists, but '$HOME' does. */ 
2087             strcpy(szPersonalTarget, pszHome);
2088         }
2089
2090         /* Replace 'My Documents' directory with a symlink of fail silently if not empty. */
2091         rmdir(pszPersonal);
2092         symlink(szPersonalTarget, pszPersonal);
2093     }
2094     else
2095     {
2096         /* '$HOME' doesn't exist. Create 'My Pictures', 'My Videos' and 'My Music' subdirs
2097          * in '%USERPROFILE%\\My Documents' or fail silently if they already exist. */
2098         strcpy(szPersonalTarget, pszPersonal);
2099         for (i = 0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2100             strcpy(szMyStuffTarget, szPersonalTarget);
2101             if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])))
2102                 mkdir(szMyStuffTarget, 0777);
2103         }
2104     }
2105
2106     /* Create symbolic links for 'My Pictures', 'My Video' and 'My Music'. */
2107     for (i=0; i < sizeof(aidsMyStuff)/sizeof(aidsMyStuff[0]); i++) {
2108         /* Create the current 'My Whatever' folder and get it's unix path. */
2109         hr = SHGetFolderPathW(NULL, acsidlMyStuff[i]|CSIDL_FLAG_CREATE, NULL,
2110                               SHGFP_TYPE_DEFAULT, wszTempPath);
2111         if (FAILED(hr)) continue;
2112         pszMyStuff = wine_get_unix_file_name(wszTempPath);
2113         if (!pszMyStuff) continue;
2114         
2115         strcpy(szMyStuffTarget, szPersonalTarget);
2116         if (_SHAppendToUnixPath(szMyStuffTarget, MAKEINTRESOURCEW(aidsMyStuff[i])) &&
2117             !stat(szMyStuffTarget, &statFolder) && S_ISDIR(statFolder.st_mode))
2118         {
2119             /* If there's a 'My Whatever' directory where 'My Documents' links to, link to it. */
2120             rmdir(pszMyStuff);
2121             symlink(szMyStuffTarget, pszMyStuff);
2122         } 
2123         else
2124         {
2125             rmdir(pszMyStuff);
2126             if (xdg_results && xdg_results[i])
2127             {
2128                 /* the folder specified by XDG_XXX_DIR exists, link to it. */
2129                 symlink(xdg_results[i], pszMyStuff);
2130             }
2131             else
2132             {
2133                 /* Else link to where 'My Documents' itself links to. */
2134                 symlink(szPersonalTarget, pszMyStuff);
2135             }
2136         }
2137         HeapFree(GetProcessHeap(), 0, pszMyStuff);
2138     }
2139
2140     /* Last but not least, the Desktop folder */
2141     if (pszHome)
2142         strcpy(szDesktopTarget, pszHome);
2143     else
2144         strcpy(szDesktopTarget, pszPersonal);
2145     HeapFree(GetProcessHeap(), 0, pszPersonal);
2146
2147     xdg_desktop_dir = xdg_results ? xdg_results[num - 1] : NULL;
2148     if (xdg_desktop_dir ||
2149         (_SHAppendToUnixPath(szDesktopTarget, DesktopW) &&
2150         !stat(szDesktopTarget, &statFolder) && S_ISDIR(statFolder.st_mode)))
2151     {
2152         hr = SHGetFolderPathW(NULL, CSIDL_DESKTOPDIRECTORY|CSIDL_FLAG_CREATE, NULL,
2153                               SHGFP_TYPE_DEFAULT, wszTempPath);
2154         if (SUCCEEDED(hr) && (pszDesktop = wine_get_unix_file_name(wszTempPath))) 
2155         {
2156             rmdir(pszDesktop);
2157             if (xdg_desktop_dir)
2158                 symlink(xdg_desktop_dir, pszDesktop);
2159             else
2160                 symlink(szDesktopTarget, pszDesktop);
2161             HeapFree(GetProcessHeap(), 0, pszDesktop);
2162         }
2163     }
2164
2165     /* Free resources allocated by XDG_UserDirLookup() */
2166     if (xdg_results)
2167     {
2168         for (i = 0; i < num; i++)
2169             HeapFree(GetProcessHeap(), 0, xdg_results[i]);
2170         HeapFree(GetProcessHeap(), 0, xdg_results);
2171     }
2172 }
2173
2174 /* Register the default values in the registry, as some apps seem to depend
2175  * on their presence.  The set registered was taken from Windows XP.
2176  */
2177 HRESULT SHELL_RegisterShellFolders(void)
2178 {
2179     HRESULT hr;
2180
2181     /* Set up '$HOME' targeted symlinks for 'My Documents', 'My Pictures',
2182      * 'My Video', 'My Music' and 'Desktop' in advance, so that the
2183      * _SHRegister*ShellFolders() functions will find everything nice and clean
2184      * and thus will not attempt to create them in the profile directory. */
2185     _SHCreateSymbolicLinks();
2186     
2187     hr = _SHRegisterUserShellFolders(TRUE);
2188     if (SUCCEEDED(hr))
2189         hr = _SHRegisterUserShellFolders(FALSE);
2190     if (SUCCEEDED(hr))
2191         hr = _SHRegisterCommonShellFolders();
2192     return hr;
2193 }
2194
2195 /*************************************************************************
2196  * SHGetSpecialFolderPathA [SHELL32.@]
2197  */
2198 BOOL WINAPI SHGetSpecialFolderPathA (
2199         HWND hwndOwner,
2200         LPSTR szPath,
2201         int nFolder,
2202         BOOL bCreate)
2203 {
2204         return (SHGetFolderPathA(
2205                 hwndOwner,
2206                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2207                 NULL,
2208                 0,
2209                 szPath)) == S_OK ? TRUE : FALSE;
2210 }
2211
2212 /*************************************************************************
2213  * SHGetSpecialFolderPathW
2214  */
2215 BOOL WINAPI SHGetSpecialFolderPathW (
2216         HWND hwndOwner,
2217         LPWSTR szPath,
2218         int nFolder,
2219         BOOL bCreate)
2220 {
2221         return (SHGetFolderPathW(
2222                 hwndOwner,
2223                 nFolder + (bCreate ? CSIDL_FLAG_CREATE : 0),
2224                 NULL,
2225                 0,
2226                 szPath)) == S_OK ? TRUE : FALSE;
2227 }
2228
2229 /*************************************************************************
2230  * SHGetSpecialFolderPath (SHELL32.175)
2231  */
2232 BOOL WINAPI SHGetSpecialFolderPathAW (
2233         HWND hwndOwner,
2234         LPVOID szPath,
2235         int nFolder,
2236         BOOL bCreate)
2237
2238 {
2239         if (SHELL_OsIsUnicode())
2240           return SHGetSpecialFolderPathW (hwndOwner, szPath, nFolder, bCreate);
2241         return SHGetSpecialFolderPathA (hwndOwner, szPath, nFolder, bCreate);
2242 }
2243
2244 /*************************************************************************
2245  * SHGetFolderLocation [SHELL32.@]
2246  *
2247  * Gets the folder locations from the registry and creates a pidl.
2248  *
2249  * PARAMS
2250  *   hwndOwner  [I]
2251  *   nFolder    [I] CSIDL_xxxxx
2252  *   hToken     [I] token representing user, or NULL for current user, or -1 for
2253  *                  default user
2254  *   dwReserved [I] must be zero
2255  *   ppidl      [O] PIDL of a special folder
2256  *
2257  * RETURNS
2258  *  Success: S_OK
2259  *  Failure: Standard OLE-defined error result, S_FALSE or E_INVALIDARG
2260  *
2261  * NOTES
2262  *  Creates missing reg keys and directories.
2263  *  Mostly forwards to SHGetFolderPathW, but a few values of nFolder return
2264  *  virtual folders that are handled here.
2265  */
2266 HRESULT WINAPI SHGetFolderLocation(
2267         HWND hwndOwner,
2268         int nFolder,
2269         HANDLE hToken,
2270         DWORD dwReserved,
2271         LPITEMIDLIST *ppidl)
2272 {
2273     HRESULT hr = E_INVALIDARG;
2274
2275     TRACE("%p 0x%08x %p 0x%08x %p\n",
2276      hwndOwner, nFolder, hToken, dwReserved, ppidl);
2277     
2278     if (!ppidl)
2279         return E_INVALIDARG;
2280     if (dwReserved)
2281         return E_INVALIDARG;
2282
2283     /* The virtual folders' locations are not user-dependent */
2284     *ppidl = NULL;
2285     switch (nFolder)
2286     {
2287         case CSIDL_DESKTOP:
2288             *ppidl = _ILCreateDesktop();
2289             break;
2290
2291         case CSIDL_PERSONAL:
2292             *ppidl = _ILCreateMyDocuments();
2293             break;
2294
2295         case CSIDL_INTERNET:
2296             *ppidl = _ILCreateIExplore();
2297             break;
2298
2299         case CSIDL_CONTROLS:
2300             *ppidl = _ILCreateControlPanel();
2301             break;
2302
2303         case CSIDL_PRINTERS:
2304             *ppidl = _ILCreatePrinters();
2305             break;
2306
2307         case CSIDL_BITBUCKET:
2308             *ppidl = _ILCreateBitBucket();
2309             break;
2310
2311         case CSIDL_DRIVES:
2312             *ppidl = _ILCreateMyComputer();
2313             break;
2314
2315         case CSIDL_NETWORK:
2316             *ppidl = _ILCreateNetwork();
2317             break;
2318
2319         default:
2320         {
2321             WCHAR szPath[MAX_PATH];
2322
2323             hr = SHGetFolderPathW(hwndOwner, nFolder, hToken,
2324              SHGFP_TYPE_CURRENT, szPath);
2325             if (SUCCEEDED(hr))
2326             {
2327                 DWORD attributes=0;
2328
2329                 TRACE("Value=%s\n", debugstr_w(szPath));
2330                 hr = SHILCreateFromPathW(szPath, ppidl, &attributes);
2331             }
2332             else if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
2333             {
2334                 /* unlike SHGetFolderPath, SHGetFolderLocation in shell32
2335                  * version 6.0 returns E_FAIL for nonexistent paths
2336                  */
2337                 hr = E_FAIL;
2338             }
2339         }
2340     }
2341     if(*ppidl)
2342         hr = NOERROR;
2343
2344     TRACE("-- (new pidl %p)\n",*ppidl);
2345     return hr;
2346 }
2347
2348 /*************************************************************************
2349  * SHGetSpecialFolderLocation           [SHELL32.@]
2350  *
2351  * NOTES
2352  *   In NT5, SHGetSpecialFolderLocation needs the <winntdir>/Recent
2353  *   directory.
2354  */
2355 HRESULT WINAPI SHGetSpecialFolderLocation(
2356         HWND hwndOwner,
2357         INT nFolder,
2358         LPITEMIDLIST * ppidl)
2359 {
2360     HRESULT hr = E_INVALIDARG;
2361
2362     TRACE("(%p,0x%x,%p)\n", hwndOwner,nFolder,ppidl);
2363
2364     if (!ppidl)
2365         return E_INVALIDARG;
2366
2367     hr = SHGetFolderLocation(hwndOwner, nFolder, NULL, 0, ppidl);
2368     return hr;
2369 }