Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2040 lines
66 KiB

  1. //
  2. // IMPEXP.CPP - Browser Import and Export Code
  3. //
  4. // Imports and Exports Favorites in various formats
  5. //
  6. // julianj 2/16/98
  7. //
  8. //
  9. // *** IMPORT FAVORITES CODE ***
  10. //
  11. /************************************************************\
  12. FILE: impext.cpp
  13. DATE: April 1, 1996
  14. AUTHOR(S): Bryan Starbuck (bryanst)
  15. DESCRIPTION:
  16. This file contains functions that can be used to upgrade
  17. settings from the Microsoft Internet Explorer v2.0 to v3.0,
  18. and some features to import Netscape features into Internet
  19. Explorer.
  20. This file will handle the logic to convert Netscape
  21. bookmarks to Microsoft Internet Explorer favorites. This
  22. will happen by finding the location of the Netscape bookmarks
  23. file and the Microsoft Internet Explorer favorites directory
  24. from the registry. Then it will parse the bookmarks file to
  25. extract the URLs, which will finally be added to the favorites
  26. directory.
  27. USAGE:
  28. This code is designed to be called when the user may
  29. want Netscape bookmarks imported into system level Favorites
  30. usable by programs such as Internet Explorer. External
  31. users should call ImportBookmarks(). If this is done during
  32. setup, it should be done after setup specifies the Favorites
  33. registry entry and directory. If Netscape is not installed,
  34. then the ImportBookmarks() is just a big no-op.
  35. NOTE:
  36. If this file is being compiled into something other
  37. than infnist.exe, it will be necessary to include the
  38. following String Resource:
  39. #define IDS_NS_BOOKMARKS_DIR 137
  40. STRINGTABLE DISCARDABLE
  41. BEGIN
  42. ...
  43. IDS_NS_BOOKMARKS_DIR "\\Imported Bookmarks"
  44. END
  45. UPDATES: I adopted this file to allow IE4.0 having the abilities
  46. to upgrade from NetScape's setting. Two CustomActions will be added
  47. to call in functions in this file. (inateeg)
  48. 8/14/98: added functions to import or export via an URL,
  49. 8/19/98: added UI to allow user to import/export via browser's File
  50. menu/"Import and Exporting..."
  51. \************************************************************/
  52. #include "priv.h"
  53. #include "impexp.h"
  54. #include <regstr.h>
  55. #include "resource.h"
  56. #include <mluisupp.h>
  57. //
  58. // Information about the Netscape Bookmark file format that is shared between
  59. // the import and export code
  60. //
  61. #define BEGIN_DIR_TOKEN "<DT><H"
  62. #ifdef UNIX
  63. #define MID_DIR_TOKEN0 "3>"
  64. #endif
  65. #define MID_DIR_TOKEN "\">"
  66. #define END_DIR_TOKEN "</H"
  67. #define BEGIN_EXITDIR_TOKEN "</DL><p>"
  68. #define BEGIN_URL_TOKEN "<DT><A HREF=\""
  69. #define END_URL_TOKEN "\" A"
  70. #ifdef UNIX
  71. #define END_URL_TOKEN2 "\">"
  72. #endif
  73. #define BEGIN_BOOKMARK_TOKEN ">"
  74. #define END_BOOKMARK_TOKEN "</A>"
  75. #define VALIDATION_STR "<!DOCTYPE NETSCAPE-Bookmark-file-"
  76. //
  77. // Use by export code
  78. //
  79. #define COMMENT_STR "<!-- This is an automatically generated file.\r\nIt will be read and overwritten.\r\nDo Not Edit! -->"
  80. #define TITLE "<TITLE>Bookmarks</TITLE>\r\n<H1>Bookmarks</H1>"
  81. // ItemType is going to be the type of entry found in the bookmarks
  82. // file.
  83. typedef enum MYENTRYTYPE
  84. {
  85. ET_OPEN_DIR = 531, // New level in heirarchy
  86. ET_CLOSE_DIR, // Close level in heirarchy
  87. ET_BOOKMARK, // Bookmark entry.
  88. ET_NONE, // End of File
  89. ET_ERROR // Bail, we encountered an error
  90. } MyEntryType;
  91. //////////////////////////////////////////////////////////////////
  92. // Internal Functions
  93. //////////////////////////////////////////////////////////////////
  94. BOOL ImportNetscapeProxy(void); // Import Netscape Proxy Setting
  95. BOOL UpdateHomePage(void); // Upgrade IE v1.0 Home URL to v3.0
  96. BOOL ImportBookmarks(TCHAR *pszPathToFavorites, TCHAR *pszPathToBookmarks, HWND hwnd); // Import Netscape Bookmarks to IE Favorites
  97. BOOL ExportFavorites(TCHAR *pszPathToFavorites, TCHAR *pszPathToBookmarks, HWND hwnd); // Export IE Favorites to Netscape Bookmarks
  98. BOOL RegStrValueEmpty(HKEY hTheKey, char * szPath, char * szKey);
  99. BOOL GetNSProxyValue(char * szProxyValue, DWORD * pdwSize);
  100. BOOL VerifyBookmarksFile(HANDLE hFile);
  101. BOOL ConvertBookmarks(TCHAR * szFavoritesDir, HANDLE hFile);
  102. MyEntryType NextFileEntry(char ** ppStr, char ** ppToken);
  103. BOOL GetData(char ** ppData, HANDLE hFile);
  104. void RemoveInvalidFileNameChars(char * pBuf);
  105. BOOL CreateDir(char *pDirName);
  106. BOOL CloseDir(void);
  107. BOOL CreateBookmark(char *pBookmarkName);
  108. BOOL GetPathFromRegistry(LPTSTR szPath, UINT cbPath, HKEY theHKEY, LPTSTR szKey, LPTSTR szVName);
  109. BOOL GetNavBkMkDir( LPTSTR lpszDir, int isize);
  110. BOOL GetTargetFavoritesPath(LPTSTR szPath, UINT cbPath);
  111. BOOL PostFavorites(TCHAR *pszPathToBookmarks, TCHAR* pszPathToPost);
  112. void CALLBACK StatusCallback(HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwStatus,
  113. LPVOID lpvInfo, DWORD dwInfoLength);
  114. //////////////////////////////////////////////////////////////////
  115. // TYPES:
  116. //////////////////////////////////////////////////////////////////
  117. //typedef enum MYENTRYTYPE MyEntryType;
  118. //////////////////////////////////////////////////////////////////
  119. // Constants:
  120. //////////////////////////////////////////////////////////////////
  121. #define MAX_URL 2048
  122. #define FILE_EXT 4 // For ".url" at the end of favorite filenames
  123. #define REASONABLE_NAME_LEN 100
  124. #define ANSIStrStr(p, q) StrStrIA(p, q)
  125. #define ANSIStrChr(p, q) StrChrIA(p, q)
  126. //////////////////////////////////////////////////////////////////
  127. // GLOBALS:
  128. //////////////////////////////////////////////////////////////////
  129. #ifndef UNIX
  130. TCHAR * szNetscapeBMRegSub = TEXT("SOFTWARE\\Netscape\\Netscape Navigator\\Bookmark List");
  131. #else
  132. TCHAR * szNetscapeBMRegSub = TEXT("SOFTWARE\\Microsoft\\Internet Explorer\\unix\\nsbookmarks");
  133. #endif
  134. TCHAR * szNetscapeBMRegKey = TEXT("File Location");
  135. TCHAR * szIEFavoritesRegSub = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
  136. TCHAR * szIEFavoritesRegKey = TEXT("Favorites");
  137. char * szInvalidFolderCharacters = "\\/:*?\"<>|";
  138. BOOL gfValidNetscapeFile = FALSE;
  139. BOOL gfValidIEDirFile = FALSE;
  140. // Returns the location of the favorites folder in which to import the netscape favorites
  141. BOOL GetTargetFavoritesPath(LPTSTR szPath, UINT cbPath)
  142. {
  143. if (GetPathFromRegistry(szPath, cbPath, HKEY_CURRENT_USER, szIEFavoritesRegSub, szIEFavoritesRegKey))
  144. {
  145. //MLLoadString(IDS_NS_BOOKMARKS_DIR, szSubDir, sizeof(szSubDir))
  146. //lstrcat(szPath, "\\Imported Netscape Favorites");
  147. return TRUE;
  148. }
  149. return FALSE;
  150. }
  151. ///////////////////////////////////////////////////////
  152. // Import Netscape Bookmarks to Microsoft
  153. // Internet Explorer's Favorites
  154. ///////////////////////////////////////////////////////
  155. /************************************************************\
  156. FUNCTION: ImportBookmarks
  157. PARAMETERS:
  158. HINSTANCE hInstWithStr - Location of String Resources.
  159. BOOL return - If an error occurs importing the bookmarks, FALSE is returned.
  160. DESCRIPTION:
  161. This function will see if it can find a IE Favorite's
  162. registry entry and a Netscape bookmarks registry entry. If
  163. both are found, then the conversion can happen. It will
  164. attempt to open the verify that the bookmarks file is
  165. valid and then convert the entries to favorite entries.
  166. If an error occures, ImportBookmarks() will return FALSE,
  167. otherwise it will return TRUE.
  168. \*************************************************************/
  169. BOOL ImportBookmarks(TCHAR *pszPathToFavorites, TCHAR *pszPathToBookmarks, HWND hwnd)
  170. {
  171. HANDLE hBookmarksFile = INVALID_HANDLE_VALUE;
  172. BOOL fSuccess = FALSE;
  173. // Prompt the user to insert floppy, format floppy or drive, remount mapped partition,
  174. // or any create sub directories so pszPathToBookmarks becomes valid.
  175. if (FAILED(SHPathPrepareForWriteWrap(hwnd, NULL, pszPathToBookmarks, FO_COPY, (SHPPFW_DEFAULT | SHPPFW_IGNOREFILENAME))))
  176. return FALSE;
  177. if (pszPathToFavorites==NULL || *pszPathToFavorites == TEXT('\0') ||
  178. pszPathToBookmarks==NULL || *pszPathToBookmarks == TEXT('\0'))
  179. {
  180. return FALSE;
  181. }
  182. hBookmarksFile = CreateFile(pszPathToBookmarks, GENERIC_READ, FILE_SHARE_READ, NULL,
  183. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
  184. if ( hBookmarksFile != INVALID_HANDLE_VALUE )
  185. {
  186. //
  187. // Verify it's a valid Bookmarks file
  188. //
  189. if (VerifyBookmarksFile( hBookmarksFile ))
  190. {
  191. //
  192. // Do the importing...
  193. //
  194. fSuccess = ConvertBookmarks(pszPathToFavorites, hBookmarksFile);
  195. if (hwnd && !fSuccess)
  196. {
  197. MLShellMessageBox(
  198. hwnd,
  199. MAKEINTRESOURCE(IDS_IMPORTCONVERTERROR),
  200. MAKEINTRESOURCE(IDS_CONFIRM_IMPTTL_FAV),
  201. MB_OK);
  202. }
  203. }
  204. else
  205. {
  206. if (hwnd)
  207. {
  208. MLShellMessageBox(
  209. hwnd,
  210. MAKEINTRESOURCE(IDS_NOTVALIDBOOKMARKS),
  211. MAKEINTRESOURCE(IDS_CONFIRM_IMPTTL_FAV),
  212. MB_OK);
  213. }
  214. }
  215. CloseHandle(hBookmarksFile);
  216. }
  217. else
  218. {
  219. if (hwnd)
  220. {
  221. MLShellMessageBox(
  222. hwnd,
  223. MAKEINTRESOURCE(IDS_COULDNTOPENBOOKMARKS),
  224. MAKEINTRESOURCE(IDS_CONFIRM_IMPTTL_FAV),
  225. MB_OK);
  226. }
  227. }
  228. return(fSuccess);
  229. }
  230. /************************************************************\
  231. FUNCTION: ConvertBookmarks
  232. PARAMETERS:
  233. char * szFavoritesDir - String containing the path to
  234. the IE Favorites directory
  235. BOOL return - If an error occurs importing the bookmarks, FALSE is returned.
  236. DESCRIPTION:
  237. This function will continue in a loop converting each
  238. entry in the bookmark file. There are three types of
  239. entries in the bookmark file, 1) a bookmark, 2) start of
  240. new level in heirarchy, 3) end of current level in heirarchy.
  241. The function NextFileEntry() will return these values until
  242. the file is empty, at which point, this function will end.
  243. NOTE:
  244. In order to prevent an infinite loop, it's assumed
  245. that NextFileEntry() will eventually return ET_NONE or ET_ERROR.
  246. \************************************************************/
  247. BOOL ConvertBookmarks(TCHAR * szFavoritesDir, HANDLE hFile)
  248. {
  249. BOOL fDone = FALSE;
  250. BOOL fSuccess = TRUE;
  251. BOOL fIsEmpty = TRUE;
  252. char * szData = NULL;
  253. char * szCurrent = NULL;
  254. char * szToken = NULL;
  255. fSuccess = GetData(&szData, hFile);
  256. if (NULL == szData)
  257. fSuccess = FALSE;
  258. szCurrent = szData;
  259. // Verify directory exists or that we can make it.
  260. if ((TRUE == fSuccess) && ( !SetCurrentDirectory(szFavoritesDir)))
  261. {
  262. // If the directory doesn't exist, make it...
  263. if ( !CreateDirectory(szFavoritesDir, NULL))
  264. fSuccess = FALSE;
  265. else
  266. if (!SetCurrentDirectory(szFavoritesDir))
  267. fSuccess = FALSE;
  268. }
  269. while ((FALSE == fDone) && (TRUE == fSuccess))
  270. {
  271. switch(NextFileEntry(&szCurrent, &szToken))
  272. {
  273. case ET_OPEN_DIR:
  274. fSuccess = CreateDir(szToken);
  275. break;
  276. case ET_CLOSE_DIR:
  277. fSuccess = CloseDir();
  278. break;
  279. case ET_BOOKMARK:
  280. fSuccess = CreateBookmark(szToken);
  281. fIsEmpty = FALSE;
  282. break;
  283. case ET_ERROR:
  284. fSuccess = FALSE;
  285. break;
  286. case ET_NONE:
  287. default:
  288. fDone = TRUE;
  289. break;
  290. }
  291. }
  292. if ( fIsEmpty )
  293. {
  294. // nothing to import, delete the dir created earlier
  295. RemoveDirectory(szFavoritesDir);
  296. }
  297. if (NULL != szData)
  298. {
  299. LocalFree(szData);
  300. szData = NULL;
  301. szCurrent = NULL; // szCurrent no longer points to valid data.
  302. szToken = NULL; // szCurrent no longer points to valid data.
  303. }
  304. return(fSuccess);
  305. }
  306. /************************************************************\
  307. FUNCTION: NextFileEntry
  308. PARAMETERS:
  309. char ** ppStr - The data to parse.
  310. char ** ppToken - The token pointer.
  311. EntryType return- See below.
  312. DESCRIPTION:
  313. This function will look for the next entry in the
  314. bookmark file to create or act on. The return value
  315. will indicate this response:
  316. ET_OPEN_DIR Create a new level in heirarchy
  317. ET_CLOSE_DIR, Close level in heirarchy
  318. ET_BOOKMARK, Create Bookmark entry.
  319. ET_NONE, End of File
  320. ET_ERROR Error encountered
  321. Errors will be detected by finding the start of a token,
  322. but in not finding other parts of the token that are needed
  323. to parse the data.
  324. \************************************************************/
  325. MyEntryType NextFileEntry(char ** ppStr, char ** ppToken)
  326. {
  327. MyEntryType returnVal = ET_NONE;
  328. char * pCurrentToken = NULL; // The current token to check if valid.
  329. char * pTheToken = NULL; // The next valid token.
  330. char * pszTemp = NULL;
  331. #ifdef UNIX
  332. char szMidDirToken[8];
  333. #endif
  334. //ASSERTSZ(NULL != ppStr, "It's an error to pass NULL for ppStr");
  335. //ASSERTSZ(NULL != *ppStr, "It's an error to pass NULL for *ppStr");
  336. //ASSERTSZ(NULL != ppToken, "It's an error to pass NULL for ppToken");
  337. if ((NULL != ppStr) && (NULL != *ppStr) && (NULL != ppToken))
  338. {
  339. // Check for begin dir token
  340. if (NULL != (pCurrentToken = ANSIStrStr(*ppStr, BEGIN_DIR_TOKEN)))
  341. {
  342. // Begin dir token found
  343. // Verify that other needed tokens exist or it's an error
  344. #ifndef UNIX
  345. if ((NULL == (pszTemp = ANSIStrStr(pCurrentToken, MID_DIR_TOKEN))) ||
  346. #else
  347. if (pCurrentToken[7] == ' ')
  348. StrCpyNA(szMidDirToken, MID_DIR_TOKEN, ARRAYSIZE(szMidDirToken));
  349. else
  350. StrCpyNA(szMidDirToken, MID_DIR_TOKEN0, ARRAYSIZE(szMidDirToken));
  351. if ((NULL == (pszTemp = ANSIStrStr(pCurrentToken, szMidDirToken))) ||
  352. #endif
  353. (NULL == ANSIStrStr(pszTemp, END_DIR_TOKEN)))
  354. {
  355. returnVal = ET_ERROR; // We can't find all the tokens needed.
  356. }
  357. else
  358. {
  359. // This function has to set *ppToken to the name of the directory to create
  360. #ifndef UNIX
  361. *ppToken = ANSIStrStr(pCurrentToken, MID_DIR_TOKEN) + sizeof(MID_DIR_TOKEN)-1;
  362. #else
  363. *ppToken = ANSIStrStr(pCurrentToken, szMidDirToken) + lstrlenA(szMidDirToken);
  364. #endif
  365. pTheToken = pCurrentToken;
  366. returnVal = ET_OPEN_DIR;
  367. }
  368. }
  369. // Check for exit dir token
  370. if ((ET_ERROR != returnVal) &&
  371. (NULL != (pCurrentToken = ANSIStrStr(*ppStr, BEGIN_EXITDIR_TOKEN))))
  372. {
  373. // Exit dir token found
  374. // See if this token comes before TheToken.
  375. if ((NULL == pTheToken) || (pCurrentToken < pTheToken))
  376. {
  377. // ppToken is not used for Exit Dir
  378. *ppToken = NULL;
  379. pTheToken = pCurrentToken;
  380. returnVal = ET_CLOSE_DIR;
  381. }
  382. }
  383. // Check for begin url token
  384. if ((ET_ERROR != returnVal) &&
  385. (NULL != (pCurrentToken = ANSIStrStr(*ppStr, BEGIN_URL_TOKEN))))
  386. {
  387. // Bookmark token found
  388. // Verify that other needed tokens exist or it's an error
  389. #ifndef UNIX
  390. if ((NULL == (pszTemp = ANSIStrStr(pCurrentToken, END_URL_TOKEN))) ||
  391. #else
  392. if (((NULL == (pszTemp = ANSIStrStr(pCurrentToken, END_URL_TOKEN))) &&
  393. (NULL == (pszTemp = ANSIStrStr(pCurrentToken, END_URL_TOKEN2)))) ||
  394. #endif
  395. (NULL == (pszTemp = ANSIStrStr(pszTemp, BEGIN_BOOKMARK_TOKEN))) ||
  396. (NULL == ANSIStrStr(pszTemp, END_BOOKMARK_TOKEN)))
  397. {
  398. returnVal = ET_ERROR; // We can't find all the tokens needed.
  399. }
  400. else
  401. {
  402. // See if this token comes before TheToken.
  403. if ((NULL == pTheToken) || (pCurrentToken < pTheToken))
  404. {
  405. // This function has to set *ppToken to the name of the bookmark
  406. *ppToken = pCurrentToken + sizeof(BEGIN_URL_TOKEN)-1;
  407. pTheToken = pCurrentToken;
  408. returnVal = ET_BOOKMARK;
  409. }
  410. }
  411. }
  412. }
  413. else
  414. returnVal = ET_ERROR; // We should never get here.
  415. if (NULL == pTheToken)
  416. returnVal = ET_NONE;
  417. else
  418. {
  419. // Next time we will start parsing where we left off.
  420. switch(returnVal)
  421. {
  422. case ET_OPEN_DIR:
  423. #ifndef UNIX
  424. *ppStr = ANSIStrStr(pTheToken, MID_DIR_TOKEN) + sizeof(MID_DIR_TOKEN);
  425. #else
  426. *ppStr = ANSIStrStr(pTheToken, szMidDirToken) + lstrlenA(szMidDirToken) + 1;
  427. #endif
  428. break;
  429. case ET_CLOSE_DIR:
  430. *ppStr = pTheToken + sizeof(BEGIN_EXITDIR_TOKEN);
  431. break;
  432. case ET_BOOKMARK:
  433. *ppStr = ANSIStrStr(pTheToken, END_BOOKMARK_TOKEN) + sizeof(END_BOOKMARK_TOKEN);
  434. break;
  435. default:
  436. break;
  437. }
  438. }
  439. return(returnVal);
  440. }
  441. /************************************************************\
  442. FUNCTION: GetPathFromRegistry
  443. PARAMETERS:
  444. LPSTR szPath - The value found in the registry. (Result of function)
  445. UINT cbPath - Size of szPath.
  446. HKEY theHKEY - The HKEY to look into (HKEY_CURRENT_USER)
  447. LPSTR szKey - Path in Registry (Software\...\Explore\Shell Folders)
  448. LPSTR szVName - Value to query (Favorites)
  449. BOOL return - TRUE if succeeded, FALSE if Error.
  450. EXAMPLE:
  451. HKEY_CURRENT_USER\Software\Microsoft\CurrentVersion\Explore\Shell Folders
  452. Favorites = "C:\WINDOWS\Favorites"
  453. DESCRIPTION:
  454. This function will look in the registry for the value
  455. to look up. The caller specifies the HKEY, subkey (szKey),
  456. value to query (szVName). The caller also sets a side memory
  457. for the result and passes a pointer to that memory in szPath
  458. with it's size in cbPath. The BOOL return value will indicate
  459. success or failure of this function.
  460. \************************************************************/
  461. BOOL GetPathFromRegistry(LPTSTR szPath, UINT cbPath, HKEY theHKEY,
  462. LPTSTR szKey, LPTSTR szVName)
  463. {
  464. DWORD dwType;
  465. DWORD dwSize;
  466. /*
  467. * Get Path to program
  468. * from the registry
  469. */
  470. dwSize = cbPath;
  471. return (ERROR_SUCCESS == SHGetValue(theHKEY, szKey, szVName, &dwType, (LPBYTE) szPath, &dwSize)
  472. && (dwType == REG_EXPAND_SZ || dwType == REG_SZ));
  473. }
  474. /************************************************************\
  475. FUNCTION: RemoveInvalidFileNameChars
  476. PARAMETERS:
  477. char * pBuf - The data to search.
  478. DESCRIPTION:
  479. This function will search pBuf until it encounters
  480. a character that is not allowed in a file name. It will
  481. then replace that character with a SPACE and continue looking
  482. for more invalid chars until they have all been removed.
  483. \************************************************************/
  484. void RemoveInvalidFileNameChars(char * pBuf)
  485. {
  486. //ASSERTSZ(NULL != pBuf, "Invalid function parameter");
  487. // Go through the array of chars, replacing offending characters with a space
  488. if (NULL != pBuf)
  489. {
  490. if (REASONABLE_NAME_LEN < strlen(pBuf))
  491. pBuf[REASONABLE_NAME_LEN] = '\0'; // String too long. Terminate it.
  492. while ('\0' != *pBuf)
  493. {
  494. // Check if the character is invalid
  495. if (!IsDBCSLeadByte(*pBuf))
  496. {
  497. if (ANSIStrChr(szInvalidFolderCharacters, *pBuf) != NULL)
  498. *pBuf = '_';
  499. }
  500. pBuf = CharNextA(pBuf);
  501. }
  502. }
  503. }
  504. /************************************************************\
  505. FUNCTION: CreateBookmark
  506. PARAMETERS:
  507. char * pBookmarkName- This is a pointer that contains
  508. the name of the bookmark to create.
  509. Note that it is not NULL terminated.
  510. BOOL return - Return TRUE if successful.
  511. DESCRIPTION:
  512. This function will take the data that is passed to
  513. it and extract the name of the bookmark and it's value to create.
  514. If the name is too long, it will be truncated. Then,
  515. the directory will be created. Any errors encountered
  516. will cause the function to return FALSE to indicate
  517. failure.
  518. \************************************************************/
  519. BOOL CreateBookmark(char *pBookmarkName)
  520. {
  521. BOOL fSuccess = FALSE;
  522. char szNameOfBM[REASONABLE_NAME_LEN];
  523. char szURL[MAX_URL];
  524. char * pstrEndOfStr = NULL;
  525. char * pstrBeginOfName = NULL;
  526. long lStrLen = 0;
  527. HANDLE hFile = NULL;
  528. DWORD dwSize;
  529. char szBuf[MAX_URL];
  530. //ASSERTSZ(NULL != pBookmarkName, "Bad input parameter");
  531. if (NULL != pBookmarkName)
  532. {
  533. pstrEndOfStr = ANSIStrStr(pBookmarkName, END_URL_TOKEN);
  534. #ifdef UNIX
  535. if (!pstrEndOfStr)
  536. pstrEndOfStr = ANSIStrStr(pBookmarkName, END_URL_TOKEN2);
  537. #endif
  538. if (NULL != pstrEndOfStr)
  539. {
  540. lStrLen = (int) (pstrEndOfStr-pBookmarkName);
  541. if (MAX_URL < lStrLen)
  542. lStrLen = MAX_URL-1;
  543. // Create the name of the Bookmark
  544. StrCpyNA(szURL, pBookmarkName, ARRAYSIZE(szURL));
  545. szURL[lStrLen] = '\0';
  546. // filter out file links, we won't create a bookmark to a file link
  547. // but remove the link silently and continue
  548. if (IsFileUrl(szURL))
  549. return TRUE;
  550. pstrBeginOfName = ANSIStrStr(pstrEndOfStr, BEGIN_BOOKMARK_TOKEN);
  551. if (NULL != pstrBeginOfName)
  552. {
  553. pstrBeginOfName += sizeof(BEGIN_BOOKMARK_TOKEN) - 1; // Start at beginning of Name
  554. pstrEndOfStr = ANSIStrStr(pstrBeginOfName, END_BOOKMARK_TOKEN); // Find end of name
  555. if (NULL != pstrEndOfStr)
  556. {
  557. lStrLen = (int) (pstrEndOfStr-pstrBeginOfName);
  558. if (REASONABLE_NAME_LEN-FILE_EXT-1 < lStrLen)
  559. lStrLen = REASONABLE_NAME_LEN-FILE_EXT-1;
  560. // Generate the URL
  561. StrCpyNA(szNameOfBM, pstrBeginOfName, lStrLen+1);
  562. //szNameOfBM[lStrLen] = '\0';
  563. StrCatBuffA(szNameOfBM, ".url", ARRAYSIZE(szNameOfBM));
  564. RemoveInvalidFileNameChars(szNameOfBM);
  565. // Check to see if Favorite w/same name exists
  566. if (INVALID_HANDLE_VALUE != (hFile = CreateFileA(szNameOfBM, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  567. CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL )))
  568. {
  569. WriteFile(hFile, "[InternetShortcut]\n", lstrlenA( "[InternetShortcut]\n" ), &dwSize, NULL);
  570. wnsprintfA( szBuf, ARRAYSIZE(szBuf), "URL=%s\n", szURL);
  571. WriteFile(hFile, szBuf, lstrlenA(szBuf), &dwSize, NULL );
  572. fSuccess = TRUE;
  573. }
  574. else
  575. {
  576. fSuccess = TRUE;
  577. }
  578. if (NULL != hFile)
  579. {
  580. CloseHandle( hFile );
  581. hFile = NULL;
  582. }
  583. }
  584. }
  585. }
  586. }
  587. return(fSuccess);
  588. }
  589. /************************************************************\
  590. FUNCTION: CreateDir
  591. PARAMETERS:
  592. char * pDirName - This is a pointer that contains
  593. the name of the directory to create.
  594. Note that it is not NULL terminated.
  595. BOOL return - Return TRUE if successful.
  596. DESCRIPTION:
  597. This function will take the data that is passed to
  598. it and extract the name of the directory to create.
  599. If the name is too long, it will be truncated. Then,
  600. the directory will be created. Any errors encountered
  601. will cause the function to return FALSE to indicate
  602. failure.
  603. \************************************************************/
  604. BOOL CreateDir(char *pDirName)
  605. {
  606. BOOL fSuccess = FALSE;
  607. char szNameOfDir[REASONABLE_NAME_LEN];
  608. char * pstrEndOfName = NULL;
  609. long lStrLen = 0;
  610. //ASSERTSZ(NULL != pDirName, "Bad input parameter");
  611. if (NULL != pDirName)
  612. {
  613. pstrEndOfName = ANSIStrStr(pDirName, END_DIR_TOKEN);
  614. if (NULL != pstrEndOfName)
  615. {
  616. lStrLen = (int) (pstrEndOfName-pDirName);
  617. if (REASONABLE_NAME_LEN-1 < lStrLen)
  618. lStrLen = REASONABLE_NAME_LEN-1;
  619. StrCpyNA(szNameOfDir, pDirName, lStrLen+1);
  620. //szNameOfDir[lStrLen] = '\0';
  621. RemoveInvalidFileNameChars(szNameOfDir);
  622. if ( !SetCurrentDirectoryA(szNameOfDir) )
  623. {
  624. if ( CreateDirectoryA(szNameOfDir, NULL) )
  625. {
  626. if ( SetCurrentDirectoryA(szNameOfDir) )
  627. {
  628. fSuccess = TRUE;// It didn't exist, but now it does.
  629. }
  630. }
  631. }
  632. else
  633. fSuccess = TRUE; // It exists already.
  634. }
  635. }
  636. return(fSuccess);
  637. }
  638. /************************************************************\
  639. FUNCTION: CloseDir
  640. PARAMETERS:
  641. BOOL return - Return TRUE if successful.
  642. DESCRIPTION:
  643. This function will back out of the current directory.
  644. \************************************************************/
  645. BOOL CloseDir(void)
  646. {
  647. return( SetCurrentDirectoryA("..") );
  648. }
  649. /************************************************************\
  650. FUNCTION: VerifyBookmarksFile
  651. PARAMETERS:
  652. FILE * pFile - Pointer to Netscape Bookmarks file.
  653. BOOL return - TRUE if No Error and Valid Bookmark file
  654. DESCRIPTION:
  655. This function needs to be passed with a valid pointer
  656. that points to an open file. Upon return, the file will
  657. still be open and is guarenteed to have the file pointer
  658. point to the beginning of the file.
  659. This function will return TRUE if the file contains
  660. text that indicates it's a valid Netscape bookmarks file.
  661. \************************************************************/
  662. BOOL VerifyBookmarksFile(HANDLE hFile)
  663. {
  664. BOOL fSuccess = FALSE;
  665. char szFileHeader[sizeof(VALIDATION_STR)+1] = "";
  666. DWORD dwSize;
  667. //ASSERTSZ(NULL != pFile, "You can't pass me a NULL File Pointer");
  668. if (INVALID_HANDLE_VALUE == hFile)
  669. return(FALSE);
  670. // Reading the first part of the file. If the file isn't this long, then
  671. // it can't possibly be a Bookmarks file.
  672. if ( ReadFile( hFile, szFileHeader, sizeof(VALIDATION_STR)-1, &dwSize, NULL ) && (dwSize == sizeof(VALIDATION_STR)-1) )
  673. {
  674. #ifndef UNIX
  675. szFileHeader[sizeof(VALIDATION_STR)] = '\0'; // Terminate String.
  676. #else
  677. // The above statement doesn;t serve the purpose on UNIX.
  678. // I think we should change for NT also.
  679. // IEUNIX : NULL character after the buffer read
  680. szFileHeader[sizeof(VALIDATION_STR)-1] = '\0'; // Terminate String.
  681. #endif
  682. if (0 == StrCmpA(szFileHeader, VALIDATION_STR)) // See if header is the same as the Validation string.
  683. fSuccess = TRUE;
  684. }
  685. // Reset the point to point to the beginning of the file.
  686. dwSize = SetFilePointer( hFile, 0, NULL, FILE_BEGIN );
  687. if ( dwSize == 0xFFFFFFFF )
  688. fSuccess = FALSE;
  689. return(fSuccess);
  690. }
  691. /************************************************************\
  692. FUNCTION: GetData
  693. PARAMETERS:
  694. char ** ppData - Where to put the data
  695. FILE * pFile - Pointer to Netscape Bookmarks file.
  696. BOOL return - Return TRUE is successful.
  697. DESCRIPTION:
  698. This function will find the size of the bookmarks file,
  699. malloc that much memory, and put the file's contents in
  700. that buffer. ppData will be invalid when the function
  701. is called and will return with malloced memory that
  702. needs to be freed by the falling function.
  703. \************************************************************/
  704. BOOL GetData(char ** ppData, HANDLE hFile)
  705. {
  706. DWORD dwlength, dwRead;
  707. BOOL fSuccess = FALSE;
  708. //ASSERTSZ(NULL != ppData, "Invalid input parameter");
  709. if (NULL != ppData)
  710. {
  711. *ppData = NULL;
  712. // Find the size of the data
  713. if ( dwlength = GetFileSize(hFile, NULL))
  714. {
  715. *ppData = (PSTR)LocalAlloc(LPTR, dwlength+1 );
  716. if (NULL != *ppData)
  717. {
  718. if ( ReadFile( hFile, *ppData, dwlength+1, &dwRead, NULL ) &&
  719. ( dwlength == dwRead ) )
  720. {
  721. fSuccess = TRUE;
  722. }
  723. (*ppData)[dwlength] = '\0';
  724. }
  725. }
  726. }
  727. return(fSuccess);
  728. }
  729. //
  730. // AddPath - added by julianj when porting from setup code to stand alone
  731. //
  732. void PASCAL AddPath(LPTSTR pszPath, LPCTSTR pszName, int cchPath )
  733. {
  734. LPTSTR pszTmp;
  735. int cchTmp;
  736. // Find end of the string
  737. cchTmp = lstrlen(pszPath);
  738. pszTmp = pszPath + cchTmp;
  739. cchTmp = cchPath - cchTmp;
  740. // If no trailing backslash then add one
  741. if ( pszTmp > pszPath && *(CharPrev( pszPath, pszTmp )) != FILENAME_SEPARATOR )
  742. {
  743. *(pszTmp++) = FILENAME_SEPARATOR;
  744. cchTmp--;
  745. }
  746. // Add new name to existing path string
  747. while ( *pszName == TEXT(' ') ) pszName++;
  748. StrCpyN( pszTmp, pszName, cchTmp );
  749. }
  750. //
  751. // GetVersionFromFile - added by julianj when porting from setup code to stand alone
  752. //
  753. BOOL GetVersionFromFile(PTSTR pszFileName, PDWORD pdwMSVer, PDWORD pdwLSVer)
  754. {
  755. DWORD dwVerInfoSize, dwHandle;
  756. LPVOID lpVerInfo;
  757. VS_FIXEDFILEINFO *pvsVSFixedFileInfo;
  758. UINT uSize;
  759. HRESULT hr = E_FAIL;
  760. *pdwMSVer = *pdwLSVer = 0;
  761. if ((dwVerInfoSize = GetFileVersionInfoSize(pszFileName, &dwHandle)))
  762. {
  763. if ((lpVerInfo = (LPVOID) LocalAlloc(LPTR, dwVerInfoSize)) != NULL)
  764. {
  765. if (GetFileVersionInfo(pszFileName, dwHandle, dwVerInfoSize, lpVerInfo))
  766. {
  767. if (VerQueryValue(lpVerInfo, TEXT("\\"), (LPVOID *) &pvsVSFixedFileInfo, &uSize))
  768. {
  769. *pdwMSVer = pvsVSFixedFileInfo->dwFileVersionMS;
  770. *pdwLSVer = pvsVSFixedFileInfo->dwFileVersionLS;
  771. hr = S_OK;
  772. }
  773. }
  774. LocalFree(lpVerInfo);
  775. lpVerInfo = NULL;
  776. }
  777. else
  778. {
  779. hr = E_OUTOFMEMORY;
  780. }
  781. }
  782. return hr;
  783. }
  784. BOOL GetNavBkMkDir( LPTSTR lpszDir, int isize)
  785. {
  786. BOOL bDirFound = FALSE;
  787. #ifndef UNIX
  788. TCHAR szDir[MAX_PATH];
  789. HKEY hKey;
  790. HKEY hKeyUser;
  791. TCHAR szUser[MAX_PATH];
  792. DWORD dwSize;
  793. StrCpyN( szUser, REGSTR_PATH_APPPATHS, ARRAYSIZE(szUser) );
  794. AddPath( szUser, TEXT("NetScape.exe"), ARRAYSIZE(szUser) );
  795. if ( GetPathFromRegistry( szDir, ARRAYSIZE(szDir), HKEY_LOCAL_MACHINE, szUser, TEXT("") ) &&
  796. lstrlen(szDir) )
  797. {
  798. DWORD dwMV, dwLV;
  799. if ( SUCCEEDED(GetVersionFromFile( szDir, &dwMV, &dwLV )) )
  800. {
  801. if ( dwMV < 0x00040000 )
  802. bDirFound = GetPathFromRegistry( lpszDir, isize, HKEY_CURRENT_USER,
  803. szNetscapeBMRegSub, szNetscapeBMRegKey);
  804. else
  805. {
  806. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\Netscape\\Netscape Navigator\\Users"), 0, KEY_READ, &hKey) == ERROR_SUCCESS)
  807. {
  808. dwSize = sizeof(szUser);
  809. if (RegQueryValueEx(hKey, TEXT("CurrentUser"), NULL, NULL, (LPBYTE)szUser, &dwSize) == ERROR_SUCCESS)
  810. {
  811. if (RegOpenKeyEx(hKey, szUser, 0, KEY_READ, &hKeyUser) == ERROR_SUCCESS)
  812. {
  813. dwSize = sizeof(szDir);
  814. if (RegQueryValueEx(hKeyUser, TEXT("DirRoot"), NULL, NULL, (LPBYTE)szDir, &dwSize) == ERROR_SUCCESS)
  815. {
  816. // Found the directory for the current user.
  817. StrCpyN( lpszDir, szDir, isize);
  818. AddPath( lpszDir, TEXT("bookmark.htm"), isize );
  819. bDirFound = TRUE;
  820. }
  821. RegCloseKey(hKeyUser);
  822. }
  823. }
  824. RegCloseKey(hKey);
  825. }
  826. }
  827. }
  828. }
  829. else
  830. #endif
  831. bDirFound = GetPathFromRegistry( lpszDir, isize, HKEY_CURRENT_USER,
  832. szNetscapeBMRegSub, szNetscapeBMRegKey);
  833. return bDirFound;
  834. }
  835. //
  836. // *** EXPORT FAVORITES CODE ***
  837. //
  838. // REVIEW REMOVE THESE
  839. #include <windows.h>
  840. //#include <stdio.h>
  841. #include <shlobj.h>
  842. #include <shlwapi.h>
  843. //
  844. // Generate HTML from favorites
  845. //
  846. #define INDENT_AMOUNT 4
  847. int Indent = 0;
  848. HANDLE g_hOutputStream = INVALID_HANDLE_VALUE;
  849. void Output(const char *format, ...)
  850. {
  851. DWORD dwSize;
  852. char buf[MAX_URL];
  853. va_list argptr;
  854. va_start(argptr, format);
  855. for (int i=0; i<Indent*INDENT_AMOUNT; i++)
  856. {
  857. WriteFile(g_hOutputStream, " ", 1, &dwSize, NULL);
  858. }
  859. wvnsprintfA(buf, ARRAYSIZE(buf), format, argptr);
  860. WriteFile(g_hOutputStream, buf, lstrlenA(buf), &dwSize, NULL);
  861. }
  862. void OutputLn(const char *format, ...)
  863. {
  864. DWORD dwSize;
  865. char buf[MAX_URL];
  866. va_list argptr;
  867. va_start(argptr, format);
  868. for (int i=0; i<Indent*INDENT_AMOUNT; i++)
  869. {
  870. WriteFile(g_hOutputStream, " ", 1, &dwSize, NULL);
  871. }
  872. wvnsprintfA(buf, ARRAYSIZE(buf), format, argptr);
  873. WriteFile(g_hOutputStream, buf, lstrlenA(buf), &dwSize, NULL);
  874. WriteFile(g_hOutputStream, "\r\n", 2, &dwSize, NULL);
  875. }
  876. #define CREATION_TIME 0
  877. #define ACCESS_TIME 1
  878. #define MODIFY_TIME 2
  879. //
  880. // This nasty looking macro converts a FILETIME structure
  881. // (100-nanosecond intervals since Jan 1st 1601) to a
  882. // unix time_t value (seconds since Jan 1st 1970).
  883. //
  884. // The numbers come from knowledgebase article Q167296
  885. //
  886. #define FILETIME_TO_UNIXTIME(ft) (UINT)((*(LONGLONG*)&ft-116444736000000000)/10000000)
  887. UINT GetUnixFileTime(LPTSTR pszFileName, int mode)
  888. {
  889. WIN32_FIND_DATA wfd;
  890. HANDLE hFind;
  891. hFind = FindFirstFile(pszFileName,&wfd);
  892. if (hFind == INVALID_HANDLE_VALUE)
  893. return 0;
  894. FindClose(hFind);
  895. switch (mode)
  896. {
  897. case CREATION_TIME:
  898. return FILETIME_TO_UNIXTIME(wfd.ftCreationTime);
  899. case ACCESS_TIME:
  900. return FILETIME_TO_UNIXTIME(wfd.ftLastAccessTime);
  901. case MODIFY_TIME:
  902. return FILETIME_TO_UNIXTIME(wfd.ftLastWriteTime);
  903. default:
  904. ASSERT(0);
  905. return 0;
  906. }
  907. }
  908. void WalkTree(TCHAR * szDir)
  909. {
  910. WIN32_FIND_DATA findFileData;
  911. TCHAR buf[MAX_PATH];
  912. HANDLE hFind;
  913. Indent++;
  914. //
  915. // First iterate through all directories
  916. //
  917. wnsprintf(buf, ARRAYSIZE(buf), TEXT("%s") TEXT(FILENAME_SEPARATOR_STR) TEXT("*"), szDir);
  918. hFind = FindFirstFile(buf, &findFileData);
  919. if (INVALID_HANDLE_VALUE != hFind)
  920. {
  921. do
  922. {
  923. if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  924. {
  925. if ((StrCmp(findFileData.cFileName, TEXT(".")) != 0 &&
  926. StrCmp(findFileData.cFileName, TEXT("..")) != 0 &&
  927. StrCmp(findFileData.cFileName, TEXT("History")) != 0 && // REVIEW just for JJ. Should check for system bit on folders
  928. StrCmp(findFileData.cFileName, TEXT("Software Updates")) != 0 && // don't export software updates
  929. StrCmp(findFileData.cFileName, TEXT("Channels")) != 0)) // don't export channels for now!
  930. {
  931. char thisFile[MAX_PATH];
  932. wnsprintf(buf, ARRAYSIZE(buf), TEXT("%s") TEXT(FILENAME_SEPARATOR_STR) TEXT("%s"), szDir, findFileData.cFileName);
  933. if (!(GetFileAttributes(buf)&FILE_ATTRIBUTE_SYSTEM))
  934. {
  935. SHTCharToAnsi(findFileData.cFileName, thisFile, MAX_PATH);
  936. OutputLn("<DT><H3 FOLDED ADD_DATE=\"%u\">%s</H3>", GetUnixFileTime(buf,CREATION_TIME), thisFile);
  937. OutputLn("<DL><p>");
  938. WalkTree(buf);
  939. OutputLn(BEGIN_EXITDIR_TOKEN);
  940. }
  941. }
  942. else
  943. {
  944. ; // ignore . and ..
  945. }
  946. }
  947. } while (FindNextFile(hFind, &findFileData));
  948. FindClose(hFind);
  949. }
  950. //
  951. // Next iterate through all files
  952. //
  953. wnsprintf(buf, ARRAYSIZE(buf), TEXT("%s") TEXT(FILENAME_SEPARATOR_STR) TEXT("*"), szDir);
  954. hFind = FindFirstFile(buf, &findFileData);
  955. if (INVALID_HANDLE_VALUE != hFind)
  956. {
  957. do
  958. {
  959. if (!(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
  960. {
  961. wnsprintf(buf, ARRAYSIZE(buf), TEXT("%s") TEXT(FILENAME_SEPARATOR_STR) TEXT("%s"), szDir, findFileData.cFileName);
  962. //
  963. // Read the url from the .url file
  964. //
  965. TCHAR szUrl[MAX_PATH];
  966. SHGetIniString(
  967. TEXT("InternetShortcut"),
  968. TEXT("URL"),
  969. szUrl, // returns url
  970. MAX_PATH,
  971. buf); // full path to .url file
  972. if (*szUrl != 0)
  973. {
  974. //
  975. // create a copy of the filename without the extension
  976. // note PathFindExtension returns a ptr to the NULL at
  977. // end if '.' not found so its ok to just blast *pch with 0
  978. //
  979. TCHAR szFileName[MAX_PATH];
  980. StrCpyN(szFileName, findFileData.cFileName, ARRAYSIZE(szFileName));
  981. TCHAR *pch = PathFindExtension(szFileName);
  982. *pch = TEXT('\0'); //
  983. char szUrlAnsi[MAX_PATH], szFileNameAnsi[MAX_PATH];
  984. SHTCharToAnsi(szUrl, szUrlAnsi, MAX_PATH);
  985. SHTCharToAnsi(szFileName, szFileNameAnsi, MAX_PATH);
  986. OutputLn("<DT><A HREF=\"%s\" ADD_DATE=\"%u\" LAST_VISIT=\"%u\" LAST_MODIFIED=\"%u\">%s</A>",
  987. szUrlAnsi,
  988. GetUnixFileTime(buf,CREATION_TIME),
  989. GetUnixFileTime(buf,ACCESS_TIME),
  990. GetUnixFileTime(buf,MODIFY_TIME),
  991. szFileNameAnsi);
  992. }
  993. }
  994. } while (FindNextFile(hFind, &findFileData));
  995. FindClose(hFind);
  996. }
  997. Indent--;
  998. }
  999. BOOL ExportFavorites(TCHAR * pszPathToFavorites, TCHAR * pszPathToBookmarks, HWND hwnd)
  1000. {
  1001. // Prompt the user to insert floppy, format floppy or drive, remount mapped partition,
  1002. // or any create sub directories so pszPathToBookmarks becomes valid.
  1003. if (FAILED(SHPathPrepareForWriteWrap(hwnd, NULL, pszPathToBookmarks, FO_COPY, (SHPPFW_DEFAULT | SHPPFW_IGNOREFILENAME))))
  1004. return FALSE;
  1005. // Open output file REVIEW redo to use Win32 file apis
  1006. g_hOutputStream = CreateFile(
  1007. pszPathToBookmarks,
  1008. GENERIC_WRITE,
  1009. 0, // no sharing,
  1010. NULL, // no security attribs
  1011. CREATE_ALWAYS, // overwrite if present
  1012. FILE_ATTRIBUTE_NORMAL,
  1013. NULL);
  1014. if (g_hOutputStream == INVALID_HANDLE_VALUE)
  1015. return FALSE;
  1016. //
  1017. // Output bookmark file header stuff
  1018. //
  1019. Output(VALIDATION_STR);
  1020. OutputLn("1>");
  1021. OutputLn(COMMENT_STR);
  1022. OutputLn(TITLE); // REVIEW put/persist users name in Title???
  1023. //
  1024. // Do the walk
  1025. //
  1026. OutputLn("<DL><p>");
  1027. WalkTree(pszPathToFavorites);
  1028. OutputLn(BEGIN_EXITDIR_TOKEN);
  1029. //
  1030. // Close output file handle
  1031. //
  1032. CloseHandle(g_hOutputStream); // REVIEW
  1033. return TRUE;
  1034. }
  1035. //
  1036. // Import/Export User interface dialog routines
  1037. //
  1038. //
  1039. // Standalone app for importing the Netscape Favorites into IE.
  1040. //
  1041. // julianj 3/9/98
  1042. //
  1043. #ifdef _WIN32_WINNT
  1044. #undef _WIN32_WINNT
  1045. #endif
  1046. #ifdef _WIN32_WINDOWS
  1047. #undef _WIN32_WINDOWS
  1048. #endif
  1049. #ifdef WINVER
  1050. #undef WINVER
  1051. #endif
  1052. #define _WIN32_WINDOWS 0x0400
  1053. #define _WIN32_WINNT 0x0400
  1054. #define WINVER 0x0400
  1055. TCHAR g_szPathToFavorites[MAX_PATH+1];
  1056. TCHAR g_szPathToBookmarks[MAX_PATH+1];
  1057. LPITEMIDLIST g_pidlFavorites = NULL;
  1058. enum DIALOG_TYPE {FILE_OPEN_DIALOG, FILE_SAVE_DIALOG};
  1059. BOOL BrowseForBookmarks(TCHAR *pszPathToBookmarks, int cchPathToBookmarks, HWND hwnd, DIALOG_TYPE dialogType)
  1060. {
  1061. TCHAR szFile[MAX_PATH];
  1062. TCHAR szDir[MAX_PATH];
  1063. TCHAR *pszFileName = PathFindFileName(pszPathToBookmarks);
  1064. TCHAR szDialogTitle[MAX_PATH];
  1065. //
  1066. // Now copy the filename into the buffer for use with OpenFile
  1067. // and then copy szDir from path to bookmarks and truncate it at filename
  1068. // so it contains the initial working directory for the dialog
  1069. //
  1070. StrCpyN(szFile, pszFileName, ARRAYSIZE(szFile));
  1071. StrCpyN(szDir, pszPathToBookmarks, ARRAYSIZE(szDir));
  1072. szDir[pszFileName-pszPathToBookmarks] = TEXT('\0');
  1073. //
  1074. // Use common dialog code to get path to folder
  1075. //
  1076. TCHAR filter[] = TEXT("HTML File\0*.HTM\0All Files\0*.*\0");
  1077. OPENFILENAME ofn = {0};
  1078. ofn.lStructSize = sizeof(ofn);
  1079. ofn.hwndOwner = hwnd;
  1080. ofn.hInstance = HINST_THISDLL;
  1081. ofn.lpstrFilter = filter;
  1082. ofn.lpstrFile = szFile;
  1083. ofn.nMaxFile = ARRAYSIZE(szFile);
  1084. ofn.lpstrInitialDir = szDir;
  1085. ofn.lpstrDefExt = TEXT("htm");
  1086. if (dialogType == FILE_SAVE_DIALOG)
  1087. {
  1088. MLLoadString(IDS_EXPORTDIALOGTITLE, szDialogTitle, ARRAYSIZE(szDialogTitle));
  1089. ofn.lpstrTitle = szDialogTitle;
  1090. ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
  1091. if (GetSaveFileName(&ofn))
  1092. {
  1093. StrCpyN(pszPathToBookmarks, szFile, cchPathToBookmarks);
  1094. return TRUE;
  1095. }
  1096. }
  1097. else
  1098. {
  1099. MLLoadString(IDS_IMPORTDIALOGTITLE, szDialogTitle, ARRAYSIZE(szDialogTitle));
  1100. ofn.lpstrTitle = szDialogTitle;
  1101. ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
  1102. if (GetOpenFileName(&ofn))
  1103. {
  1104. StrCpyN(pszPathToBookmarks, szFile, cchPathToBookmarks);
  1105. return TRUE;
  1106. }
  1107. }
  1108. return FALSE;
  1109. }
  1110. HRESULT CreateILFromPath(LPCTSTR pszPath, LPITEMIDLIST* ppidl)
  1111. {
  1112. // ASSERT(pszPath);
  1113. // ASSERT(ppidl);
  1114. HRESULT hr;
  1115. IShellFolder* pIShellFolder;
  1116. hr = SHGetDesktopFolder(&pIShellFolder);
  1117. if (SUCCEEDED(hr))
  1118. {
  1119. // ASSERT(pIShellFolder);
  1120. WCHAR wszPath[MAX_PATH];
  1121. if (SHTCharToUnicode(pszPath, wszPath, ARRAYSIZE(wszPath)))
  1122. {
  1123. ULONG ucch;
  1124. hr = pIShellFolder->ParseDisplayName(NULL, NULL, wszPath, &ucch,
  1125. ppidl, NULL);
  1126. }
  1127. else
  1128. {
  1129. hr = E_FAIL;
  1130. }
  1131. pIShellFolder->Release();
  1132. }
  1133. return hr;
  1134. }
  1135. #define REG_STR_IMPEXP TEXT("Software\\Microsoft\\Internet Explorer\\Main")
  1136. #define REG_STR_PATHTOFAVORITES TEXT("FavoritesImportFolder")
  1137. #define REG_STR_PATHTOBOOKMARKS TEXT("FavoritesExportFile")
  1138. #define REG_STR_DESKTOP TEXT("Desktop")
  1139. #define REG_STR_SHELLFOLDERS TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders")
  1140. #ifndef UNIX
  1141. #define STR_BOOKMARK_FILE TEXT("\\bookmark.htm")
  1142. #else
  1143. #define STR_BOOKMARK_FILE TEXT("/bookmark.html")
  1144. #endif
  1145. //
  1146. // InitializePaths
  1147. //
  1148. void InitializePaths()
  1149. {
  1150. //
  1151. // Read the Netscape users bookmark file location and the
  1152. // current users favorite path from registry
  1153. //
  1154. if (!GetNavBkMkDir(g_szPathToBookmarks, MAX_PATH))
  1155. {
  1156. //
  1157. // If Nav isn't installed then use the desktop
  1158. //
  1159. GetPathFromRegistry(g_szPathToBookmarks, MAX_PATH, HKEY_CURRENT_USER,
  1160. REG_STR_SHELLFOLDERS, REG_STR_DESKTOP);
  1161. StrCatBuff(g_szPathToBookmarks, STR_BOOKMARK_FILE, ARRAYSIZE(g_szPathToBookmarks));
  1162. }
  1163. GetTargetFavoritesPath(g_szPathToFavorites, MAX_PATH);
  1164. if (FAILED(CreateILFromPath(g_szPathToFavorites, &g_pidlFavorites)))
  1165. g_pidlFavorites = NULL;
  1166. //
  1167. // Now override these values with values stored in the registry just for
  1168. // this tool, so if the user consistently wants to save their favorites
  1169. // out to a separate .HTM file its easy to do
  1170. //
  1171. HKEY hKey;
  1172. DWORD dwSize;
  1173. DWORD dwType;
  1174. if (RegOpenKeyEx(HKEY_CURRENT_USER, REG_STR_IMPEXP, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
  1175. {
  1176. // dsheldon: Setting dwType before RegQueryValueEx doesn't do anything. Should we check it afterwards?
  1177. dwSize = sizeof g_szPathToBookmarks;
  1178. dwType = REG_SZ;
  1179. RegQueryValueEx(hKey, REG_STR_PATHTOBOOKMARKS, 0, &dwType, (LPBYTE)g_szPathToBookmarks, &dwSize);
  1180. dwSize = sizeof g_szPathToFavorites;
  1181. dwType = REG_SZ;
  1182. RegQueryValueEx(hKey, REG_STR_PATHTOFAVORITES, 0, &dwType, (LPBYTE)g_szPathToFavorites, &dwSize);
  1183. RegCloseKey(hKey);
  1184. }
  1185. }
  1186. void PersistPaths()
  1187. {
  1188. HKEY hKey;
  1189. DWORD dwDisp;
  1190. if (RegCreateKeyEx(HKEY_CURRENT_USER, REG_STR_IMPEXP, 0, NULL, 0, KEY_SET_VALUE, NULL, &hKey, &dwDisp) == ERROR_SUCCESS)
  1191. {
  1192. RegSetValueEx(hKey, REG_STR_PATHTOBOOKMARKS, 0, REG_SZ, (LPBYTE)g_szPathToBookmarks, (lstrlen(g_szPathToBookmarks)+1)*sizeof(TCHAR));
  1193. RegSetValueEx(hKey, REG_STR_PATHTOFAVORITES, 0, REG_SZ, (LPBYTE)g_szPathToFavorites, (lstrlen(g_szPathToFavorites)+1)*sizeof(TCHAR));
  1194. RegCloseKey(hKey);
  1195. }
  1196. }
  1197. #define REG_STR_IE_POLICIES TEXT("Software\\Policies\\Microsoft\\Internet Explorer")
  1198. #define REG_STR_IMPEXP_POLICIES TEXT("DisableImportExportFavorites")
  1199. BOOL IsImportExportDisabled(void)
  1200. {
  1201. HKEY hKey;
  1202. DWORD dwSize = sizeof(DWORD);
  1203. DWORD dwType;
  1204. DWORD value = 0;
  1205. BOOL bret = FALSE;
  1206. if (RegOpenKeyEx(HKEY_CURRENT_USER, REG_STR_IE_POLICIES, 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
  1207. {
  1208. if (RegQueryValueEx(hKey, REG_STR_IMPEXP_POLICIES, 0, &dwType, (PBYTE)&value, &dwSize) == ERROR_SUCCESS &&
  1209. (dwType == REG_BINARY || dwType == REG_DWORD))
  1210. bret = (value) ? TRUE : FALSE;
  1211. RegCloseKey(hKey);
  1212. }
  1213. return bret;
  1214. }
  1215. void DoImportOrExport(BOOL fImport, LPCWSTR pwszPath, LPCWSTR pwszImpExpPath, BOOL fConfirm)
  1216. {
  1217. BOOL fRemote = FALSE;
  1218. HWND hwnd = NULL;
  1219. TCHAR szImpExpPath[INTERNET_MAX_URL_LENGTH];
  1220. //
  1221. // REVIEW should this be passed in...
  1222. //
  1223. hwnd = GetActiveWindow();
  1224. // Decide if import/export is allowed here
  1225. if (IsImportExportDisabled())
  1226. {
  1227. MLShellMessageBox(
  1228. hwnd,
  1229. (fImport) ? MAKEINTRESOURCE(IDS_IMPORT_DISABLED) :
  1230. MAKEINTRESOURCE(IDS_EXPORT_DISABLED),
  1231. (fImport) ? MAKEINTRESOURCE(IDS_CONFIRM_IMPTTL_FAV) :
  1232. MAKEINTRESOURCE(IDS_CONFIRM_EXPTTL_FAV),
  1233. MB_OK);
  1234. return;
  1235. }
  1236. InitializePaths();
  1237. //
  1238. // Overwrite path to favorites with passed in one if present
  1239. //
  1240. if (pwszPath && *pwszPath != 0)
  1241. {
  1242. SHUnicodeToTChar(pwszPath, g_szPathToFavorites, ARRAYSIZE(g_szPathToFavorites));
  1243. }
  1244. //
  1245. // Decide if we export/import to/from an URL? or a file
  1246. // (we expect pwszImpExpPath an absolute path)
  1247. // if it's not a valid URL or filename, we give error message and bail out
  1248. //
  1249. if (pwszImpExpPath && *pwszImpExpPath != 0)
  1250. {
  1251. SHUnicodeToTChar(pwszImpExpPath, szImpExpPath, ARRAYSIZE(szImpExpPath));
  1252. if (PathIsURL(pwszImpExpPath))
  1253. {
  1254. TCHAR szDialogTitle[MAX_PATH];
  1255. TCHAR szfmt[MAX_PATH], szmsg[MAX_PATH+INTERNET_MAX_URL_LENGTH];
  1256. fRemote = TRUE;
  1257. if (fImport)
  1258. {
  1259. if (fConfirm)
  1260. {
  1261. //
  1262. // Show confirmation UI when importing over internet
  1263. //
  1264. MLLoadShellLangString(IDS_CONFIRM_IMPTTL_FAV, szDialogTitle, ARRAYSIZE(szDialogTitle));
  1265. MLLoadShellLangString(IDS_CONFIRM_IMPORT, szfmt, ARRAYSIZE(szfmt));
  1266. wnsprintf(szmsg, ARRAYSIZE(szmsg), szfmt, szImpExpPath);
  1267. if (MLShellMessageBox(hwnd, szmsg, szDialogTitle,
  1268. MB_YESNO | MB_ICONQUESTION) == IDNO)
  1269. return;
  1270. }
  1271. // download imported file to cache
  1272. if ( (IsGlobalOffline() && !InternetGoOnline(g_szPathToBookmarks,hwnd,0)) ||
  1273. FAILED(URLDownloadToCacheFile(NULL, szImpExpPath, g_szPathToBookmarks, MAX_PATH, 0, NULL)))
  1274. {
  1275. MLShellMessageBox(
  1276. hwnd,
  1277. MAKEINTRESOURCE(IDS_IMPORTFAILURE_FAV),
  1278. MAKEINTRESOURCE(IDS_CONFIRM_IMPTTL_FAV),
  1279. MB_OK);
  1280. return;
  1281. }
  1282. }
  1283. else
  1284. {
  1285. if (fConfirm)
  1286. {
  1287. //
  1288. // Show confirmation UI when exporting over internet
  1289. //
  1290. MLLoadShellLangString(IDS_CONFIRM_EXPTTL_FAV, szDialogTitle, ARRAYSIZE(szDialogTitle));
  1291. MLLoadShellLangString(IDS_CONFIRM_EXPORT, szfmt, ARRAYSIZE(szfmt));
  1292. wnsprintf(szmsg, ARRAYSIZE(szmsg), szfmt, szImpExpPath);
  1293. if (MLShellMessageBox(hwnd, szmsg, szDialogTitle,
  1294. MB_YESNO | MB_ICONQUESTION) == IDNO)
  1295. return;
  1296. }
  1297. //
  1298. // Create bookmark file name from bookmark directory with favorite name so we can export
  1299. // favorites to local file before posting to URL
  1300. //
  1301. TCHAR *pszFav = PathFindFileName(g_szPathToFavorites);
  1302. TCHAR *pszBMD = PathFindFileName(g_szPathToBookmarks);
  1303. if (pszFav && pszBMD)
  1304. {
  1305. StrCpyN(pszBMD, pszFav, ARRAYSIZE(g_szPathToBookmarks) - ((int)(pszBMD - g_szPathToBookmarks)));
  1306. StrCatBuff(pszBMD, TEXT(".htm"), ARRAYSIZE(g_szPathToBookmarks) - ((int)(pszBMD - g_szPathToBookmarks)));
  1307. }
  1308. }
  1309. }
  1310. else
  1311. {
  1312. if (fConfirm)
  1313. {
  1314. TCHAR szDialogTitle[MAX_PATH];
  1315. TCHAR szfmt[MAX_PATH], szmsg[MAX_PATH+INTERNET_MAX_URL_LENGTH];
  1316. if (fImport)
  1317. {
  1318. //
  1319. // Show confirmation UI when importing
  1320. //
  1321. MLLoadShellLangString(IDS_CONFIRM_IMPTTL_FAV, szDialogTitle, ARRAYSIZE(szDialogTitle));
  1322. MLLoadShellLangString(IDS_CONFIRM_IMPORT, szfmt, ARRAYSIZE(szfmt));
  1323. wnsprintf(szmsg, ARRAYSIZE(szmsg), szfmt, szImpExpPath);
  1324. if (MLShellMessageBox(hwnd, szmsg, szDialogTitle,
  1325. MB_YESNO | MB_ICONQUESTION) == IDNO)
  1326. return;
  1327. }
  1328. else
  1329. {
  1330. //
  1331. // Show confirmation UI when exporting.
  1332. //
  1333. MLLoadShellLangString(IDS_CONFIRM_EXPTTL_FAV, szDialogTitle, ARRAYSIZE(szDialogTitle));
  1334. MLLoadShellLangString(IDS_CONFIRM_EXPORT, szfmt, ARRAYSIZE(szfmt));
  1335. wnsprintf(szmsg, ARRAYSIZE(szmsg), szfmt, szImpExpPath);
  1336. if (MLShellMessageBox(hwnd, szmsg, szDialogTitle,
  1337. MB_YESNO | MB_ICONQUESTION) == IDNO)
  1338. return;
  1339. }
  1340. }
  1341. if (PathFindFileName(szImpExpPath) != szImpExpPath)
  1342. {
  1343. //override path to bookmarks with passed in one
  1344. StrCpyN(g_szPathToBookmarks, szImpExpPath, ARRAYSIZE(g_szPathToBookmarks));
  1345. }
  1346. else
  1347. {
  1348. MLShellMessageBox(
  1349. hwnd,
  1350. MAKEINTRESOURCE(IDS_IMPORTFAILURE_FAV),
  1351. MAKEINTRESOURCE(IDS_CONFIRM_IMPTTL_FAV),
  1352. MB_OK);
  1353. return;
  1354. }
  1355. }
  1356. }
  1357. else
  1358. {
  1359. if (fImport)
  1360. {
  1361. //
  1362. // Do Import Favorites UI
  1363. //
  1364. if (!BrowseForBookmarks(g_szPathToBookmarks, ARRAYSIZE(g_szPathToBookmarks), hwnd, FILE_OPEN_DIALOG))
  1365. return;
  1366. }
  1367. else
  1368. {
  1369. //
  1370. // Do Export Favorites UI
  1371. //
  1372. if (!BrowseForBookmarks(g_szPathToBookmarks, ARRAYSIZE(g_szPathToBookmarks), hwnd, FILE_SAVE_DIALOG))
  1373. return;
  1374. }
  1375. }
  1376. if (fImport)
  1377. {
  1378. if (ImportBookmarks(g_szPathToFavorites, g_szPathToBookmarks, hwnd))
  1379. {
  1380. MLShellMessageBox(
  1381. hwnd,
  1382. MAKEINTRESOURCE(IDS_IMPORTSUCCESS_FAV),
  1383. MAKEINTRESOURCE(IDS_CONFIRM_IMPTTL_FAV),
  1384. MB_OK);
  1385. #ifdef UNIX
  1386. SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH | SHCNF_FLUSH, g_szPathToFavorites, 0);
  1387. #endif
  1388. if (!fRemote)
  1389. PersistPaths();
  1390. }
  1391. else
  1392. {
  1393. ; // ImportBookmarks will report errors
  1394. }
  1395. }
  1396. else
  1397. {
  1398. if (ExportFavorites(g_szPathToFavorites, g_szPathToBookmarks, hwnd))
  1399. {
  1400. if (fRemote)
  1401. {
  1402. if ( (!IsGlobalOffline() || InternetGoOnline(g_szPathToBookmarks,hwnd,0)) &&
  1403. PostFavorites(g_szPathToBookmarks, szImpExpPath))
  1404. {
  1405. MLShellMessageBox(
  1406. hwnd,
  1407. MAKEINTRESOURCE(IDS_EXPORTSUCCESS_FAV),
  1408. MAKEINTRESOURCE(IDS_CONFIRM_EXPTTL_FAV),
  1409. MB_OK);
  1410. }
  1411. else
  1412. MLShellMessageBox(
  1413. hwnd,
  1414. MAKEINTRESOURCE(IDS_EXPORTFAILURE_FAV),
  1415. MAKEINTRESOURCE(IDS_CONFIRM_EXPTTL_FAV),
  1416. MB_OK);
  1417. //Remove temp file on local disk
  1418. DeleteFile(g_szPathToBookmarks);
  1419. }
  1420. else
  1421. {
  1422. MLShellMessageBox(
  1423. hwnd,
  1424. MAKEINTRESOURCE(IDS_EXPORTSUCCESS_FAV),
  1425. MAKEINTRESOURCE(IDS_CONFIRM_EXPTTL_FAV),
  1426. MB_OK);
  1427. PersistPaths();
  1428. }
  1429. }
  1430. else
  1431. {
  1432. MLShellMessageBox(
  1433. hwnd,
  1434. MAKEINTRESOURCE(IDS_EXPORTFAILURE_FAV),
  1435. MAKEINTRESOURCE(IDS_CONFIRM_EXPTTL_FAV),
  1436. MB_OK);
  1437. }
  1438. }
  1439. }
  1440. //
  1441. // *** POST FAVORITES HTML FILE ***
  1442. //
  1443. HINTERNET g_hInternet = 0;
  1444. HINTERNET g_hConnect = 0;
  1445. HINTERNET g_hHttpRequest = 0;
  1446. HANDLE g_hEvent = NULL;
  1447. typedef struct AsyncRes
  1448. {
  1449. DWORD_PTR Result;
  1450. DWORD_PTR Error;
  1451. } ASYNCRES;
  1452. #define STR_USERAGENT "PostFavorites"
  1453. void CloseRequest(void)
  1454. {
  1455. if (g_hHttpRequest)
  1456. InternetCloseHandle(g_hHttpRequest);
  1457. if (g_hConnect)
  1458. InternetCloseHandle(g_hConnect);
  1459. if (g_hInternet)
  1460. InternetCloseHandle(g_hInternet);
  1461. g_hInternet = g_hConnect = g_hHttpRequest = 0;
  1462. }
  1463. HRESULT InitRequest(LPSTR pszPostURL, BOOL bAsync, ASYNCRES *pasyncres)
  1464. {
  1465. char hostName[INTERNET_MAX_HOST_NAME_LENGTH+1];
  1466. char userName[INTERNET_MAX_USER_NAME_LENGTH+1];
  1467. char password[INTERNET_MAX_PASSWORD_LENGTH+1];
  1468. char urlPath[INTERNET_MAX_PATH_LENGTH+1];
  1469. URL_COMPONENTSA uc;
  1470. memset(&uc, 0, sizeof(URL_COMPONENTS));
  1471. uc.dwStructSize = sizeof(URL_COMPONENTS);
  1472. uc.lpszHostName = hostName;
  1473. uc.dwHostNameLength = sizeof(hostName);
  1474. uc.nPort = INTERNET_INVALID_PORT_NUMBER;
  1475. uc.lpszUserName = userName;
  1476. uc.dwUserNameLength = sizeof(userName);
  1477. uc.lpszPassword = password;
  1478. uc.dwPasswordLength = sizeof(password);
  1479. uc.lpszUrlPath = urlPath;
  1480. uc.dwUrlPathLength = sizeof(urlPath);
  1481. if (!InternetCrackUrlA(pszPostURL,lstrlenA(pszPostURL),ICU_DECODE, &uc))
  1482. {
  1483. return E_FAIL;
  1484. }
  1485. if (bAsync)
  1486. {
  1487. // Create an auto-reset event
  1488. g_hEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
  1489. if (g_hEvent == NULL)
  1490. bAsync = FALSE;
  1491. }
  1492. g_hInternet = InternetOpenA(STR_USERAGENT, // used in User-Agent: header
  1493. INTERNET_OPEN_TYPE_PRECONFIG, //INTERNET_OPEN_TYPE_DIRECT,
  1494. NULL,
  1495. NULL,
  1496. (bAsync) ? INTERNET_FLAG_ASYNC : 0
  1497. );
  1498. if ( !g_hInternet )
  1499. {
  1500. return E_FAIL;
  1501. }
  1502. if (bAsync)
  1503. {
  1504. if (INTERNET_INVALID_STATUS_CALLBACK == InternetSetStatusCallbackA(g_hInternet, StatusCallback))
  1505. return E_FAIL;
  1506. }
  1507. // Connect to host
  1508. g_hConnect = InternetConnectA(g_hInternet,
  1509. uc.lpszHostName,
  1510. uc.nPort, //INTERNET_INVALID_PORT_NUMBER,
  1511. uc.lpszUserName,
  1512. uc.lpszPassword,
  1513. INTERNET_SERVICE_HTTP,
  1514. 0, //INTERNET_FLAG_KEEP_CONNECTION,
  1515. (bAsync)? (DWORD_PTR) pasyncres : 0);
  1516. if ( !g_hConnect )
  1517. {
  1518. if (bAsync && GetLastError() == ERROR_IO_PENDING)
  1519. {
  1520. WaitForSingleObject(g_hEvent, INFINITE);
  1521. if (pasyncres->Result == 0)
  1522. return E_FAIL;
  1523. g_hConnect = (HINTERNET)pasyncres->Result;
  1524. }
  1525. else
  1526. return E_FAIL;
  1527. }
  1528. // Create request.
  1529. g_hHttpRequest = HttpOpenRequestA
  1530. (
  1531. g_hConnect,
  1532. "POST",
  1533. uc.lpszUrlPath,
  1534. HTTP_VERSIONA,
  1535. NULL, //lpszReferer
  1536. NULL, //lpszAcceptTypes
  1537. INTERNET_FLAG_RELOAD
  1538. | INTERNET_FLAG_KEEP_CONNECTION
  1539. | SECURITY_INTERNET_MASK, // ignore SSL warnings
  1540. (bAsync)? (DWORD_PTR) pasyncres : 0);
  1541. if ( !g_hHttpRequest )
  1542. {
  1543. if (bAsync && GetLastError() == ERROR_IO_PENDING)
  1544. {
  1545. WaitForSingleObject(g_hEvent, INFINITE);
  1546. if (pasyncres->Result == 0)
  1547. return E_FAIL;
  1548. g_hHttpRequest = (HINTERNET)pasyncres->Result;
  1549. }
  1550. else
  1551. return E_FAIL;
  1552. }
  1553. return S_OK;
  1554. }
  1555. const char c_szHeaders[] = "Content-Type: application/x-www-form-urlencoded\r\n";
  1556. #define c_ccHearders (ARRAYSIZE(c_szHeaders) - 1)
  1557. BOOL AddRequestHeaders
  1558. (
  1559. LPCSTR lpszHeaders,
  1560. DWORD dwHeadersLength,
  1561. DWORD dwAddFlag,
  1562. BOOL bAsync,
  1563. ASYNCRES *pasyncres
  1564. )
  1565. {
  1566. BOOL bRet = FALSE;
  1567. bRet = HttpAddRequestHeadersA(g_hHttpRequest,
  1568. lpszHeaders,
  1569. dwHeadersLength,
  1570. HTTP_ADDREQ_FLAG_ADD | dwAddFlag);
  1571. if (bAsync && !bRet && GetLastError() == ERROR_IO_PENDING)
  1572. {
  1573. WaitForSingleObject(g_hEvent, INFINITE);
  1574. bRet = (BOOL)pasyncres->Result;
  1575. }
  1576. return bRet;
  1577. }
  1578. HRESULT SendRequest
  1579. (
  1580. LPCSTR lpszHeaders,
  1581. DWORD dwHeadersLength,
  1582. LPCSTR lpszOption,
  1583. DWORD dwOptionLength,
  1584. BOOL bAsync,
  1585. ASYNCRES *pasyncres
  1586. )
  1587. {
  1588. BOOL bRet=FALSE;
  1589. bRet = AddRequestHeaders((LPCSTR)c_szHeaders, (DWORD)-1L, 0, bAsync, pasyncres);
  1590. if (lpszHeaders && *lpszHeaders) // don't bother if it's empty
  1591. {
  1592. bRet = AddRequestHeaders(
  1593. (LPCSTR)lpszHeaders,
  1594. dwHeadersLength,
  1595. HTTP_ADDREQ_FLAG_REPLACE,
  1596. bAsync,
  1597. pasyncres);
  1598. if ( !bRet )
  1599. {
  1600. return E_FAIL;
  1601. }
  1602. }
  1603. pasyncres->Result = 0;
  1604. bRet = HttpSendRequestA(g_hHttpRequest,
  1605. NULL, //HEADER_ENCTYPE,
  1606. 0, //sizeof(HEADER_ENCTYPE),
  1607. (LPVOID)lpszOption,
  1608. dwOptionLength);
  1609. if ( !bRet )
  1610. {
  1611. DWORD_PTR dwLastError = GetLastError();
  1612. if (bAsync && dwLastError == ERROR_IO_PENDING)
  1613. {
  1614. WaitForSingleObject(g_hEvent, INFINITE);
  1615. dwLastError = pasyncres->Error;
  1616. bRet = (BOOL)pasyncres->Result;
  1617. if (!bRet)
  1618. {
  1619. TraceMsg(DM_ERROR, "Async HttpSendRequest returned FALSE");
  1620. if (dwLastError != ERROR_SUCCESS)
  1621. {
  1622. TraceMsg(DM_ERROR, "Async HttpSendRequest failed: Error = %lx", dwLastError);
  1623. return E_FAIL;
  1624. }
  1625. }
  1626. }
  1627. else
  1628. {
  1629. TraceMsg(DM_ERROR, "HttpSendRequest failed: Error = %lx", dwLastError);
  1630. return E_FAIL;
  1631. }
  1632. }
  1633. //
  1634. //verify request response here
  1635. //
  1636. DWORD dwBuffLen;
  1637. TCHAR buff[10];
  1638. dwBuffLen = sizeof(buff);
  1639. bRet = HttpQueryInfo(g_hHttpRequest,
  1640. HTTP_QUERY_STATUS_CODE, //HTTP_QUERY_RAW_HEADERS,
  1641. buff,
  1642. &dwBuffLen,
  1643. NULL);
  1644. int iretcode = StrToInt(buff);
  1645. TraceMsg(DM_TRACE, "HttpQueryInfo returned %d", iretcode);
  1646. return (iretcode == HTTP_STATUS_OK) ?
  1647. S_OK : E_FAIL;
  1648. }
  1649. DWORD ReadFavoritesFile(LPCTSTR lpFile, LPSTR* lplpbuf)
  1650. {
  1651. HANDLE hFile = NULL;
  1652. DWORD cbFile = 0;
  1653. DWORD cbRead;
  1654. hFile = CreateFile(lpFile,
  1655. GENERIC_READ,
  1656. 0, //no sharing
  1657. NULL,
  1658. OPEN_EXISTING,
  1659. FILE_ATTRIBUTE_NORMAL,
  1660. NULL);
  1661. if (hFile == INVALID_HANDLE_VALUE)
  1662. return 0;
  1663. cbFile = GetFileSize(hFile, NULL);
  1664. if (cbFile == 0xFFFFFFFF)
  1665. {
  1666. CloseHandle(hFile);
  1667. return 0;
  1668. }
  1669. *lplpbuf = (LPSTR)GlobalAlloc(LPTR, (cbFile + 2) * sizeof(CHAR));
  1670. cbRead = 0;
  1671. if (!*lplpbuf || !ReadFile(hFile, *lplpbuf, cbFile, &cbRead, NULL))
  1672. {
  1673. cbRead = 0;
  1674. }
  1675. ASSERT((cbRead == cbFile));
  1676. CloseHandle(hFile);
  1677. return cbRead;
  1678. }
  1679. BOOL PostFavorites(TCHAR *pszPathToBookmarks, TCHAR* pszPathToPost)
  1680. {
  1681. DWORD cbRead = 0;
  1682. LPSTR lpbuf = NULL;
  1683. BOOL bret = FALSE;
  1684. BOOL bAsync = TRUE;
  1685. CHAR szPathToPost[INTERNET_MAX_URL_LENGTH];
  1686. ASYNCRES asyncres = {0, 0};
  1687. cbRead = ReadFavoritesFile(pszPathToBookmarks, &lpbuf);
  1688. if (cbRead == 0)
  1689. {
  1690. if (lpbuf)
  1691. {
  1692. GlobalFree(lpbuf);
  1693. lpbuf = NULL;
  1694. }
  1695. return TRUE;
  1696. }
  1697. SHTCharToAnsi(pszPathToPost, szPathToPost, ARRAYSIZE(szPathToPost));
  1698. if (SUCCEEDED(InitRequest(szPathToPost, bAsync, &asyncres)))
  1699. {
  1700. bret = (SUCCEEDED(SendRequest(NULL, lstrlenA(""), lpbuf, cbRead, bAsync, &asyncres)));
  1701. }
  1702. CloseRequest();
  1703. if (lpbuf)
  1704. {
  1705. GlobalFree( lpbuf );
  1706. lpbuf = NULL;
  1707. }
  1708. return bret;
  1709. }
  1710. //
  1711. // Callback function for Asynchronous HTTP POST request
  1712. //
  1713. void CALLBACK StatusCallback(
  1714. HINTERNET hInternet,
  1715. DWORD_PTR dwContext,
  1716. DWORD dwStatus,
  1717. LPVOID lpvInfo,
  1718. DWORD dwInfoLength
  1719. )
  1720. {
  1721. switch (dwStatus)
  1722. {
  1723. case INTERNET_STATUS_REQUEST_COMPLETE:
  1724. {
  1725. ASYNCRES *pasyncres = (ASYNCRES *)dwContext;
  1726. pasyncres->Result = ((LPINTERNET_ASYNC_RESULT)lpvInfo)->dwResult;
  1727. pasyncres->Error = ((LPINTERNET_ASYNC_RESULT)lpvInfo)->dwError;
  1728. SetEvent(g_hEvent);
  1729. }
  1730. break;
  1731. default:
  1732. break;
  1733. }
  1734. }