1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
|
//This file is part of Msg_Export a Miranda IM plugin
//Copyright (C)2002 Kennet Nielsen ( http://sourceforge.net/projects/msg-export/ )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
// Default error string used upon errors
const wchar_t *pszGroupError = LPGENW("No_Group");
const wchar_t *pszDbPathError = L".";
// Replacement for characters not allowed in file names.
const wchar_t cBadCharReplace = '_';
// g_sTimeFormat
wstring g_sTimeFormat;
// path from options dialog
wstring g_sExportDir;
// The default filename. Used if no other file name is specified in DB.
wstring g_sDefaultFile;
// path used then %dbpath% is used in export file path
wstring g_sDBPath = pszDbPathError;
// path to miranda exe file used when to avoid relative paths
wstring g_sMirandaPath = pszDbPathError;
// Used to store the width of the user name for a file.
// if a file contains events from many users the one user name
// may be shorter. so to make all event have the same first
// column width this map contains the largest user name
map<wstring, string::size_type, less<wstring> > clFileTo1ColWidth;
// default line width
int nMaxLineWidth = 80;
// This enum define the actions which MsgExport must take when a File is renamed
ENDialogAction g_enRenameAction;
// This enum define the actions which MsgExport must take when a user is delete
ENDialogAction g_enDeleteAction;
bool g_bUseJson;
DATABASELINK *g_pDriver = nullptr;
/////////////////////////////////////////////////////////////////////
// Member Function : nGetFormatCount
// Type : Global
// Parameters : pszToCheck - ?
// Returns : int
int nGetFormatCount(const wchar_t *pszToCheck)
{
if (!pszToCheck || pszToCheck[0] == 0)
return 0;
int nCount = 0;
for (; pszToCheck[1] != 0; pszToCheck++) {
if (pszToCheck[0] == '%' && pszToCheck[1] != '%')
nCount++;
}
return nCount;
}
/////////////////////////////////////////////////////////////////////
// Member Function : _DBGetStringW
// Type : Global
// Parameters : hContact - ?
// szModule - ?
// szSetting - ?
// pszError - ?
// Returns : string
// Description : Reads a string from the database
// Just like those in database.h
wstring _DBGetStringW(MCONTACT hContact, const char *szModule, const char *szSetting, const wchar_t *pszError)
{
DBVARIANT dbv = { 0 };
if (db_get_ws(hContact, szModule, szSetting, &dbv))
return pszError;
wstring ret = dbv.pwszVal;
db_free(&dbv);
return ret;
}
/////////////////////////////////////////////////////////////////////
// Member Function : ReplaceAll
// Type : Global
// Parameters : sSrc - string to replace in
// pszReplace - what to replace
// sNew - the string to insert instead of pszReplace
// Returns : void
// Description : will replace all occurrences of a string with another string
// used to replace %user%, and other user
static void ReplaceAll(wstring &sSrc, const wchar_t *pszReplace, const wstring &sNew)
{
string::size_type nCur = 0;
while ((nCur = sSrc.find(pszReplace, nCur)) != sSrc.npos) {
sSrc.replace(nCur, mir_wstrlen(pszReplace), sNew);
nCur += sNew.size();
}
}
static void ReplaceAll(wstring &sSrc, const wchar_t *pszReplace, const wchar_t *pszNew)
{
wstring sNew = pszNew;
ReplaceAll(sSrc, pszReplace, sNew);
}
/////////////////////////////////////////////////////////////////////
// Member Function : sGetErrorString
// Type : Global
// Parameters : dwError - ?
// Returns : string
CMStringW sGetErrorString(uint32_t dwError)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR)&lpMsgBuf,
0,
nullptr);
// Process any inserts in lpMsgBuf.
// ...
// Display the string.
CMStringW ret((LPCTSTR)lpMsgBuf);
ret.Replace(L"\r", L" ");
ret.Replace(L"\n", L" ");
ret.Replace(L" ", L" ");
// Free the buffer.
LocalFree(lpMsgBuf);
return ret;
}
CMStringW sGetErrorString()
{
return sGetErrorString(GetLastError());
}
void LogLastError(const wchar_t *pszError)
{
uint32_t error = GetLastError();
CMStringW sError = pszError;
wchar_t szTemp[50];
mir_snwprintf(szTemp, L"MsgExport error\r\nErrorCode: %d\r\n", error);
sError += szTemp;
sError += sGetErrorString(error);
Netlib_LogW(nullptr, sError.c_str());
}
/////////////////////////////////////////////////////////////////////
// Member Function : nContactDeleted
// Type : Global
// Parameters : wparam - handle to the deleted Contact
// lparam - 0
// Returns : int
// Description : Called when an contact is about to be deleted
int nContactDeleted(WPARAM hContact, LPARAM)
{
HWND hInternalWindow = WindowList_Find(hInternalWindowList, hContact);
if (hInternalWindow)
CloseWindow(hInternalWindow);
if (g_enDeleteAction == eDANothing)
return 0;
wstring sFilePath = GetFilePathFromUser(hContact);
// Test if there is another user using this file
for (auto &hOtherContact : Contacts())
if (hContact != hOtherContact && sFilePath == GetFilePathFromUser(hOtherContact))
return 0; // we found another contact abort mission :-)
// Test to see if there is a file to delete
HANDLE hPrevFile = CreateFile(sFilePath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hPrevFile != INVALID_HANDLE_VALUE) {
CloseHandle(hPrevFile);
wchar_t szTemp[500];
mir_snwprintf(szTemp, L"%s\r\n%s", TranslateT("User has been deleted. Do you want to delete the file?"), sFilePath.c_str());
if (g_enDeleteAction == eDAAutomatic || MessageBox(nullptr, szTemp, MSG_BOX_TITEL, MB_YESNO) == IDYES) {
if (!DeleteFile(sFilePath.c_str())) {
mir_snwprintf(szTemp, L"%s\r\n%s", TranslateT("Failed to delete the file"), sFilePath.c_str());
LogLastError(szTemp);
}
}
}
return 0;
}
/////////////////////////////////////////////////////////////////////
wchar_t* GetMyOwnNick(MCONTACT hContact)
{
wchar_t *p = Contact::GetInfo(CNF_DISPLAY, NULL, Proto_GetBaseAccountName(hContact));
return (p != nullptr) ? p : mir_wstrdup(TranslateT("No_Nick"));
}
/////////////////////////////////////////////////////////////////////
// Member Function : bReadMirandaDirAndPath
// Type : Global
// Parameters : None
// Returns : void
// Description : Used to set the internal path.
// Handles the reading from the mirandaboot.ini to get the %dbpath%
bool bReadMirandaDirAndPath()
{
wchar_t szDBPath[MAX_PATH], tmp[MAX_PATH];
wcsncpy_s(szDBPath, pszDbPathError, _TRUNCATE);
PathToAbsoluteW(L"miranda32.exe", tmp);
g_sMirandaPath = tmp;
g_sMirandaPath.erase(g_sMirandaPath.find_last_of(L"\\"));
Profile_GetPathW(MAX_PATH, szDBPath);
g_sDBPath = szDBPath;
Profile_GetNameW(MAX_PATH, szDBPath);
g_sDBPath.append(L"\\").append(szDBPath);
g_sDBPath.erase(g_sDBPath.size() - 4);
return true;
}
/////////////////////////////////////////////////////////////////////
// Member Function : ReplaceDBPath
// Type : Global
// Parameters : sRet - ?
void ReplaceDBPath(wstring &sRet)
{
ReplaceAll(sRet, L"%dbpath%", g_sDBPath);
// Try to figure out if it is a relative path ( ..\..\MsgExport\ )
if (sRet.size() <= 2 || !(sRet[1] == ':' ||
(sRet[0] == '\\' && sRet[1] == '\\'))) {
// Relative path
// we will prepend the mirande exe path to avoid problems
// if the current directory changes ( User receives a file )
sRet = g_sMirandaPath + sRet;
}
}
/////////////////////////////////////////////////////////////////////
// Member Function : GetFilePathFromUser
// Type : Global
// Parameters : hContact - Handle to user
// Returns : string containing the complete file name and path
static bool CompareNoExt(const wstring &s1, const wstring &s2)
{
wstring t1(s1), t2(s2);
ReplaceAll(t1, L".txt.json", L".txt");
ReplaceAll(t2, L".txt.json", L".txt");
return t1 == t2;
}
wstring GetFilePathFromUser(MCONTACT hContact)
{
wstring sFilePath = g_sExportDir + _DBGetStringW(hContact, MODULENAME, "FileName", g_sDefaultFile.c_str());
if (g_bUseJson)
sFilePath += L".json";
bool bNickUsed = sFilePath.find(L"%nick%") != string::npos;
ReplaceDefines(hContact, sFilePath);
wstring sNoDBPath = sFilePath;
ReplaceTimeVariables(sFilePath);
ReplaceDBPath(sFilePath);
// Previous file name check to see if it has changed !!
wstring sPrevFileName = _DBGetStringW(hContact, MODULENAME, "PrevFileName", L"");
if (!CompareNoExt(sNoDBPath, sPrevFileName)) {
if (!sPrevFileName.empty()) {
ReplaceDBPath(sPrevFileName);
// Here we will try to avoid the (Unknown contact) in cases where the protocol for
// this user has been removed.
if (bNickUsed && Clist_GetContactDisplayName(hContact, GCDNF_NOMYHANDLE) == nullptr)
return sPrevFileName; // Then the filename must have changed from a correct path to one including the (Unknown contact)
// file name has changed
if (g_enRenameAction != eDANothing) {
// we can not use FILE_SHARE_DELETE because this is not supported by win 98 / ME
HANDLE hPrevFile = CreateFile(sPrevFileName.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hPrevFile != INVALID_HANDLE_VALUE) {
CloseHandle(hPrevFile);
wchar_t szTemp[500];
// There is a previous file we can move
// ask user ?
bool bTryRename;
if (g_enRenameAction != eDAAutomatic) {
wstring sRemoteUser = Clist_GetContactDisplayName(hContact);
mir_snwprintf(szTemp,
TranslateT("File name for the user \"%s\" has changed!\n\nfrom:\t%s\nto:\t%s\n\nDo you wish to rename file?"),
sRemoteUser.c_str(),
sPrevFileName.c_str(),
sFilePath.c_str());
bTryRename = MessageBox(nullptr, szTemp, MSG_BOX_TITEL, MB_YESNO) == IDYES;
}
else bTryRename = true;
if (bTryRename) {
if (!MoveFile(sPrevFileName.c_str(), sFilePath.c_str())) {
// this might be because the new path isn't created
// so we will try to create it
CreatePathToFileW(sFilePath.c_str());
while (!MoveFile(sPrevFileName.c_str(), sFilePath.c_str())) {
mir_snwprintf(szTemp,
TranslateT("Failed to rename file\n\nfrom:\t%s\nto:\t%s\n\nFailed with error: %s"),
sPrevFileName.c_str(),
sFilePath.c_str(),
sGetErrorString().c_str());
if (MessageBox(nullptr, szTemp, MSG_BOX_TITEL, MB_RETRYCANCEL) != IDRETRY)
break;
}
}
}
}
}
}
// Store the Filename used so that we can check if it changes.
g_plugin.setWString(hContact, "PrevFileName", sNoDBPath.c_str());
}
return sFilePath;
}
/////////////////////////////////////////////////////////////////////
// Member Function : FileNickFromHandle
// Type : Global
// Parameters : hContact - ?
// Returns : string
// Description : Replaces invalid file name chars
wstring FileNickFromHandle(MCONTACT hContact)
{
wstring ret = Clist_GetContactDisplayName(hContact);
string::size_type nCur = 0;
while ((nCur = ret.find_first_of(L":\\", nCur)) != ret.npos)
ret[nCur] = cBadCharReplace;
return ret;
}
/////////////////////////////////////////////////////////////////////
// Member Function : ReplaceAllNoColon
// Type : Global
// Parameters : sSrc - ?
// pszReplace - ?
// sNew - ?
// Returns : void
// Description : Removes any ':' in the new string
void ReplaceAllNoColon(wstring &sSrc, const wchar_t *pszReplace, wstring &sNew)
{
wstring::size_type nCur = 0;
while ((nCur = sNew.find_first_of(':', nCur)) != sNew.npos)
sNew[nCur] = cBadCharReplace;
ReplaceAll(sSrc, pszReplace, sNew);
}
/////////////////////////////////////////////////////////////////////
// Member Function : ReplaceDefines
// Type : Global
// Parameters : hContact - Handle to user
// sTarget - String with either %user% or %UIN%, to replace in
// Returns : void
static wstring GetUniqueId(MCONTACT hContact, const char *szProto)
{
ptrW uniqueId(Contact::GetInfo(CNF_UNIQUEID, hContact, szProto));
return (uniqueId == nullptr) ? L"(null)" : uniqueId;
}
void ReplaceDefines(MCONTACT hContact, wstring &sTarget)
{
const char *szProto = Proto_GetBaseAccountName(hContact);
if (sTarget.find(L"%nick%") != string::npos)
ReplaceAll(sTarget, L"%nick%", FileNickFromHandle(hContact));
if (sTarget.find(L"%UIN%") != string::npos) {
uint32_t dwUIN = db_get_dw(hContact, szProto, "UIN", 0);
wstring sReplaceUin;
if (dwUIN) {
wchar_t sTmp[20];
mir_snwprintf(sTmp, L"%d", dwUIN);
sReplaceUin = sTmp;
}
else sReplaceUin = GetUniqueId(hContact, szProto);
ReplaceAll(sTarget, L"%UIN%", sReplaceUin);
}
if (sTarget.find(L"%e-mail%") != string::npos) {
wstring sEMail = _DBGetStringW(hContact, szProto, "e-mail", L"");
if (sEMail.empty())
sEMail = FileNickFromHandle(hContact);
ReplaceAllNoColon(sTarget, L"%e-mail%", sEMail);
}
if (sTarget.find(L"%identifier%") != string::npos)
ReplaceAll(sTarget, L"%identifier%", GetUniqueId(hContact, szProto));
if (sTarget.find(L"%id%") != string::npos)
ReplaceAll(sTarget, L"%id%", GetUniqueId(hContact, szProto));
if (sTarget.find(L"%protocol%") != string::npos) {
wstring tmp = _DBGetStringW(hContact, "Protocol", "p", L"");
ReplaceAllNoColon(sTarget, L"%protocol%", tmp);
}
if (sTarget.find(L"%group%") != string::npos) {
wstring sGroup = _DBGetStringW(hContact, "CList", "Group", L"");
ReplaceAllNoColon(sTarget, L"%group%", sGroup);
}
// we don't touch the leading colon and \\ either
string::size_type nCur = 2;
while ((nCur = sTarget.find_first_of(L"/*?:<>|\"", nCur)) != sTarget.npos)
sTarget[nCur] = cBadCharReplace;
}
/////////////////////////////////////////////////////////////////////
// Member Function : ReplaceTimeVariables
// Type : Global
// Parameters : sRet - ?
void ReplaceTimeVariables(wstring &sRet)
{
if (sRet.find(L"%year%") != string::npos ||
sRet.find(L"%month%") != string::npos ||
sRet.find(L"%day%") != string::npos) {
SYSTEMTIME stTime;
GetLocalTime(&stTime);
wchar_t sTmp[20];
mir_snwprintf(sTmp, L"%d", stTime.wYear);
ReplaceAll(sRet, L"%year%", sTmp);
mir_snwprintf(sTmp, L"%.2d", stTime.wMonth);
ReplaceAll(sRet, L"%month%", sTmp);
mir_snwprintf(sTmp, L"%.2d", stTime.wDay);
ReplaceAll(sRet, L"%day%", sTmp);
}
}
/////////////////////////////////////////////////////////////////////
// Member Function : UpdateFileToColWidth
// Type : Global
// Parameters : None
// Returns : void
// Description : updates clFileTo1ColWidth,
void UpdateFileToColWidth()
{
clFileTo1ColWidth.clear();
for (auto &hContact : Contacts()) {
wstring sNick = Clist_GetContactDisplayName(hContact);
string::size_type &rnValue = clFileTo1ColWidth[GetFilePathFromUser(hContact)];
if (rnValue < sNick.size())
rnValue = sNick.size();
}
}
/////////////////////////////////////////////////////////////////////
// Member Function : DisplayErrorDialog
// Type : Global
// Parameters : pszError - ?
// sFile - ?
// dbei - ?
void DisplayErrorDialog(const wchar_t *pszError, wstring &sFilePath)
{
wstring sError = TranslateW(pszError);
sError += sFilePath;
sError += TranslateT("\nError: ");
sError += sGetErrorString();
sError += TranslateT("\nMessage has not been saved!\n");
sError += TranslateT("Do you wish to save debug information?");
MessageBox(nullptr, sError.c_str(), MSG_BOX_TITEL, MB_OK | MB_ICONERROR);
}
/////////////////////////////////////////////////////////////////////
// Member Function : nExportEvent
// Type : Global
// Parameters : wparam - handle to contact
// lparam - handle to the new DB event
// Returns : int
// Description : Called when an event is added to the DB
// Or from the Export All funktion
HANDLE openCreateFile(const wstring &sFilePath)
{
SetLastError(0);
HANDLE hFile = CreateFile(sFilePath.c_str(), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) {
// this might be because the path isent created
// so we will try to create it
if (!CreatePathToFileW(sFilePath.c_str()))
hFile = CreateFile(sFilePath.c_str(), GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
}
return hFile;
}
bool bIsExportEnabled(MCONTACT hContact)
{
if (!g_plugin.getByte(hContact, "EnableLog", 1))
return false;
const char *szProto = Proto_GetBaseAccountName(hContact);
char szTemp[500];
mir_snprintf(szTemp, "DisableProt_%s", szProto);
if (!g_plugin.getByte(szTemp, 1))
return false;
return true;
}
int nExportEvent(WPARAM hContact, LPARAM hDbEvent)
{
if (!bIsExportEnabled(hContact))
return 0;
// Open/create file for writing
wstring sFilePath = GetFilePathFromUser(hContact);
MDatabaseExport *pJson = nullptr;
HANDLE hFile;
if (g_bUseJson) {
pJson = g_pDriver->Export(sFilePath.c_str());
if (pJson == nullptr) {
DisplayErrorDialog(LPGENW("Failed to open or create file:\n"), sFilePath);
return 0;
}
hFile = pJson;
}
else {
hFile = openCreateFile(sFilePath);
if (hFile == INVALID_HANDLE_VALUE) {
DisplayErrorDialog(LPGENW("Failed to open or create file:\n"), sFilePath);
return 0;
}
}
// Write the event
bExportEvent(hContact, hDbEvent, hFile, sFilePath, false);
// Close the file
if (pJson) {
pJson->EndExport();
delete pJson;
}
else CloseHandle(hFile);
return 0;
}
|