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