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