summaryrefslogtreecommitdiffabout
path: root/pwmanager/pwmanager/csv.cpp
blob: 194edf245cba7d39feb94ffd0ddf5894e76aeb64 (plain)
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
/***************************************************************************
 *                                                                         *
 *   copyright (C) 2004 by Michael Buesch                                  *
 *   email: mbuesch@freenet.de                                             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License version 2        *
 *   as published by the Free Software Foundation.                         *
 *                                                                         *
 ***************************************************************************/

/***************************************************************************
 * copyright (C) 2004 by Ulf Schenk
 * This file is originaly based on version 1.1 of pwmanager
 * and was modified to run on embedded devices that run microkde
 * The original file version was 1.2
 * $Id$
 **************************************************************************/  

#include "csv.h"
#include "pwmdoc.h"
#include "pwmexception.h"

#include <kmessagebox.h>
#include <klocale.h>

#define MAX_CSV_FILE_SIZE	(50 * 1024 * 1024) // bytes


Csv::Csv(QWidget *_parent)
 : parent (_parent)
{
}

Csv::~Csv()
{
}

bool Csv::importData(const QString &filepath,
		     PwMDoc *doc)
{
	bool ret = true;
	QByteArray d;
	QFile f(filepath);
	if (!f.open(IO_ReadOnly)) {
		KMessageBox::error(parent,
				   i18n("Could not open file.\n"
					"Does the file exist?"),
				   i18n("Open error."));
		ret = false;
		goto out;
	}
	if (f.size() > MAX_CSV_FILE_SIZE) {
		KMessageBox::error(parent,
				   i18n("File too big.\nMaximum file size is 1 Byte.", "File too big.\nMaximum file size is %n Bytes.", MAX_CSV_FILE_SIZE),
				   i18n("File too big."));
		ret = false;
		goto out_close;
	}
	d = f.readAll();
	if (d.isEmpty()) {
		KMessageBox::error(parent,
				   i18n("Could not read file or file empty."),
				   i18n("Reading failed."));
		ret = false;
		goto out_close;
	}
	if (!doImport(d, doc)) {
		KMessageBox::error(parent,
				   i18n("Import failed.\n"
					"Corrupt CSV data format."),
				   i18n("File corrupt."));
		ret = false;
		goto out_close;
	}

out_close:
	f.close();
out:
	return ret;
}

bool Csv::doImport(const QByteArray &d,
		   PwMDoc *doc)
{
	PwMDataItem di;
	//US ENH: initialize all members:
	di.clear();

	int refIndex = 0;
	int ret;
	QCString s, curCat;
	int fieldIndex = 0;
	bool inRecord = false;
	/* fieldIndex is a reference count to see which
	 * value we are attaching to di.
	 * Valid counts are:
	 * 0 -> category
	 * 1 -> desc
	 * 2 -> name
	 * 3 -> pw
	 * 4 -> url
	 * 5 -> launcher
	 * 6 -> comment
	 */

	while (1) {
		ret = nextField(&s, d, inRecord, &refIndex);
		switch (ret) {
		case 0:
			// successfully got next field.
			inRecord = true;
			switch (fieldIndex) {
			case 0: // category
				if (s.isEmpty()) {
					/* This is special case. It's the category
					 * list terminating empty field.
					 */
					++fieldIndex;
				} else
					curCat = s;
				break;
			case 1:	// desc
				di.desc = s;
				++fieldIndex;
				break;
			case 2: // name
				di.name = s;
				++fieldIndex;
				break;
			case 3: // pw
				di.pw = s;
				++fieldIndex;
				break;
			case 4: // url
				di.url = s;
				++fieldIndex;
				break;
			case 5: // launcher
				di.launcher = s;
				++fieldIndex;
				break;
			case 6: // comment
				di.comment = s;
				++fieldIndex;
				break;
			default:
				/* Too many fields in a record.
				 * We simply throw it away.
				 */
				break;
			}
			break;
		case 1:
			// record complete.
			if (fieldIndex == 6)
				di.comment = s;
			inRecord = false;
			fieldIndex = 0;
			doc->addEntry(curCat, &di, true);
			//US ENH: clear di for the next row
			di.clear();
			break;
		case 2:
			// data completely parsed.
			doc->flagDirty();
			return true;
		case -1:
			// parse error
			doc->flagDirty();
			return false;
		}
	}
	BUG();
	return false;
}

int Csv::nextField(QCString *ret,
		   const QByteArray &in,
		   bool inRecord,
		   int *_refIndex)
{
	int rv = -2;
	char c;
	bool inField = false;
	bool isQuoted = false;
	bool searchingTerminator = false;
	int refIndex;
	int inSize = static_cast<int>(in.size());
	ret->truncate(0);

	for (refIndex = *_refIndex; refIndex < inSize; ++refIndex) {
		c = in.at(refIndex);
		if (!inField) {
			// we have to search the field beginning, now.
			switch (c) {
			case ' ': // space
			case '	': // tab
				// hm, still not the beginning. Go on..
				break;
			case '\r':
			case '\n':
				if (inRecord) {
					/* This is the end of the last field in
					 * the record.
					 */
					PWM_ASSERT(ret->isEmpty());
					rv = 1; // record end
					goto out;
				} else {
					// hm, still not the beginning. Go on..
					break;
				}
			case ',':
				// Oh, an empty field. How sad.
				PWM_ASSERT(ret->isEmpty());
				rv = 0; // field end
				goto out;
			case '\"':
				// this is the quoted beginning.
				inField = true;
				isQuoted = true;
				if (refIndex + 1 >= inSize)
					goto unexp_eof;
				break;
			default:
				// this is the unquoted beginning.
				inField = true;
				isQuoted = false;
				*ret += c;
				break;
			}
		} else {
			// we are in the field now. Search the end.
			if (isQuoted) {
				if (searchingTerminator) {
					switch (c) {
					case '\r':
					case '\n':
						rv = 1; // record end
						goto out;
					case ',':
						// found it.
						rv = 0; // field end
						goto out;
					default:
						// go on.
						continue;
					}
				}
				switch (c) {
				case '\"':
					/* check if this is the end of the
					 * entry, or just an inline escaped quote.
					 */
					char next;
					if (refIndex + 1 >= inSize) {
						// This is the last char, so it's the end.
						rv = 2; // data end
						goto out;
					}
					next = in.at(refIndex + 1);
					switch (next) {
					case '\"':
						// This is an escaped double quote.
						// So skip next iteration.
						refIndex += 1;
						*ret += c;
						break;
					default:
						/* end of field.
						 * We have to search the comma (or newline...),
						 * which officially terminates the entry.
						 */
						searchingTerminator = true;
						break;
					}
					break;
				default:
					// nothing special about the char. Go on!
					*ret += c;
					break;
				}
			} else {
				switch (c) {
				case '\"':
					// This is not allowed here.
					return -1; // parser error
				case '\r':
				case '\n':
					rv = 1; // record end
					goto out;
				case ',':
					rv = 0; // field end
					goto out;
				default:
					// nothing special about the char. Go on!
					*ret += c;
					break;
				}
			}
		}
	}
	// we are at the end of the stream, now!
	if (searchingTerminator) {
		/* Ok, there's no terminating comma (or newline...),
		 * because we are at the end. That's perfectly fine.
		 */
		PWM_ASSERT(inField);
		rv = 2; // data end
		goto out;
	}
	if (!isQuoted && inField) {
		// That's the end of the last unquoted field.
		rv = 2; // data end
		goto out;
	}
	if (!inField) {
		// This is expected EOF
		rv = 2; // data end
		goto out;
	}

unexp_eof:
	printDebug("unexpected EOF :(");
	return -1; // parser error

out:
	if (!isQuoted)
		*ret = ret->stripWhiteSpace();
	*_refIndex = refIndex + 1;
	return rv;
}

bool Csv::exportData(const QString &filepath,
		     PwMDoc *doc)
{
	PWM_ASSERT(!doc->isDocEmpty());
	bool ret = true;
	if (QFile::exists(filepath)) {
		int ret;
		ret = KMessageBox::questionYesNo(parent,
						 i18n("This file does already exist.\n"
						      "Do you want to overwrite it?"),
						 i18n("Overwrite file?"));
		if (ret == KMessageBox::No)
			return false;
		if (!QFile::remove(filepath)) {
			KMessageBox::error(parent,
					   i18n("Could not delete the old file."),
					   i18n("Delete error."));
			return false;
		}
	}
	QFile f(filepath);
	if (!f.open(IO_ReadWrite)) {
		KMessageBox::error(parent,
				   i18n("Could not open file for writing."),
				   i18n("Open error."));
		ret = false;
		goto out;
	}
	doc->unlockAll_tempoary();
	if (!doExport(f, doc))
		ret = false;
	doc->unlockAll_tempoary(true);
	f.close();
out:
	return ret;
}

bool Csv::doExport(QFile &f,
		   PwMDoc *doc)
{
	unsigned int numCat = doc->numCategories();
	unsigned int numEntr;
	unsigned int i, j;
	PwMDataItem d;
	QCString s, catName;
	QByteArray b;

	for (i = 0; i < numCat; ++i) {
		numEntr = doc->numEntries(i);
		catName = newField(doc->getCategory(i)->c_str());
		for (j = 0; j < numEntr; ++j) {
			doc->getEntry(i, j, &d);
			s = catName;
			s += ",,";
			s += newField(d.desc.c_str());
			s += ",";
			s += newField(d.name.c_str());
			s += ",";
			s += newField(d.pw.c_str());
			s += ",";
			s += newField(d.url.c_str());
			s += ",";
			s += newField(d.launcher.c_str());
			s += ",";
			s += newField(d.comment.c_str());
			s += "\r\n";
			b = s;
			// remove \0 termination
#ifndef PWM_EMBEDDED
			b.resize(b.size() - 1, QGArray::SpeedOptim);
#else
			b.resize(b.size() - 1);
#endif
			if (!f.writeBlock(b))
				return false;
		}
	}
	return true;
}

QCString Csv::newField(QCString s)
{
	if (s.isEmpty())
		return QCString();
	QCString ret("\"");
#ifndef PWM_EMBEDDED
	s.replace('\"', "\"\"");
#else
	s.replace(QRegExp("\""), "\"\"");
#endif
	ret += s;
	ret += "\"";
	return ret;
}