aboutsummaryrefslogtreecommitdiff
path: root/vmime-master/src/vmime/text.cpp
blob: 86ba44f1e605c59f94cb7490c56995e59732d11f (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
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
//
// VMime library (http://www.vmime.org)
// Copyright (C) 2002 Vincent Richard <vincent@vmime.org>
//
// 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 3 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.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Linking this library statically or dynamically with other modules is making
// a combined work based on this library.  Thus, the terms and conditions of
// the GNU General Public License cover the whole combination.
//

#include "vmime/text.hpp"

#include "vmime/parserHelpers.hpp"
#include "vmime/encoding.hpp"


namespace vmime {


text::text() {

}


text::text(const text& t)
	: headerFieldValue() {

	copyFrom(t);
}


text::text(const string& t, const charset& ch) {

	createFromString(t, ch);
}


text::text(const string& t) {

	createFromString(t, charset::getLocalCharset());
}


text::text(const word& w) {

	appendWord(make_shared <word>(w));
}


text::~text() {

	removeAllWords();
}


void text::parseImpl(
	const parsingContext& ctx,
	const string& buffer,
	const size_t position,
	const size_t end,
	size_t* newPosition
) {

	removeAllWords();

	size_t newPos;

	const std::vector <shared_ptr <word> > words =
		word::parseMultiple(ctx, buffer, position, end, &newPos);

	copy_vector(words, m_words);

	setParsedBounds(position, newPos);

	if (newPosition) {
		*newPosition = newPos;
	}
}


void text::generateImpl(
	const generationContext& ctx,
	utility::outputStream& os,
	const size_t curLinePos,
	size_t* newLinePos
) const {

	encodeAndFold(ctx, os, curLinePos, newLinePos, 0);
}


void text::copyFrom(const component& other) {

	const text& t = dynamic_cast <const text&>(other);

	removeAllWords();

	for (std::vector <shared_ptr <word> >::const_iterator i = t.m_words.begin() ;
	     i != t.m_words.end() ; ++i) {

		m_words.push_back(make_shared <word>(**i));
	}
}


text& text::operator=(const component& other) {

	copyFrom(other);
	return *this;
}


text& text::operator=(const text& other) {

	copyFrom(other);
	return *this;
}


bool text::operator==(const text& t) const {

	if (getWordCount() == t.getWordCount()) {

		bool equal = true;

		std::vector <shared_ptr <word> >::const_iterator i = m_words.begin();
		std::vector <shared_ptr <word> >::const_iterator j = t.m_words.begin();

		for ( ; equal && i != m_words.end() ; ++i, ++j) {
			equal = (**i == **j);
		}

		return equal;
	}

	return false;
}


bool text::operator!=(const text& t) const {

	return !(*this == t);
}


const string text::getConvertedText(
	const charset& dest,
	const charsetConverterOptions& opts
) const {

	string out;

	for (std::vector <shared_ptr <word> >::const_iterator i = m_words.begin() ;
	     i != m_words.end() ; ++i) {

		out += (*i)->getConvertedText(dest, opts);
	}

	return out;
}


void text::appendWord(const shared_ptr <word>& w) {

	m_words.push_back(w);
}


void text::insertWordBefore(const size_t pos, const shared_ptr <word>& w) {

	m_words.insert(m_words.begin() + pos, w);
}


void text::insertWordAfter(const size_t pos, const shared_ptr <word>& w) {

	m_words.insert(m_words.begin() + pos + 1, w);
}


void text::removeWord(const size_t pos) {

	const std::vector <shared_ptr <word> >::iterator it = m_words.begin() + pos;

	m_words.erase(it);
}


void text::removeAllWords() {

	m_words.clear();
}


size_t text::getWordCount() const {

	return m_words.size();
}


bool text::isEmpty() const {

	return m_words.empty();
}


const shared_ptr <word> text::getWordAt(const size_t pos) {

	return m_words[pos];
}


const shared_ptr <const word> text::getWordAt(const size_t pos) const {

	return m_words[pos];
}


const std::vector <shared_ptr <const word> > text::getWordList() const {

	std::vector <shared_ptr <const word> > list;

	list.reserve(m_words.size());

	for (std::vector <shared_ptr <word> >::const_iterator it = m_words.begin() ;
	     it != m_words.end() ; ++it) {

		list.push_back(*it);
	}

	return list;
}


const std::vector <shared_ptr <word> > text::getWordList() {

	return m_words;
}


shared_ptr <component> text::clone() const {

	return make_shared <text>(*this);
}


shared_ptr <text> text::newFromString(const string& in, const charset& ch) {

	shared_ptr <text> t = make_shared <text>();

	t->createFromString(in, ch);

	return t;
}


void text::createFromString(const string& in, const charset& ch) {

	size_t asciiCount = 0;
	size_t asciiPercent = 0;

	removeAllWords();

	// Check whether there is a recommended encoding for this charset.
	// If so, the whole buffer will be encoded. Else, the number of
	// 7-bit (ASCII) bytes in the input will be used to determine if
	// we need to encode the whole buffer.
	encoding recommendedEnc;
	const bool alwaysEncode = ch.getRecommendedEncoding(recommendedEnc);

	if (!alwaysEncode) {
		asciiCount = utility::stringUtils::countASCIIchars(in.begin(), in.end());
		asciiPercent = (in.length() == 0 ? 100 : (100 * asciiCount) / in.length());
	}

	// If there are "too much" non-ASCII chars, encode everything
	if (alwaysEncode || asciiPercent < 60) {  // less than 60% ASCII chars

		appendWord(make_shared <word>(in, ch));

	// Else, only encode words which need it
	} else {

		bool is8bit = false;     // is the current word 8-bit?
		bool prevIs8bit = false; // is previous word 8-bit?
		unsigned int count = 0;  // total number of words

		for (size_t end = in.size(), pos = 0, start = 0 ; ; ) {

			if (pos == end || parserHelpers::isSpace(in[pos])) {

				const string chunk(in.begin() + start, in.begin() + pos);

				if (pos != end) {
					++pos;
				}

				if (is8bit) {

					if (count && prevIs8bit) {

						// No need to create a new encoded word, just append
						// the current word to the previous one.
						shared_ptr <word> w = getWordAt(getWordCount() - 1);
						w->getBuffer() += " " + chunk;

					} else {

						if (count) {
							shared_ptr <word> w = getWordAt(getWordCount() - 1);
							w->getBuffer() += ' ';
						}

						appendWord(make_shared <word>(chunk, ch));

						prevIs8bit = true;
						++count;
					}

				} else {

					if (count && !prevIs8bit) {

						shared_ptr <word> w = getWordAt(getWordCount() - 1);
						w->getBuffer() += " " + chunk;

					} else {

						appendWord(make_shared <word>(chunk, charset(charsets::US_ASCII)));

						prevIs8bit = false;
						++count;
					}
				}

				if (pos == end) {
					break;
				}

				is8bit = false;
				start = pos;

			} else if (!parserHelpers::isAscii(in[pos])) {

				is8bit = true;
				++pos;

			} else {

				++pos;
			}
		}
	}
}


void text::encodeAndFold(
	const generationContext& ctx,
	utility::outputStream& os,
	const size_t firstLineOffset,
	size_t* lastLineLength,
	const int flags
) const {

	size_t curLineLength = firstLineOffset;
	word::generatorState state;

	for (size_t wi = 0 ; wi < getWordCount() ; ++wi) {

		getWordAt(wi)->generate(
			ctx, os, curLineLength,
			&curLineLength, flags, &state
		);
	}

	if (lastLineLength) {
		*lastLineLength = curLineLength;
	}
}


shared_ptr <text> text::decodeAndUnfold(const string& in) {

	shared_ptr <text> t = make_shared <text>();

	decodeAndUnfold(parsingContext::getDefaultContext(), in, t.get());

	return t;
}


shared_ptr <text> text::decodeAndUnfold(const parsingContext& ctx, const string& in) {

	shared_ptr <text> t = make_shared <text>();

	decodeAndUnfold(ctx, in, t.get());

	return t;
}


text* text::decodeAndUnfold(const string& in, text* generateInExisting) {

	return decodeAndUnfold(parsingContext::getDefaultContext(), in, generateInExisting);
}


text* text::decodeAndUnfold(const parsingContext& ctx, const string& in, text* generateInExisting) {

	text* out = generateInExisting ? generateInExisting : new text();

	out->removeAllWords();

	std::vector <shared_ptr <word> > words = word::parseMultiple(ctx, in, 0, in.length(), NULL);
	fixBrokenWords(words);

	copy_vector(words, out->m_words);

	return out;
}


// static
void text::fixBrokenWords(std::vector <shared_ptr <word> >& words) {

	if (words.size() < 2) {
		return;
	}

	// Fix words which encode a non-integral number of characters.
	// This is not RFC-compliant, but we should be able to recover from it.
	for (size_t i = 0, n = words.size() ; i < n - 1 ; ++i) {

		shared_ptr <word> w1 = words[i];

		// Check whether the word is valid
		bool valid = false;

		try {

			valid = w1->getCharset().isValidText(w1->getBuffer(), NULL);

		} catch (vmime::exceptions::charset_conv_error& e) {

			// Unknown charset or unexpected conversion error: assume word is valid
			valid = true;
		}

		// If the current word is not valid, try to grab some bytes
		// from the next words, to see whether it becomes valid.
		if (!valid) {

			string buffer(w1->getBuffer());
			size_t mergeWords = 1;  // number of adjacent words to merge

			for (size_t j = i + 1 ; j < n ; ++j) {

				shared_ptr <word> nextWord = words[j];

				if (nextWord->getCharset() != w1->getCharset()) {
					break;
				}

				buffer += nextWord->getBuffer();
				++mergeWords;
			}

			if (mergeWords == 1) {
				// No adjacent word with same charset found
				continue;
			}

			string::size_type firstInvalidByte;
			valid = w1->getCharset().isValidText(buffer, &firstInvalidByte);

			// Current word with additional bytes from the next words
			// is now valid: adjust buffers of words.
			w1->setBuffer(string(buffer.begin(), buffer.begin() + firstInvalidByte));
			words[i + 1]->setBuffer(string(buffer.begin() + firstInvalidByte, buffer.end()));

			// Remove unused words
			for (size_t j = 0 ; j < mergeWords - 2 ; ++j) {

				words.erase(words.begin() + i + 2);
				--n;
			}

			// If the next word is now empty, remove it
			if (words[i + 1]->getBuffer().empty()) {

				words.erase(words.begin() + i + 1);
				--n;
			}
		}
	}
}


const std::vector <shared_ptr <component> > text::getChildComponents() {

	std::vector <shared_ptr <component> > list;

	copy_vector(m_words, list);

	return list;
}


const string text::getWholeBuffer() const {

	string res;

	for (std::vector <shared_ptr <word> >::const_iterator it = m_words.begin() ;
	     it != m_words.end() ; ++it) {

		res += (*it)->getBuffer();
	}

	return res;
}


} // vmime