00001
00002
00003
00004
00005 #include <config.h>
00006
00007 #include "partNode.h"
00008
00009
00010 #define ALLOW_GUI 1
00011 #include "kmkernel.h"
00012 #include "kmmessage.h"
00013 #include "mailinglist-magic.h"
00014 #include "messageproperty.h"
00015 using KMail::MessageProperty;
00016 #include "objecttreeparser.h"
00017 using KMail::ObjectTreeParser;
00018 #include "kmfolderindex.h"
00019 #include "undostack.h"
00020 #include "kmversion.h"
00021 #include "headerstrategy.h"
00022 #include "globalsettings.h"
00023 using KMail::HeaderStrategy;
00024 #include "kmaddrbook.h"
00025 #include "kcursorsaver.h"
00026 #include "templateparser.h"
00027
00028 #include <libkpimidentities/identity.h>
00029 #include <libkpimidentities/identitymanager.h>
00030 #include <libemailfunctions/email.h>
00031
00032 #include <kasciistringtools.h>
00033
00034 #include <kpgpblock.h>
00035 #include <kaddrbook.h>
00036
00037 #include <kapplication.h>
00038 #include <kglobalsettings.h>
00039 #include <kdebug.h>
00040 #include <kconfig.h>
00041 #include <khtml_part.h>
00042 #include <kuser.h>
00043 #include <kidna.h>
00044 #include <kasciistricmp.h>
00045
00046 #include <qcursor.h>
00047 #include <qtextcodec.h>
00048 #include <qmessagebox.h>
00049 #include <kmime_util.h>
00050 #include <kmime_charfreq.h>
00051
00052 #include <kmime_header_parsing.h>
00053 using KMime::HeaderParsing::parseAddressList;
00054 using namespace KMime::Types;
00055
00056 #include <mimelib/body.h>
00057 #include <mimelib/field.h>
00058 #include <mimelib/mimepp.h>
00059 #include <mimelib/string.h>
00060 #include <assert.h>
00061 #include <sys/time.h>
00062 #include <time.h>
00063 #include <klocale.h>
00064 #include <stdlib.h>
00065 #include <unistd.h>
00066 #include "util.h"
00067
00068 #if ALLOW_GUI
00069 #include <kmessagebox.h>
00070 #endif
00071
00072 using namespace KMime;
00073
00074 static DwString emptyString("");
00075
00076
00077 static QString sReplyLanguage, sReplyStr, sReplyAllStr, sIndentPrefixStr;
00078 static bool sSmartQuote,
00079 sWordWrap;
00080 static int sWrapCol;
00081 static QStringList sPrefCharsets;
00082
00083 QString KMMessage::sForwardStr;
00084 const HeaderStrategy * KMMessage::sHeaderStrategy = HeaderStrategy::rich();
00085
00086 static void applyHeadersToMessagePart( DwHeaders& headers, KMMessagePart* aPart );
00087
00088 QValueList<KMMessage*> KMMessage::sPendingDeletes;
00089
00090
00091 KMMessage::KMMessage(DwMessage* aMsg)
00092 : KMMsgBase()
00093 {
00094 init( aMsg );
00095
00096 mNeedsAssembly = true;
00097 }
00098
00099
00100 KMMessage::KMMessage(KMFolder* parent): KMMsgBase(parent)
00101 {
00102 init();
00103 }
00104
00105
00106
00107 KMMessage::KMMessage(KMMsgInfo& msgInfo): KMMsgBase()
00108 {
00109 init();
00110
00111 mMsgSize = msgInfo.msgSize();
00112 mFolderOffset = msgInfo.folderOffset();
00113 mStatus = msgInfo.status();
00114 mEncryptionState = msgInfo.encryptionState();
00115 mSignatureState = msgInfo.signatureState();
00116 mMDNSentState = msgInfo.mdnSentState();
00117 mDate = msgInfo.date();
00118 mFileName = msgInfo.fileName();
00119 KMMsgBase::assign(&msgInfo);
00120 }
00121
00122
00123
00124 KMMessage::KMMessage(const KMMessage& other) :
00125 KMMsgBase( other ),
00126 ISubject(),
00127 mMsg(0)
00128 {
00129 init();
00130 assign( other );
00131 }
00132
00133 void KMMessage::init( DwMessage* aMsg )
00134 {
00135 mNeedsAssembly = false;
00136 if ( aMsg ) {
00137 mMsg = aMsg;
00138 } else {
00139 mMsg = new DwMessage;
00140 }
00141 mOverrideCodec = 0;
00142 mDecodeHTML = false;
00143 mComplete = true;
00144 mReadyToShow = true;
00145 mMsgSize = 0;
00146 mMsgLength = 0;
00147 mFolderOffset = 0;
00148 mStatus = KMMsgStatusNew;
00149 mEncryptionState = KMMsgEncryptionStateUnknown;
00150 mSignatureState = KMMsgSignatureStateUnknown;
00151 mMDNSentState = KMMsgMDNStateUnknown;
00152 mDate = 0;
00153 mUnencryptedMsg = 0;
00154 mLastUpdated = 0;
00155 mCursorPos = 0;
00156 mMsgInfo = 0;
00157 mIsParsed = false;
00158 }
00159
00160 void KMMessage::assign( const KMMessage& other )
00161 {
00162 MessageProperty::forget( this );
00163 delete mMsg;
00164 delete mUnencryptedMsg;
00165
00166 mNeedsAssembly = true;
00167 if( other.mMsg )
00168 mMsg = new DwMessage( *(other.mMsg) );
00169 else
00170 mMsg = 0;
00171 mOverrideCodec = other.mOverrideCodec;
00172 mDecodeHTML = other.mDecodeHTML;
00173 mMsgSize = other.mMsgSize;
00174 mMsgLength = other.mMsgLength;
00175 mFolderOffset = other.mFolderOffset;
00176 mStatus = other.mStatus;
00177 mEncryptionState = other.mEncryptionState;
00178 mSignatureState = other.mSignatureState;
00179 mMDNSentState = other.mMDNSentState;
00180 mIsParsed = other.mIsParsed;
00181 mDate = other.mDate;
00182 if( other.hasUnencryptedMsg() )
00183 mUnencryptedMsg = new KMMessage( *other.unencryptedMsg() );
00184 else
00185 mUnencryptedMsg = 0;
00186 setDrafts( other.drafts() );
00187 setTemplates( other.templates() );
00188
00189
00190 }
00191
00192
00193 KMMessage::~KMMessage()
00194 {
00195 delete mMsgInfo;
00196 delete mMsg;
00197 kmkernel->undoStack()->msgDestroyed( this );
00198 }
00199
00200
00201
00202 void KMMessage::setReferences(const QCString& aStr)
00203 {
00204 if (!aStr) return;
00205 mMsg->Headers().References().FromString(aStr);
00206 mNeedsAssembly = true;
00207 }
00208
00209
00210
00211 QCString KMMessage::id() const
00212 {
00213 DwHeaders& header = mMsg->Headers();
00214 if (header.HasMessageId())
00215 return KMail::Util::CString( header.MessageId().AsString() );
00216 else
00217 return "";
00218 }
00219
00220
00221
00222
00223
00224
00225
00226 void KMMessage::setMsgSerNum(unsigned long newMsgSerNum)
00227 {
00228 MessageProperty::setSerialCache( this, newMsgSerNum );
00229 }
00230
00231
00232
00233 bool KMMessage::isMessage() const
00234 {
00235 return true;
00236 }
00237
00238
00239 bool KMMessage::transferInProgress() const
00240 {
00241 return MessageProperty::transferInProgress( getMsgSerNum() );
00242 }
00243
00244
00245
00246 void KMMessage::setTransferInProgress(bool value, bool force)
00247 {
00248 MessageProperty::setTransferInProgress( getMsgSerNum(), value, force );
00249 if ( !transferInProgress() && sPendingDeletes.contains( this ) ) {
00250 sPendingDeletes.remove( this );
00251 if ( parent() ) {
00252 int idx = parent()->find( this );
00253 if ( idx > 0 ) {
00254 parent()->removeMsg( idx );
00255 }
00256 }
00257 }
00258 }
00259
00260
00261
00262 bool KMMessage::isUrgent() const {
00263 return headerField( "Priority" ).contains( "urgent", false )
00264 || headerField( "X-Priority" ).startsWith( "2" );
00265 }
00266
00267
00268 void KMMessage::setUnencryptedMsg( KMMessage* unencrypted )
00269 {
00270 delete mUnencryptedMsg;
00271 mUnencryptedMsg = unencrypted;
00272 }
00273
00274
00275
00276 KPIM::EmailParseResult KMMessage::isValidEmailAddressList( const QString& aStr,
00277 QString& brokenAddress )
00278 {
00279 if ( aStr.isEmpty() ) {
00280 return KPIM::AddressEmpty;
00281 }
00282
00283 QStringList list = KPIM::splitEmailAddrList( aStr );
00284 for( QStringList::const_iterator it = list.begin(); it != list.end(); ++it ) {
00285 KPIM::EmailParseResult errorCode = KPIM::isValidEmailAddress( *it );
00286 if ( errorCode != KPIM::AddressOk ) {
00287 brokenAddress = ( *it );
00288 return errorCode;
00289 }
00290 }
00291 return KPIM::AddressOk;
00292 }
00293
00294
00295 const DwString& KMMessage::asDwString() const
00296 {
00297 if (mNeedsAssembly)
00298 {
00299 mNeedsAssembly = false;
00300 mMsg->Assemble();
00301 }
00302 return mMsg->AsString();
00303 }
00304
00305
00306 const DwMessage* KMMessage::asDwMessage()
00307 {
00308 if (mNeedsAssembly)
00309 {
00310 mNeedsAssembly = false;
00311 mMsg->Assemble();
00312 }
00313 return mMsg;
00314 }
00315
00316
00317 QCString KMMessage::asString() const {
00318 return KMail::Util::CString( asDwString() );
00319 }
00320
00321
00322 QByteArray KMMessage::asSendableString() const
00323 {
00324 KMMessage msg( new DwMessage( *this->mMsg ) );
00325 msg.removePrivateHeaderFields();
00326 msg.removeHeaderField("Bcc");
00327 return KMail::Util::ByteArray( msg.asDwString() );
00328 }
00329
00330 QCString KMMessage::headerAsSendableString() const
00331 {
00332 KMMessage msg( new DwMessage( *this->mMsg ) );
00333 msg.removePrivateHeaderFields();
00334 msg.removeHeaderField("Bcc");
00335 return msg.headerAsString().latin1();
00336 }
00337
00338 void KMMessage::removePrivateHeaderFields() {
00339 removeHeaderField("Status");
00340 removeHeaderField("X-Status");
00341 removeHeaderField("X-KMail-EncryptionState");
00342 removeHeaderField("X-KMail-SignatureState");
00343 removeHeaderField("X-KMail-MDN-Sent");
00344 removeHeaderField("X-KMail-Transport");
00345 removeHeaderField("X-KMail-Identity");
00346 removeHeaderField("X-KMail-Fcc");
00347 removeHeaderField("X-KMail-Redirect-From");
00348 removeHeaderField("X-KMail-Link-Message");
00349 removeHeaderField("X-KMail-Link-Type");
00350 removeHeaderField( "X-KMail-Markup" );
00351 }
00352
00353
00354 void KMMessage::setStatusFields()
00355 {
00356 char str[2] = { 0, 0 };
00357
00358 setHeaderField("Status", status() & KMMsgStatusNew ? "R" : "RO");
00359 setHeaderField("X-Status", statusToStr(status()));
00360
00361 str[0] = (char)encryptionState();
00362 setHeaderField("X-KMail-EncryptionState", str);
00363
00364 str[0] = (char)signatureState();
00365
00366 setHeaderField("X-KMail-SignatureState", str);
00367
00368 str[0] = static_cast<char>( mdnSentState() );
00369 setHeaderField("X-KMail-MDN-Sent", str);
00370
00371
00372
00373 mNeedsAssembly = false;
00374 mMsg->Headers().Assemble();
00375 mMsg->Assemble( mMsg->Headers(),
00376 mMsg->Body() );
00377 }
00378
00379
00380
00381 QString KMMessage::headerAsString() const
00382 {
00383 DwHeaders& header = mMsg->Headers();
00384 header.Assemble();
00385 if ( header.AsString().empty() )
00386 return QString::null;
00387 return QString::fromLatin1( header.AsString().c_str() );
00388 }
00389
00390
00391
00392 DwMediaType& KMMessage::dwContentType()
00393 {
00394 return mMsg->Headers().ContentType();
00395 }
00396
00397 void KMMessage::fromByteArray( const QByteArray & ba, bool setStatus ) {
00398 return fromDwString( DwString( ba.data(), ba.size() ), setStatus );
00399 }
00400
00401 void KMMessage::fromString( const QCString & str, bool aSetStatus ) {
00402 return fromDwString( KMail::Util::dwString( str ), aSetStatus );
00403 }
00404
00405 void KMMessage::fromDwString(const DwString& str, bool aSetStatus)
00406 {
00407 delete mMsg;
00408 mMsg = new DwMessage;
00409 mMsg->FromString( str );
00410 mMsg->Parse();
00411
00412 if (aSetStatus) {
00413 setStatus(headerField("Status").latin1(), headerField("X-Status").latin1());
00414 setEncryptionStateChar( headerField("X-KMail-EncryptionState").at(0) );
00415 setSignatureStateChar( headerField("X-KMail-SignatureState").at(0) );
00416 setMDNSentState( static_cast<KMMsgMDNSentState>( headerField("X-KMail-MDN-Sent").at(0).latin1() ) );
00417 }
00418 if (attachmentState() == KMMsgAttachmentUnknown && readyToShow())
00419 updateAttachmentState();
00420
00421 mNeedsAssembly = false;
00422 mDate = date();
00423 }
00424
00425
00426
00427 QString KMMessage::formatString(const QString& aStr) const
00428 {
00429 QString result, str;
00430 QChar ch;
00431 uint j;
00432
00433 if (aStr.isEmpty())
00434 return aStr;
00435
00436 unsigned int strLength(aStr.length());
00437 for (uint i=0; i<strLength;) {
00438 ch = aStr[i++];
00439 if (ch == '%') {
00440 ch = aStr[i++];
00441 switch ((char)ch) {
00442 case 'D':
00443
00444
00445
00446
00447 result += KMime::DateFormatter::formatDate( KMime::DateFormatter::Localized,
00448 date(), sReplyLanguage, false );
00449 break;
00450 case 'e':
00451 result += from();
00452 break;
00453 case 'F':
00454 result += fromStrip();
00455 break;
00456 case 'f':
00457 {
00458 str = fromStrip();
00459
00460 for (j=0; str[j]>' '; j++)
00461 ;
00462 unsigned int strLength(str.length());
00463 for (; j < strLength && str[j] <= ' '; j++)
00464 ;
00465 result += str[0];
00466 if (str[j]>' ')
00467 result += str[j];
00468 else
00469 if (str[1]>' ')
00470 result += str[1];
00471 }
00472 break;
00473 case 'T':
00474 result += toStrip();
00475 break;
00476 case 't':
00477 result += to();
00478 break;
00479 case 'C':
00480 result += ccStrip();
00481 break;
00482 case 'c':
00483 result += cc();
00484 break;
00485 case 'S':
00486 result += subject();
00487 break;
00488 case '_':
00489 result += ' ';
00490 break;
00491 case 'L':
00492 result += "\n";
00493 break;
00494 case '%':
00495 result += '%';
00496 break;
00497 default:
00498 result += '%';
00499 result += ch;
00500 break;
00501 }
00502 } else
00503 result += ch;
00504 }
00505 return result;
00506 }
00507
00508 static void removeTrailingSpace( QString &line )
00509 {
00510 int i = line.length()-1;
00511 while( (i >= 0) && ((line[i] == ' ') || (line[i] == '\t')))
00512 i--;
00513 line.truncate( i+1);
00514 }
00515
00516 static QString splitLine( QString &line)
00517 {
00518 removeTrailingSpace( line );
00519 int i = 0;
00520 int j = -1;
00521 int l = line.length();
00522
00523
00524
00525 while(i < l)
00526 {
00527 QChar c = line[i];
00528 if ((c == '>') || (c == ':') || (c == '|'))
00529 j = i+1;
00530 else if ((c != ' ') && (c != '\t'))
00531 break;
00532 i++;
00533 }
00534
00535 if ( j <= 0 )
00536 {
00537 return "";
00538 }
00539 if ( i == l )
00540 {
00541 QString result = line.left(j);
00542 line = QString::null;
00543 return result;
00544 }
00545
00546 QString result = line.left(j);
00547 line = line.mid(j);
00548 return result;
00549 }
00550
00551 static QString flowText(QString &text, const QString& indent, int maxLength)
00552 {
00553 maxLength--;
00554 if (text.isEmpty())
00555 {
00556 return indent+"<NULL>\n";
00557 }
00558 QString result;
00559 while (1)
00560 {
00561 int i;
00562 if ((int) text.length() > maxLength)
00563 {
00564 i = maxLength;
00565 while( (i >= 0) && (text[i] != ' '))
00566 i--;
00567 if (i <= 0)
00568 {
00569
00570 i = maxLength;
00571
00572
00573 }
00574 }
00575 else
00576 {
00577 i = text.length();
00578 }
00579
00580 QString line = text.left(i);
00581 if (i < (int) text.length())
00582 text = text.mid(i);
00583 else
00584 text = QString::null;
00585
00586 result += indent + line + '\n';
00587
00588 if (text.isEmpty())
00589 return result;
00590 }
00591 }
00592
00593 static bool flushPart(QString &msg, QStringList &part,
00594 const QString &indent, int maxLength)
00595 {
00596 maxLength -= indent.length();
00597 if (maxLength < 20) maxLength = 20;
00598
00599
00600 while ((part.begin() != part.end()) && part.last().isEmpty())
00601 {
00602 part.remove(part.fromLast());
00603 }
00604
00605 QString text;
00606 for(QStringList::Iterator it2 = part.begin();
00607 it2 != part.end();
00608 it2++)
00609 {
00610 QString line = (*it2);
00611
00612 if (line.isEmpty())
00613 {
00614 if (!text.isEmpty())
00615 msg += flowText(text, indent, maxLength);
00616 msg += indent + '\n';
00617 }
00618 else
00619 {
00620 if (text.isEmpty())
00621 text = line;
00622 else
00623 text += ' '+line.stripWhiteSpace();
00624
00625 if (((int) text.length() < maxLength) || ((int) line.length() < (maxLength-10)))
00626 msg += flowText(text, indent, maxLength);
00627 }
00628 }
00629 if (!text.isEmpty())
00630 msg += flowText(text, indent, maxLength);
00631
00632 bool appendEmptyLine = true;
00633 if (!part.count())
00634 appendEmptyLine = false;
00635
00636 part.clear();
00637 return appendEmptyLine;
00638 }
00639
00640 static QString stripSignature( const QString & msg, bool clearSigned ) {
00641 if ( clearSigned )
00642 return msg.left( msg.findRev( QRegExp( "\n--\\s?\n" ) ) );
00643 else
00644 return msg.left( msg.findRev( "\n-- \n" ) );
00645 }
00646
00647 QString KMMessage::smartQuote( const QString & msg, int maxLineLength )
00648 {
00649 QStringList part;
00650 QString oldIndent;
00651 bool firstPart = true;
00652
00653
00654 const QStringList lines = QStringList::split('\n', msg, true);
00655
00656 QString result;
00657 for(QStringList::const_iterator it = lines.begin();
00658 it != lines.end();
00659 ++it)
00660 {
00661 QString line = *it;
00662
00663 const QString indent = splitLine( line );
00664
00665 if ( line.isEmpty())
00666 {
00667 if (!firstPart)
00668 part.append(QString::null);
00669 continue;
00670 };
00671
00672 if (firstPart)
00673 {
00674 oldIndent = indent;
00675 firstPart = false;
00676 }
00677
00678 if (oldIndent != indent)
00679 {
00680 QString fromLine;
00681
00682 if (part.count() && (oldIndent.length() < indent.length()))
00683 {
00684 QStringList::Iterator it2 = part.fromLast();
00685 while( (it2 != part.end()) && (*it2).isEmpty())
00686 --it2;
00687
00688 if ((it2 != part.end()) && ((*it2).endsWith(":")))
00689 {
00690 fromLine = oldIndent + (*it2) + '\n';
00691 part.remove(it2);
00692 }
00693 }
00694 if (flushPart( result, part, oldIndent, maxLineLength))
00695 {
00696 if (oldIndent.length() > indent.length())
00697 result += indent + '\n';
00698 else
00699 result += oldIndent + '\n';
00700 }
00701 if (!fromLine.isEmpty())
00702 {
00703 result += fromLine;
00704 }
00705 oldIndent = indent;
00706 }
00707 part.append(line);
00708 }
00709 flushPart( result, part, oldIndent, maxLineLength);
00710 return result;
00711 }
00712
00713
00714
00715 void KMMessage::parseTextStringFromDwPart( partNode * root,
00716 QCString& parsedString,
00717 const QTextCodec*& codec,
00718 bool& isHTML ) const
00719 {
00720 if ( !root ) return;
00721
00722 isHTML = false;
00723
00724 {
00725 ObjectTreeParser otp( 0, 0, true, false, true );
00726 otp.parseObjectTree( root );
00727 }
00728 partNode * curNode = root->findType( DwMime::kTypeText,
00729 DwMime::kSubtypeUnknown,
00730 true,
00731 false );
00732 kdDebug(5006) << "\n\n======= KMMessage::parseTextStringFromDwPart() - "
00733 << ( curNode ? "text part found!\n" : "sorry, no text node!\n" ) << endl;
00734 if( curNode ) {
00735 isHTML = DwMime::kSubtypeHtml == curNode->subType();
00736
00737 ObjectTreeParser otp( 0, 0, true, false, true );
00738 otp.parseObjectTree( curNode );
00739 parsedString = otp.rawReplyString();
00740 codec = curNode->msgPart().codec();
00741 }
00742 }
00743
00744
00745
00746 QString KMMessage::asPlainText( bool aStripSignature, bool allowDecryption ) const {
00747 QCString parsedString;
00748 bool isHTML = false;
00749 const QTextCodec * codec = 0;
00750
00751 partNode * root = partNode::fromMessage( this );
00752 if ( !root ) return QString::null;
00753 parseTextStringFromDwPart( root, parsedString, codec, isHTML );
00754 delete root;
00755
00756 if ( mOverrideCodec || !codec )
00757 codec = this->codec();
00758
00759 if ( parsedString.isEmpty() )
00760 return QString::null;
00761
00762 bool clearSigned = false;
00763 QString result;
00764
00765
00766 if ( allowDecryption ) {
00767 QPtrList<Kpgp::Block> pgpBlocks;
00768 QStrList nonPgpBlocks;
00769 if ( Kpgp::Module::prepareMessageForDecryption( parsedString,
00770 pgpBlocks,
00771 nonPgpBlocks ) ) {
00772
00773
00774 if ( pgpBlocks.count() == 1 ) {
00775 Kpgp::Block * block = pgpBlocks.first();
00776 if ( block->type() == Kpgp::PgpMessageBlock ||
00777 block->type() == Kpgp::ClearsignedBlock ) {
00778 if ( block->type() == Kpgp::PgpMessageBlock ) {
00779
00780 block->decrypt();
00781 } else {
00782
00783 block->verify();
00784 clearSigned = true;
00785 }
00786
00787 result = codec->toUnicode( nonPgpBlocks.first() )
00788 + codec->toUnicode( block->text() )
00789 + codec->toUnicode( nonPgpBlocks.last() );
00790 }
00791 }
00792 }
00793 }
00794
00795 if ( result.isEmpty() ) {
00796 result = codec->toUnicode( parsedString );
00797 if ( result.isEmpty() )
00798 return result;
00799 }
00800
00801
00802 if ( isHTML && mDecodeHTML ) {
00803 KHTMLPart htmlPart;
00804 htmlPart.setOnlyLocalReferences( true );
00805 htmlPart.setMetaRefreshEnabled( false );
00806 htmlPart.setPluginsEnabled( false );
00807 htmlPart.setJScriptEnabled( false );
00808 htmlPart.setJavaEnabled( false );
00809 htmlPart.begin();
00810 htmlPart.write( result );
00811 htmlPart.end();
00812 htmlPart.selectAll();
00813 result = htmlPart.selectedText();
00814 }
00815
00816
00817 if ( aStripSignature )
00818 return stripSignature( result, clearSigned );
00819 else
00820 return result;
00821 }
00822
00823 QString KMMessage::asQuotedString( const QString& aHeaderStr,
00824 const QString& aIndentStr,
00825 const QString& selection ,
00826 bool aStripSignature ,
00827 bool allowDecryption ) const
00828 {
00829 QString content = selection.isEmpty() ?
00830 asPlainText( aStripSignature, allowDecryption ) : selection ;
00831
00832
00833 const int firstNonWS = content.find( QRegExp( "\\S" ) );
00834 const int lineStart = content.findRev( '\n', firstNonWS );
00835 if ( lineStart >= 0 )
00836 content.remove( 0, static_cast<unsigned int>( lineStart ) );
00837
00838 const QString indentStr = formatString( aIndentStr );
00839
00840 content.replace( '\n', '\n' + indentStr );
00841 content.prepend( indentStr );
00842 content += '\n';
00843
00844 const QString headerStr = formatString( aHeaderStr );
00845 if ( sSmartQuote && sWordWrap )
00846 return headerStr + smartQuote( content, sWrapCol );
00847 return headerStr + content;
00848 }
00849
00850
00851 KMMessage* KMMessage::createReply( KMail::ReplyStrategy replyStrategy,
00852 QString selection ,
00853 bool noQuote ,
00854 bool allowDecryption ,
00855 bool selectionIsBody ,
00856 const QString &tmpl )
00857 {
00858 KMMessage* msg = new KMMessage;
00859 QString str, replyStr, mailingListStr, replyToStr, toStr;
00860 QStringList mailingListAddresses;
00861 QCString refStr, headerName;
00862 bool replyAll = true;
00863
00864 msg->initFromMessage(this);
00865
00866 MailingList::name(this, headerName, mailingListStr);
00867 replyToStr = replyTo();
00868
00869 msg->setCharset("utf-8");
00870
00871
00872 if ( parent() && parent()->isMailingListEnabled() &&
00873 !parent()->mailingListPostAddress().isEmpty() ) {
00874 mailingListAddresses << parent()->mailingListPostAddress();
00875 }
00876 if ( headerField("List-Post").find( "mailto:", 0, false ) != -1 ) {
00877 QString listPost = headerField("List-Post");
00878 QRegExp rx( "<mailto:([^@>]+)@([^>]+)>", false );
00879 if ( rx.search( listPost, 0 ) != -1 )
00880 mailingListAddresses << rx.cap(1) + '@' + rx.cap(2);
00881 }
00882
00883
00884 replyStr = sReplyAllStr;
00885
00886 switch( replyStrategy ) {
00887 case KMail::ReplySmart : {
00888 if ( !headerField( "Mail-Followup-To" ).isEmpty() ) {
00889 toStr = headerField( "Mail-Followup-To" );
00890 }
00891 else if ( !replyToStr.isEmpty() ) {
00892
00893 toStr = replyToStr;
00894 }
00895 else if ( !mailingListAddresses.isEmpty() ) {
00896 toStr = mailingListAddresses[0];
00897 }
00898 else {
00899
00900 toStr = from();
00901 replyStr = sReplyStr;
00902 replyAll = false;
00903 }
00904
00905 QStringList recipients = KPIM::splitEmailAddrList( toStr );
00906 toStr = stripMyAddressesFromAddressList( recipients ).join(", ");
00907
00908 if ( toStr.isEmpty() && !recipients.isEmpty() )
00909 toStr = recipients[0];
00910
00911 break;
00912 }
00913 case KMail::ReplyList : {
00914 if ( !headerField( "Mail-Followup-To" ).isEmpty() ) {
00915 toStr = headerField( "Mail-Followup-To" );
00916 }
00917 else if ( !mailingListAddresses.isEmpty() ) {
00918 toStr = mailingListAddresses[0];
00919 }
00920 else if ( !replyToStr.isEmpty() ) {
00921
00922 toStr = replyToStr;
00923 }
00924
00925 QStringList recipients = KPIM::splitEmailAddrList( toStr );
00926 toStr = stripMyAddressesFromAddressList( recipients ).join(", ");
00927
00928 break;
00929 }
00930 case KMail::ReplyAll : {
00931 QStringList recipients;
00932 QStringList ccRecipients;
00933
00934
00935 if( !replyToStr.isEmpty() ) {
00936 recipients += KPIM::splitEmailAddrList( replyToStr );
00937
00938
00939 for ( QStringList::const_iterator it = mailingListAddresses.begin();
00940 it != mailingListAddresses.end();
00941 ++it ) {
00942 recipients = stripAddressFromAddressList( *it, recipients );
00943 }
00944 }
00945
00946 if ( !mailingListAddresses.isEmpty() ) {
00947
00948 if ( recipients.isEmpty() && !from().isEmpty() ) {
00949
00950
00951 ccRecipients += from();
00952 kdDebug(5006) << "Added " << from() << " to the list of CC recipients"
00953 << endl;
00954 }
00955
00956 recipients.prepend( mailingListAddresses[0] );
00957 }
00958 else {
00959
00960 if ( recipients.isEmpty() && !from().isEmpty() ) {
00961
00962
00963 recipients += from();
00964 kdDebug(5006) << "Added " << from() << " to the list of recipients"
00965 << endl;
00966 }
00967 }
00968
00969
00970 toStr = stripMyAddressesFromAddressList( recipients ).join(", ");
00971
00972
00973 if( !cc().isEmpty() || !to().isEmpty() ) {
00974 QStringList list;
00975 if (!to().isEmpty())
00976 list += KPIM::splitEmailAddrList(to());
00977 if (!cc().isEmpty())
00978 list += KPIM::splitEmailAddrList(cc());
00979 for( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) {
00980 if( !addressIsInAddressList( *it, recipients )
00981 && !addressIsInAddressList( *it, ccRecipients ) ) {
00982 ccRecipients += *it;
00983 kdDebug(5006) << "Added " << *it << " to the list of CC recipients"
00984 << endl;
00985 }
00986 }
00987 }
00988
00989 if ( !ccRecipients.isEmpty() ) {
00990
00991 ccRecipients = stripMyAddressesFromAddressList( ccRecipients );
00992
00993
00994
00995 if ( toStr.isEmpty() && !ccRecipients.isEmpty() ) {
00996 toStr = ccRecipients[0];
00997 ccRecipients.pop_front();
00998 }
00999
01000 msg->setCc( ccRecipients.join(", ") );
01001 }
01002
01003 if ( toStr.isEmpty() && !recipients.isEmpty() ) {
01004
01005 toStr = recipients[0];
01006 }
01007 break;
01008 }
01009 case KMail::ReplyAuthor : {
01010 if ( !replyToStr.isEmpty() ) {
01011 QStringList recipients = KPIM::splitEmailAddrList( replyToStr );
01012
01013
01014 for ( QStringList::const_iterator it = mailingListAddresses.begin();
01015 it != mailingListAddresses.end();
01016 ++it ) {
01017 recipients = stripAddressFromAddressList( *it, recipients );
01018 }
01019 if ( !recipients.isEmpty() ) {
01020 toStr = recipients.join(", ");
01021 }
01022 else {
01023
01024
01025 toStr = from();
01026 }
01027 }
01028 else if ( !from().isEmpty() ) {
01029 toStr = from();
01030 }
01031 replyStr = sReplyStr;
01032 replyAll = false;
01033 break;
01034 }
01035 case KMail::ReplyNone : {
01036
01037 }
01038 }
01039
01040 msg->setTo(toStr);
01041
01042 refStr = getRefStr();
01043 if (!refStr.isEmpty())
01044 msg->setReferences(refStr);
01045
01046 msg->setReplyToId(msgId());
01047
01048
01049
01050
01051
01052
01053
01054
01055
01056
01057
01058 msg->setSubject( replySubject() );
01059
01060 TemplateParser parser( msg, (replyAll ? TemplateParser::ReplyAll : TemplateParser::Reply),
01061 selection, sSmartQuote, noQuote, allowDecryption, selectionIsBody );
01062 if ( !tmpl.isEmpty() ) {
01063 parser.process( tmpl, this );
01064 } else {
01065 parser.process( this );
01066 }
01067
01068
01069 msg->link(this, KMMsgStatusReplied);
01070
01071 if ( parent() && parent()->putRepliesInSameFolder() )
01072 msg->setFcc( parent()->idString() );
01073
01074
01075 if ( encryptionState() == KMMsgPartiallyEncrypted ||
01076 encryptionState() == KMMsgFullyEncrypted ) {
01077 msg->setEncryptionState( KMMsgFullyEncrypted );
01078 }
01079
01080 return msg;
01081 }
01082
01083
01084
01085 QCString KMMessage::getRefStr() const
01086 {
01087 QCString firstRef, lastRef, refStr, retRefStr;
01088 int i, j;
01089
01090 refStr = headerField("References").stripWhiteSpace().latin1();
01091
01092 if (refStr.isEmpty())
01093 return headerField("Message-Id").latin1();
01094
01095 i = refStr.find('<');
01096 j = refStr.find('>');
01097 firstRef = refStr.mid(i, j-i+1);
01098 if (!firstRef.isEmpty())
01099 retRefStr = firstRef + ' ';
01100
01101 i = refStr.findRev('<');
01102 j = refStr.findRev('>');
01103
01104 lastRef = refStr.mid(i, j-i+1);
01105 if (!lastRef.isEmpty() && lastRef != firstRef)
01106 retRefStr += lastRef + ' ';
01107
01108 retRefStr += headerField("Message-Id").latin1();
01109 return retRefStr;
01110 }
01111
01112
01113 KMMessage* KMMessage::createRedirect( const QString &toStr )
01114 {
01115
01116 KMMessage* msg = new KMMessage( new DwMessage( *this->mMsg ) );
01117 KMMessagePart msgPart;
01118
01119 uint id = 0;
01120 QString strId = msg->headerField( "X-KMail-Identity" ).stripWhiteSpace();
01121 if ( !strId.isEmpty())
01122 id = strId.toUInt();
01123 const KPIM::Identity & ident =
01124 kmkernel->identityManager()->identityForUoidOrDefault( id );
01125
01126
01127 QString strByWayOf = QString("%1 (by way of %2 <%3>)")
01128 .arg( from() )
01129 .arg( ident.fullName() )
01130 .arg( ident.emailAddr() );
01131
01132
01133 QString strFrom = QString("%1 <%2>")
01134 .arg( ident.fullName() )
01135 .arg( ident.emailAddr() );
01136
01137
01138 QString origDate = msg->headerField( "Date" );
01139 msg->setDateToday();
01140 QString newDate = msg->headerField( "Date" );
01141
01142 if ( origDate.isEmpty() )
01143 msg->removeHeaderField( "Date" );
01144 else
01145 msg->setHeaderField( "Date", origDate );
01146
01147
01148 msg->setHeaderField( "Resent-Message-ID", generateMessageId( msg->sender() ),
01149 Structured, true);
01150 msg->setHeaderField( "Resent-Date", newDate, Structured, true );
01151 msg->setHeaderField( "Resent-To", toStr, Address, true );
01152 msg->setHeaderField( "Resent-From", strFrom, Address, true );
01153
01154 msg->setHeaderField( "X-KMail-Redirect-From", strByWayOf );
01155 msg->setHeaderField( "X-KMail-Recipients", toStr, Address );
01156
01157 msg->link(this, KMMsgStatusForwarded);
01158
01159 return msg;
01160 }
01161
01162
01163
01164 QCString KMMessage::createForwardBody()
01165 {
01166 QString s;
01167 QCString str;
01168
01169 if (sHeaderStrategy == HeaderStrategy::all()) {
01170 s = "\n\n---------- " + sForwardStr + " ----------\n\n";
01171 s += headerAsString();
01172 str = asQuotedString(s, "", QString::null, false, false).utf8();
01173 str += "\n-------------------------------------------------------\n";
01174 } else {
01175 s = "\n\n---------- " + sForwardStr + " ----------\n\n";
01176 s += "Subject: " + subject() + "\n";
01177 s += "Date: "
01178 + KMime::DateFormatter::formatDate( KMime::DateFormatter::Localized,
01179 date(), sReplyLanguage, false )
01180 + "\n";
01181 s += "From: " + from() + "\n";
01182 s += "To: " + to() + "\n";
01183 if (!cc().isEmpty()) s += "Cc: " + cc() + "\n";
01184 s += "\n";
01185 str = asQuotedString(s, "", QString::null, false, false).utf8();
01186 str += "\n-------------------------------------------------------\n";
01187 }
01188
01189 return str;
01190 }
01191
01192 void KMMessage::sanitizeHeaders( const QStringList& whiteList )
01193 {
01194
01195
01196 DwHeaders& header = mMsg->Headers();
01197 DwField* field = header.FirstField();
01198 DwField* nextField;
01199 while (field)
01200 {
01201 nextField = field->Next();
01202 if ( field->FieldNameStr().find( "ontent" ) == DwString::npos
01203 && !whiteList.contains( QString::fromLatin1( field->FieldNameStr().c_str() ) ) )
01204 header.RemoveField(field);
01205 field = nextField;
01206 }
01207 mMsg->Assemble();
01208 }
01209
01210
01211 KMMessage* KMMessage::createForward( const QString &tmpl )
01212 {
01213 KMMessage* msg = new KMMessage();
01214 QString id;
01215
01216
01217
01218
01219 if ( type() == DwMime::kTypeMultipart ||
01220 ( type() == DwMime::kTypeText && subtype() == DwMime::kSubtypePlain ) ) {
01221
01222 msg->fromDwString( this->asDwString() );
01223
01224
01225 const int type = msg->type();
01226 const int subtype = msg->subtype();
01227
01228 msg->sanitizeHeaders();
01229
01230
01231 QStringList blacklist = GlobalSettings::self()->mimetypesToStripWhenInlineForwarding();
01232 for ( QStringList::Iterator it = blacklist.begin(); it != blacklist.end(); ++it ) {
01233 QString entry = (*it);
01234 int sep = entry.find( '/' );
01235 QCString type = entry.left( sep ).latin1();
01236 QCString subtype = entry.mid( sep+1 ).latin1();
01237 kdDebug( 5006 ) << "Looking for blacklisted type: " << type << "/" << subtype << endl;
01238 while ( DwBodyPart * part = msg->findDwBodyPart( type, subtype ) ) {
01239 msg->mMsg->Body().RemoveBodyPart( part );
01240 }
01241 }
01242 msg->mMsg->Assemble();
01243
01244 msg->initFromMessage( this );
01245
01246 msg->setType( type );
01247 msg->setSubtype( subtype );
01248 } else if( type() == DwMime::kTypeText && subtype() == DwMime::kSubtypeHtml ) {
01249
01250
01251 msg->initFromMessage( this );
01252 msg->setType( DwMime::kTypeText );
01253 msg->setSubtype( DwMime::kSubtypeHtml );
01254 msg->mNeedsAssembly = true;
01255 msg->cleanupHeader();
01256 } else {
01257
01258
01259 msg->initFromMessage( this );
01260 msg->removeHeaderField("Content-Type");
01261 msg->removeHeaderField("Content-Transfer-Encoding");
01262
01263 DwHeaders & header = msg->mMsg->Headers();
01264 header.MimeVersion().FromString("1.0");
01265 DwMediaType & contentType = msg->dwContentType();
01266 contentType.SetType( DwMime::kTypeMultipart );
01267 contentType.SetSubtype( DwMime::kSubtypeMixed );
01268 contentType.CreateBoundary(0);
01269 contentType.Assemble();
01270
01271
01272 KMMessagePart msgPart;
01273 bodyPart( 0, &msgPart );
01274 msg->addBodyPart(&msgPart);
01275
01276 KMMessagePart secondPart;
01277 secondPart.setType( type() );
01278 secondPart.setSubtype( subtype() );
01279 secondPart.setBody( mMsg->Body().AsString() );
01280
01281 applyHeadersToMessagePart( mMsg->Headers(), &secondPart );
01282 msg->addBodyPart(&secondPart);
01283 msg->mNeedsAssembly = true;
01284 msg->cleanupHeader();
01285 }
01286
01287
01288 msg->setSubject( forwardSubject() );
01289
01290 TemplateParser parser( msg, TemplateParser::Forward,
01291 asPlainText( false, false ),
01292 false, false, false, false);
01293 if ( !tmpl.isEmpty() ) {
01294 parser.process( tmpl, this );
01295 } else {
01296 parser.process( this );
01297 }
01298
01299
01300
01301
01302
01303
01304
01305
01306 msg->link(this, KMMsgStatusForwarded);
01307 return msg;
01308 }
01309
01310 static const struct {
01311 const char * dontAskAgainID;
01312 bool canDeny;
01313 const char * text;
01314 } mdnMessageBoxes[] = {
01315 { "mdnNormalAsk", true,
01316 I18N_NOOP("This message contains a request to return a notification "
01317 "about your reception of the message.\n"
01318 "You can either ignore the request or let KMail send a "
01319 "\"denied\" or normal response.") },
01320 { "mdnUnknownOption", false,
01321 I18N_NOOP("This message contains a request to send a notification "
01322 "about your reception of the message.\n"
01323 "It contains a processing instruction that is marked as "
01324 "\"required\", but which is unknown to KMail.\n"
01325 "You can either ignore the request or let KMail send a "
01326 "\"failed\" response.") },
01327 { "mdnMultipleAddressesInReceiptTo", true,
01328 I18N_NOOP("This message contains a request to send a notification "
01329 "about your reception of the message,\n"
01330 "but it is requested to send the notification to more "
01331 "than one address.\n"
01332 "You can either ignore the request or let KMail send a "
01333 "\"denied\" or normal response.") },
01334 { "mdnReturnPathEmpty", true,
01335 I18N_NOOP("This message contains a request to send a notification "
01336 "about your reception of the message,\n"
01337 "but there is no return-path set.\n"
01338 "You can either ignore the request or let KMail send a "
01339 "\"denied\" or normal response.") },
01340 { "mdnReturnPathNotInReceiptTo", true,
01341 I18N_NOOP("This message contains a request to send a notification "
01342 "about your reception of the message,\n"
01343 "but the return-path address differs from the address "
01344 "the notification was requested to be sent to.\n"
01345 "You can either ignore the request or let KMail send a "
01346 "\"denied\" or normal response.") },
01347 };
01348
01349 static const int numMdnMessageBoxes
01350 = sizeof mdnMessageBoxes / sizeof *mdnMessageBoxes;
01351
01352
01353 static int requestAdviceOnMDN( const char * what ) {
01354 for ( int i = 0 ; i < numMdnMessageBoxes ; ++i )
01355 if ( !qstrcmp( what, mdnMessageBoxes[i].dontAskAgainID ) )
01356 if ( mdnMessageBoxes[i].canDeny ) {
01357 const KCursorSaver saver( QCursor::ArrowCursor );
01358 int answer = QMessageBox::information( 0,
01359 i18n("Message Disposition Notification Request"),
01360 i18n( mdnMessageBoxes[i].text ),
01361 i18n("&Ignore"), i18n("Send \"&denied\""), i18n("&Send") );
01362 return answer ? answer + 1 : 0 ;
01363 } else {
01364 const KCursorSaver saver( QCursor::ArrowCursor );
01365 int answer = QMessageBox::information( 0,
01366 i18n("Message Disposition Notification Request"),
01367 i18n( mdnMessageBoxes[i].text ),
01368 i18n("&Ignore"), i18n("&Send") );
01369 return answer ? answer + 2 : 0 ;
01370 }
01371 kdWarning(5006) << "didn't find data for message box \""
01372 << what << "\"" << endl;
01373 return 0;
01374 }
01375
01376 KMMessage* KMMessage::createMDN( MDN::ActionMode a,
01377 MDN::DispositionType d,
01378 bool allowGUI,
01379 QValueList<MDN::DispositionModifier> m )
01380 {
01381
01382
01383
01384
01385
01386
01387 #ifndef MDN_DEBUG
01388 if ( mdnSentState() != KMMsgMDNStateUnknown &&
01389 mdnSentState() != KMMsgMDNNone )
01390 return 0;
01391 #else
01392 char st[2]; st[0] = (char)mdnSentState(); st[1] = 0;
01393 kdDebug(5006) << "mdnSentState() == '" << st << "'" << endl;
01394 #endif
01395
01396
01397 if ( findDwBodyPart( DwMime::kTypeMessage,
01398 DwMime::kSubtypeDispositionNotification ) ) {
01399 setMDNSentState( KMMsgMDNIgnore );
01400 return 0;
01401 }
01402
01403
01404 QString receiptTo = headerField("Disposition-Notification-To");
01405 if ( receiptTo.stripWhiteSpace().isEmpty() ) return 0;
01406 receiptTo.remove( '\n' );
01407
01408
01409 MDN::SendingMode s = MDN::SentAutomatically;
01410 QString special;
01411 KConfigGroup mdnConfig( KMKernel::config(), "MDN" );
01412
01413
01414 int mode = mdnConfig.readNumEntry( "default-policy", 0 );
01415 if ( !mode || mode < 0 || mode > 3 ) {
01416
01417 setMDNSentState( KMMsgMDNIgnore );
01418 return 0;
01419 }
01420
01421
01422
01423
01424
01425
01426
01427 QString notificationOptions = headerField("Disposition-Notification-Options");
01428 if ( notificationOptions.contains( "required", false ) ) {
01429
01430
01431
01432 if ( !allowGUI ) return 0;
01433 mode = requestAdviceOnMDN( "mdnUnknownOption" );
01434 s = MDN::SentManually;
01435
01436 special = i18n("Header \"Disposition-Notification-Options\" contained "
01437 "required, but unknown parameter");
01438 d = MDN::Failed;
01439 m.clear();
01440 }
01441
01442
01443
01444
01445 kdDebug(5006) << "KPIM::splitEmailAddrList(receiptTo): "
01446 << KPIM::splitEmailAddrList(receiptTo).join("\n") << endl;
01447 if ( KPIM::splitEmailAddrList(receiptTo).count() > 1 ) {
01448 if ( !allowGUI ) return 0;
01449 mode = requestAdviceOnMDN( "mdnMultipleAddressesInReceiptTo" );
01450 s = MDN::SentManually;
01451 }
01452
01453
01454
01455
01456
01457
01458 AddrSpecList returnPathList = extractAddrSpecs("Return-Path");
01459 QString returnPath = returnPathList.isEmpty() ? QString::null
01460 : returnPathList.front().localPart + '@' + returnPathList.front().domain ;
01461 kdDebug(5006) << "clean return path: " << returnPath << endl;
01462 if ( returnPath.isEmpty() || !receiptTo.contains( returnPath, false ) ) {
01463 if ( !allowGUI ) return 0;
01464 mode = requestAdviceOnMDN( returnPath.isEmpty() ?
01465 "mdnReturnPathEmpty" :
01466 "mdnReturnPathNotInReceiptTo" );
01467 s = MDN::SentManually;
01468 }
01469
01470 if ( a != KMime::MDN::AutomaticAction ) {
01471
01472 if ( mode == 1 ) {
01473 if ( !allowGUI ) return 0;
01474 mode = requestAdviceOnMDN( "mdnNormalAsk" );
01475 s = MDN::SentManually;
01476 }
01477
01478 switch ( mode ) {
01479 case 0:
01480 setMDNSentState( KMMsgMDNIgnore );
01481 return 0;
01482 default:
01483 case 1:
01484 kdFatal(5006) << "KMMessage::createMDN(): The \"ask\" mode should "
01485 << "never appear here!" << endl;
01486 break;
01487 case 2:
01488 d = MDN::Denied;
01489 m.clear();
01490 break;
01491 case 3:
01492 break;
01493 }
01494 }
01495
01496
01497
01498 QString finalRecipient = kmkernel->identityManager()
01499 ->identityForUoidOrDefault( identityUoid() ).fullEmailAddr();
01500
01501
01502
01503
01504
01505 KMMessage * receipt = new KMMessage();
01506 receipt->initFromMessage( this );
01507 receipt->removeHeaderField("Content-Type");
01508 receipt->removeHeaderField("Content-Transfer-Encoding");
01509
01510 DwHeaders & header = receipt->mMsg->Headers();
01511 header.MimeVersion().FromString("1.0");
01512 DwMediaType & contentType = receipt->dwContentType();
01513 contentType.SetType( DwMime::kTypeMultipart );
01514 contentType.SetSubtype( DwMime::kSubtypeReport );
01515 contentType.CreateBoundary(0);
01516 receipt->mNeedsAssembly = true;
01517 receipt->setContentTypeParam( "report-type", "disposition-notification" );
01518
01519 QString description = replaceHeadersInString( MDN::descriptionFor( d, m ) );
01520
01521
01522 KMMessagePart firstMsgPart;
01523 firstMsgPart.setTypeStr( "text" );
01524 firstMsgPart.setSubtypeStr( "plain" );
01525 firstMsgPart.setBodyFromUnicode( description );
01526 receipt->addBodyPart( &firstMsgPart );
01527
01528
01529 KMMessagePart secondMsgPart;
01530 secondMsgPart.setType( DwMime::kTypeMessage );
01531 secondMsgPart.setSubtype( DwMime::kSubtypeDispositionNotification );
01532
01533
01534 secondMsgPart.setBodyEncoded( MDN::dispositionNotificationBodyContent(
01535 finalRecipient,
01536 rawHeaderField("Original-Recipient"),
01537 id(),
01538 d, a, s, m, special ) );
01539 receipt->addBodyPart( &secondMsgPart );
01540
01541
01542 int num = mdnConfig.readNumEntry( "quote-message", 0 );
01543 if ( num < 0 || num > 2 ) num = 0;
01544 MDN::ReturnContent returnContent = static_cast<MDN::ReturnContent>( num );
01545
01546 KMMessagePart thirdMsgPart;
01547 switch ( returnContent ) {
01548 case MDN::All:
01549 thirdMsgPart.setTypeStr( "message" );
01550 thirdMsgPart.setSubtypeStr( "rfc822" );
01551 thirdMsgPart.setBody( asSendableString() );
01552 receipt->addBodyPart( &thirdMsgPart );
01553 break;
01554 case MDN::HeadersOnly:
01555 thirdMsgPart.setTypeStr( "text" );
01556 thirdMsgPart.setSubtypeStr( "rfc822-headers" );
01557 thirdMsgPart.setBody( headerAsSendableString() );
01558 receipt->addBodyPart( &thirdMsgPart );
01559 break;
01560 case MDN::Nothing:
01561 default:
01562 break;
01563 };
01564
01565 receipt->setTo( receiptTo );
01566 receipt->setSubject( "Message Disposition Notification" );
01567 receipt->setReplyToId( msgId() );
01568 receipt->setReferences( getRefStr() );
01569
01570 receipt->cleanupHeader();
01571
01572 kdDebug(5006) << "final message:\n" + receipt->asString() << endl;
01573
01574
01575
01576
01577 KMMsgMDNSentState state = KMMsgMDNStateUnknown;
01578 switch ( d ) {
01579 case MDN::Displayed: state = KMMsgMDNDisplayed; break;
01580 case MDN::Deleted: state = KMMsgMDNDeleted; break;
01581 case MDN::Dispatched: state = KMMsgMDNDispatched; break;
01582 case MDN::Processed: state = KMMsgMDNProcessed; break;
01583 case MDN::Denied: state = KMMsgMDNDenied; break;
01584 case MDN::Failed: state = KMMsgMDNFailed; break;
01585 };
01586 setMDNSentState( state );
01587
01588 return receipt;
01589 }
01590
01591 QString KMMessage::replaceHeadersInString( const QString & s ) const {
01592 QString result = s;
01593 QRegExp rx( "\\$\\{([a-z0-9-]+)\\}", false );
01594 Q_ASSERT( rx.isValid() );
01595
01596 QRegExp rxDate( "\\$\\{date\\}" );
01597 Q_ASSERT( rxDate.isValid() );
01598
01599 QString sDate = KMime::DateFormatter::formatDate(
01600 KMime::DateFormatter::Localized, date() );
01601
01602 int idx = 0;
01603 if( ( idx = rxDate.search( result, idx ) ) != -1 ) {
01604 result.replace( idx, rxDate.matchedLength(), sDate );
01605 }
01606
01607 idx = 0;
01608 while ( ( idx = rx.search( result, idx ) ) != -1 ) {
01609 QString replacement = headerField( rx.cap(1).latin1() );
01610 result.replace( idx, rx.matchedLength(), replacement );
01611 idx += replacement.length();
01612 }
01613 return result;
01614 }
01615
01616 KMMessage* KMMessage::createDeliveryReceipt() const
01617 {
01618 QString str, receiptTo;
01619 KMMessage *receipt;
01620
01621 receiptTo = headerField("Disposition-Notification-To");
01622 if ( receiptTo.stripWhiteSpace().isEmpty() ) return 0;
01623 receiptTo.remove( '\n' );
01624
01625 receipt = new KMMessage;
01626 receipt->initFromMessage(this);
01627 receipt->setTo(receiptTo);
01628 receipt->setSubject(i18n("Receipt: ") + subject());
01629
01630 str = "Your message was successfully delivered.";
01631 str += "\n\n---------- Message header follows ----------\n";
01632 str += headerAsString();
01633 str += "--------------------------------------------\n";
01634
01635
01636 receipt->setBody(str.latin1());
01637 receipt->setAutomaticFields();
01638
01639 return receipt;
01640 }
01641
01642
01643 void KMMessage::applyIdentity( uint id )
01644 {
01645 const KPIM::Identity & ident =
01646 kmkernel->identityManager()->identityForUoidOrDefault( id );
01647
01648 if(ident.fullEmailAddr().isEmpty())
01649 setFrom("");
01650 else
01651 setFrom(ident.fullEmailAddr());
01652
01653 if(ident.replyToAddr().isEmpty())
01654 setReplyTo("");
01655 else
01656 setReplyTo(ident.replyToAddr());
01657
01658 if(ident.bcc().isEmpty())
01659 setBcc("");
01660 else
01661 setBcc(ident.bcc());
01662
01663 if (ident.organization().isEmpty())
01664 removeHeaderField("Organization");
01665 else
01666 setHeaderField("Organization", ident.organization());
01667
01668 if (ident.isDefault())
01669 removeHeaderField("X-KMail-Identity");
01670 else
01671 setHeaderField("X-KMail-Identity", QString::number( ident.uoid() ));
01672
01673 if ( ident.transport().isEmpty() )
01674 removeHeaderField( "X-KMail-Transport" );
01675 else
01676 setHeaderField( "X-KMail-Transport", ident.transport() );
01677
01678 if ( ident.fcc().isEmpty() )
01679 setFcc( QString::null );
01680 else
01681 setFcc( ident.fcc() );
01682
01683 if ( ident.drafts().isEmpty() )
01684 setDrafts( QString::null );
01685 else
01686 setDrafts( ident.drafts() );
01687
01688 if ( ident.templates().isEmpty() )
01689 setTemplates( QString::null );
01690 else
01691 setTemplates( ident.templates() );
01692
01693 }
01694
01695
01696 void KMMessage::initHeader( uint id )
01697 {
01698 applyIdentity( id );
01699 setTo("");
01700 setSubject("");
01701 setDateToday();
01702
01703 setHeaderField("User-Agent", "KMail/" KMAIL_VERSION );
01704
01705 setHeaderField("Content-Type","text/plain");
01706 }
01707
01708 uint KMMessage::identityUoid() const {
01709 QString idString = headerField("X-KMail-Identity").stripWhiteSpace();
01710 bool ok = false;
01711 int id = idString.toUInt( &ok );
01712
01713 if ( !ok || id == 0 )
01714 id = kmkernel->identityManager()->identityForAddress( to() + ", " + cc() ).uoid();
01715 if ( id == 0 && parent() )
01716 id = parent()->identity();
01717
01718 return id;
01719 }
01720
01721
01722
01723 void KMMessage::initFromMessage(const KMMessage *msg, bool idHeaders)
01724 {
01725 uint id = msg->identityUoid();
01726
01727 if ( idHeaders ) initHeader(id);
01728 else setHeaderField("X-KMail-Identity", QString::number(id));
01729 if (!msg->headerField("X-KMail-Transport").isEmpty())
01730 setHeaderField("X-KMail-Transport", msg->headerField("X-KMail-Transport"));
01731 }
01732
01733
01734
01735 void KMMessage::cleanupHeader()
01736 {
01737 DwHeaders& header = mMsg->Headers();
01738 DwField* field = header.FirstField();
01739 DwField* nextField;
01740
01741 if (mNeedsAssembly) mMsg->Assemble();
01742 mNeedsAssembly = false;
01743
01744 while (field)
01745 {
01746 nextField = field->Next();
01747 if (field->FieldBody()->AsString().empty())
01748 {
01749 header.RemoveField(field);
01750 mNeedsAssembly = true;
01751 }
01752 field = nextField;
01753 }
01754 }
01755
01756
01757
01758 void KMMessage::setAutomaticFields(bool aIsMulti)
01759 {
01760 DwHeaders& header = mMsg->Headers();
01761 header.MimeVersion().FromString("1.0");
01762
01763 if (aIsMulti || numBodyParts() > 1)
01764 {
01765
01766 DwMediaType& contentType = dwContentType();
01767 contentType.SetType( DwMime::kTypeMultipart);
01768 contentType.SetSubtype(DwMime::kSubtypeMixed );
01769
01770
01771 contentType.CreateBoundary(0);
01772 }
01773 mNeedsAssembly = true;
01774 }
01775
01776
01777
01778 QString KMMessage::dateStr() const
01779 {
01780 KConfigGroup general( KMKernel::config(), "General" );
01781 DwHeaders& header = mMsg->Headers();
01782 time_t unixTime;
01783
01784 if (!header.HasDate()) return "";
01785 unixTime = header.Date().AsUnixTime();
01786
01787
01788
01789 return KMime::DateFormatter::formatDate(
01790 static_cast<KMime::DateFormatter::FormatType>(general.readNumEntry( "dateFormat", KMime::DateFormatter::Fancy )),
01791 unixTime, general.readEntry( "customDateFormat" ));
01792 }
01793
01794
01795
01796 QCString KMMessage::dateShortStr() const
01797 {
01798 DwHeaders& header = mMsg->Headers();
01799 time_t unixTime;
01800
01801 if (!header.HasDate()) return "";
01802 unixTime = header.Date().AsUnixTime();
01803
01804 QCString result = ctime(&unixTime);
01805 int len = result.length();
01806 if (result[len-1]=='\n')
01807 result.truncate(len-1);
01808
01809 return result;
01810 }
01811
01812
01813
01814 QString KMMessage::dateIsoStr() const
01815 {
01816 DwHeaders& header = mMsg->Headers();
01817 time_t unixTime;
01818
01819 if (!header.HasDate()) return "";
01820 unixTime = header.Date().AsUnixTime();
01821
01822 char cstr[64];
01823 strftime(cstr, 63, "%Y-%m-%d %H:%M:%S", localtime(&unixTime));
01824 return QString(cstr);
01825 }
01826
01827
01828
01829 time_t KMMessage::date() const
01830 {
01831 time_t res = ( time_t )-1;
01832 DwHeaders& header = mMsg->Headers();
01833 if (header.HasDate())
01834 res = header.Date().AsUnixTime();
01835 return res;
01836 }
01837
01838
01839
01840 void KMMessage::setDateToday()
01841 {
01842 struct timeval tval;
01843 gettimeofday(&tval, 0);
01844 setDate((time_t)tval.tv_sec);
01845 }
01846
01847
01848
01849 void KMMessage::setDate(time_t aDate)
01850 {
01851 mDate = aDate;
01852 mMsg->Headers().Date().FromCalendarTime(aDate);
01853 mMsg->Headers().Date().Assemble();
01854 mNeedsAssembly = true;
01855 mDirty = true;
01856 }
01857
01858
01859
01860 void KMMessage::setDate(const QCString& aStr)
01861 {
01862 DwHeaders& header = mMsg->Headers();
01863
01864 header.Date().FromString(aStr);
01865 header.Date().Parse();
01866 mNeedsAssembly = true;
01867 mDirty = true;
01868
01869 if (header.HasDate())
01870 mDate = header.Date().AsUnixTime();
01871 }
01872
01873
01874
01875 QString KMMessage::to() const
01876 {
01877
01878 QValueList<QCString> rawHeaders = rawHeaderFields( "To" );
01879 QStringList headers;
01880 for ( QValueList<QCString>::Iterator it = rawHeaders.begin(); it != rawHeaders.end(); ++it ) {
01881 headers << *it;
01882 }
01883 return KPIM::normalizeAddressesAndDecodeIDNs( headers.join( ", " ) );
01884 }
01885
01886
01887
01888 void KMMessage::setTo(const QString& aStr)
01889 {
01890 setHeaderField( "To", aStr, Address );
01891 }
01892
01893
01894 QString KMMessage::toStrip() const
01895 {
01896 return stripEmailAddr( to() );
01897 }
01898
01899
01900 QString KMMessage::replyTo() const
01901 {
01902 return KPIM::normalizeAddressesAndDecodeIDNs( rawHeaderField("Reply-To") );
01903 }
01904
01905
01906
01907 void KMMessage::setReplyTo(const QString& aStr)
01908 {
01909 setHeaderField( "Reply-To", aStr, Address );
01910 }
01911
01912
01913
01914 void KMMessage::setReplyTo(KMMessage* aMsg)
01915 {
01916 setHeaderField( "Reply-To", aMsg->from(), Address );
01917 }
01918
01919
01920
01921 QString KMMessage::cc() const
01922 {
01923
01924
01925 QValueList<QCString> rawHeaders = rawHeaderFields( "Cc" );
01926 QStringList headers;
01927 for ( QValueList<QCString>::Iterator it = rawHeaders.begin(); it != rawHeaders.end(); ++it ) {
01928 headers << *it;
01929 }
01930 return KPIM::normalizeAddressesAndDecodeIDNs( headers.join( ", " ) );
01931 }
01932
01933
01934
01935 void KMMessage::setCc(const QString& aStr)
01936 {
01937 setHeaderField( "Cc", aStr, Address );
01938 }
01939
01940
01941
01942 QString KMMessage::ccStrip() const
01943 {
01944 return stripEmailAddr( cc() );
01945 }
01946
01947
01948
01949 QString KMMessage::bcc() const
01950 {
01951 return KPIM::normalizeAddressesAndDecodeIDNs( rawHeaderField("Bcc") );
01952 }
01953
01954
01955
01956 void KMMessage::setBcc(const QString& aStr)
01957 {
01958 setHeaderField( "Bcc", aStr, Address );
01959 }
01960
01961
01962 QString KMMessage::fcc() const
01963 {
01964 return headerField( "X-KMail-Fcc" );
01965 }
01966
01967
01968
01969 void KMMessage::setFcc( const QString &aStr )
01970 {
01971 setHeaderField( "X-KMail-Fcc", aStr );
01972 }
01973
01974
01975 void KMMessage::setDrafts( const QString &aStr )
01976 {
01977 mDrafts = aStr;
01978 }
01979
01980
01981 void KMMessage::setTemplates( const QString &aStr )
01982 {
01983 mTemplates = aStr;
01984 }
01985
01986
01987 QString KMMessage::who() const
01988 {
01989 if (mParent)
01990 return KPIM::normalizeAddressesAndDecodeIDNs( rawHeaderField(mParent->whoField().utf8()) );
01991 return from();
01992 }
01993
01994
01995
01996 QString KMMessage::from() const
01997 {
01998 return KPIM::normalizeAddressesAndDecodeIDNs( rawHeaderField("From") );
01999 }
02000
02001
02002
02003 void KMMessage::setFrom(const QString& bStr)
02004 {
02005 QString aStr = bStr;
02006 if (aStr.isNull())
02007 aStr = "";
02008 setHeaderField( "From", aStr, Address );
02009 mDirty = true;
02010 }
02011
02012
02013
02014 QString KMMessage::fromStrip() const
02015 {
02016 return stripEmailAddr( from() );
02017 }
02018
02019
02020 QString KMMessage::sender() const {
02021 AddrSpecList asl = extractAddrSpecs( "Sender" );
02022 if ( asl.empty() )
02023 asl = extractAddrSpecs( "From" );
02024 if ( asl.empty() )
02025 return QString::null;
02026 return asl.front().asString();
02027 }
02028
02029
02030 QString KMMessage::subject() const
02031 {
02032 return headerField("Subject");
02033 }
02034
02035
02036
02037 void KMMessage::setSubject(const QString& aStr)
02038 {
02039 setHeaderField("Subject",aStr);
02040 mDirty = true;
02041 }
02042
02043
02044
02045 QString KMMessage::xmark() const
02046 {
02047 return headerField("X-KMail-Mark");
02048 }
02049
02050
02051
02052 void KMMessage::setXMark(const QString& aStr)
02053 {
02054 setHeaderField("X-KMail-Mark", aStr);
02055 mDirty = true;
02056 }
02057
02058
02059
02060 QString KMMessage::replyToId() const
02061 {
02062 int leftAngle, rightAngle;
02063 QString replyTo, references;
02064
02065 replyTo = headerField("In-Reply-To");
02066
02067 rightAngle = replyTo.find( '>' );
02068 if (rightAngle != -1)
02069 replyTo.truncate( rightAngle + 1 );
02070
02071 leftAngle = replyTo.findRev( '<' );
02072 if (leftAngle != -1)
02073 replyTo = replyTo.mid( leftAngle );
02074
02075
02076
02077
02078
02079 if (!replyTo.isEmpty() && (replyTo[0] == '<') &&
02080 ( -1 == replyTo.find( '"' ) ) )
02081 return replyTo;
02082
02083 references = headerField("References");
02084 leftAngle = references.findRev( '<' );
02085 if (leftAngle != -1)
02086 references = references.mid( leftAngle );
02087 rightAngle = references.find( '>' );
02088 if (rightAngle != -1)
02089 references.truncate( rightAngle + 1 );
02090
02091
02092 if (!references.isEmpty() && references[0] == '<')
02093 return references;
02094
02095 else
02096 return replyTo;
02097 }
02098
02099
02100
02101 QString KMMessage::replyToIdMD5() const {
02102 return base64EncodedMD5( replyToId() );
02103 }
02104
02105
02106 QString KMMessage::references() const
02107 {
02108 int leftAngle, rightAngle;
02109 QString references = headerField( "References" );
02110
02111
02112 leftAngle = references.findRev( '<' );
02113 leftAngle = references.findRev( '<', leftAngle - 1 );
02114 if( leftAngle != -1 )
02115 references = references.mid( leftAngle );
02116 rightAngle = references.findRev( '>' );
02117 if( rightAngle != -1 )
02118 references.truncate( rightAngle + 1 );
02119
02120 if( !references.isEmpty() && references[0] == '<' )
02121 return references;
02122 else
02123 return QString::null;
02124 }
02125
02126
02127 QString KMMessage::replyToAuxIdMD5() const
02128 {
02129 QString result = references();
02130
02131
02132 const int rightAngle = result.find( '>' );
02133 if( rightAngle != -1 )
02134 result.truncate( rightAngle + 1 );
02135
02136 return base64EncodedMD5( result );
02137 }
02138
02139
02140 QString KMMessage::strippedSubjectMD5() const {
02141 return base64EncodedMD5( stripOffPrefixes( subject() ), true );
02142 }
02143
02144
02145 QString KMMessage::subjectMD5() const {
02146 return base64EncodedMD5( subject(), true );
02147 }
02148
02149
02150 bool KMMessage::subjectIsPrefixed() const {
02151 return subjectMD5() != strippedSubjectMD5();
02152 }
02153
02154
02155 void KMMessage::setReplyToId(const QString& aStr)
02156 {
02157 setHeaderField("In-Reply-To", aStr);
02158 mDirty = true;
02159 }
02160
02161
02162
02163 QString KMMessage::msgId() const
02164 {
02165 QString msgId = headerField("Message-Id");
02166
02167
02168 const int rightAngle = msgId.find( '>' );
02169 if (rightAngle != -1)
02170 msgId.truncate( rightAngle + 1 );
02171
02172 const int leftAngle = msgId.findRev( '<' );
02173 if (leftAngle != -1)
02174 msgId = msgId.mid( leftAngle );
02175 return msgId;
02176 }
02177
02178
02179
02180 QString KMMessage::msgIdMD5() const {
02181 return base64EncodedMD5( msgId() );
02182 }
02183
02184
02185
02186 void KMMessage::setMsgId(const QString& aStr)
02187 {
02188 setHeaderField("Message-Id", aStr);
02189 mDirty = true;
02190 }
02191
02192
02193 size_t KMMessage::msgSizeServer() const {
02194 return headerField( "X-Length" ).toULong();
02195 }
02196
02197
02198
02199 void KMMessage::setMsgSizeServer(size_t size)
02200 {
02201 setHeaderField("X-Length", QCString().setNum(size));
02202 mDirty = true;
02203 }
02204
02205
02206 ulong KMMessage::UID() const {
02207 return headerField( "X-UID" ).toULong();
02208 }
02209
02210
02211
02212 void KMMessage::setUID(ulong uid)
02213 {
02214 setHeaderField("X-UID", QCString().setNum(uid));
02215 mDirty = true;
02216 }
02217
02218
02219 AddressList KMMessage::splitAddrField( const QCString & str )
02220 {
02221 AddressList result;
02222 const char * scursor = str.begin();
02223 if ( !scursor )
02224 return AddressList();
02225 const char * const send = str.begin() + str.length();
02226 if ( !parseAddressList( scursor, send, result ) )
02227 kdDebug(5006) << "Error in address splitting: parseAddressList returned false!"
02228 << endl;
02229 return result;
02230 }
02231
02232 AddressList KMMessage::headerAddrField( const QCString & aName ) const {
02233 return KMMessage::splitAddrField( rawHeaderField( aName ) );
02234 }
02235
02236 AddrSpecList KMMessage::extractAddrSpecs( const QCString & header ) const {
02237 AddressList al = headerAddrField( header );
02238 AddrSpecList result;
02239 for ( AddressList::const_iterator ait = al.begin() ; ait != al.end() ; ++ait )
02240 for ( MailboxList::const_iterator mit = (*ait).mailboxList.begin() ; mit != (*ait).mailboxList.end() ; ++mit )
02241 result.push_back( (*mit).addrSpec );
02242 return result;
02243 }
02244
02245 QCString KMMessage::rawHeaderField( const QCString & name ) const {
02246 if ( name.isEmpty() ) return QCString();
02247
02248 DwHeaders & header = mMsg->Headers();
02249 DwField * field = header.FindField( name );
02250
02251 if ( !field ) return QCString();
02252
02253 return header.FieldBody( name.data() ).AsString().c_str();
02254 }
02255
02256 QValueList<QCString> KMMessage::rawHeaderFields( const QCString& field ) const
02257 {
02258 if ( field.isEmpty() || !mMsg->Headers().FindField( field ) )
02259 return QValueList<QCString>();
02260
02261 std::vector<DwFieldBody*> v = mMsg->Headers().AllFieldBodies( field.data() );
02262 QValueList<QCString> headerFields;
02263 for ( uint i = 0; i < v.size(); ++i ) {
02264 headerFields.append( v[i]->AsString().c_str() );
02265 }
02266
02267 return headerFields;
02268 }
02269
02270 QString KMMessage::headerField(const QCString& aName) const
02271 {
02272 if ( aName.isEmpty() )
02273 return QString::null;
02274
02275 if ( !mMsg->Headers().FindField( aName ) )
02276 return QString::null;
02277
02278 return decodeRFC2047String( mMsg->Headers().FieldBody( aName.data() ).AsString().c_str(),
02279 charset() );
02280
02281 }
02282
02283 QStringList KMMessage::headerFields( const QCString& field ) const
02284 {
02285 if ( field.isEmpty() || !mMsg->Headers().FindField( field ) )
02286 return QStringList();
02287
02288 std::vector<DwFieldBody*> v = mMsg->Headers().AllFieldBodies( field.data() );
02289 QStringList headerFields;
02290 for ( uint i = 0; i < v.size(); ++i ) {
02291 headerFields.append( decodeRFC2047String( v[i]->AsString().c_str(), charset() ) );
02292 }
02293
02294 return headerFields;
02295 }
02296
02297
02298 void KMMessage::removeHeaderField(const QCString& aName)
02299 {
02300 DwHeaders & header = mMsg->Headers();
02301 DwField * field = header.FindField(aName);
02302 if (!field) return;
02303
02304 header.RemoveField(field);
02305 mNeedsAssembly = true;
02306 }
02307
02308
02309 void KMMessage::removeHeaderFields(const QCString& aName)
02310 {
02311 DwHeaders & header = mMsg->Headers();
02312 while ( DwField * field = header.FindField(aName) ) {
02313 header.RemoveField(field);
02314 mNeedsAssembly = true;
02315 }
02316 }
02317
02318
02319
02320 void KMMessage::setHeaderField( const QCString& aName, const QString& bValue,
02321 HeaderFieldType type, bool prepend )
02322 {
02323 #if 0
02324 if ( type != Unstructured )
02325 kdDebug(5006) << "KMMessage::setHeaderField( \"" << aName << "\", \""
02326 << bValue << "\", " << type << " )" << endl;
02327 #endif
02328 if (aName.isEmpty()) return;
02329
02330 DwHeaders& header = mMsg->Headers();
02331
02332 DwString str;
02333 DwField* field;
02334 QCString aValue;
02335 if (!bValue.isEmpty())
02336 {
02337 QString value = bValue;
02338 if ( type == Address )
02339 value = KPIM::normalizeAddressesAndEncodeIDNs( value );
02340 #if 0
02341 if ( type != Unstructured )
02342 kdDebug(5006) << "value: \"" << value << "\"" << endl;
02343 #endif
02344 QCString encoding = autoDetectCharset( charset(), sPrefCharsets, value );
02345 if (encoding.isEmpty())
02346 encoding = "utf-8";
02347 aValue = encodeRFC2047String( value, encoding );
02348 #if 0
02349 if ( type != Unstructured )
02350 kdDebug(5006) << "aValue: \"" << aValue << "\"" << endl;
02351 #endif
02352 }
02353 str = aName;
02354 if (str[str.length()-1] != ':') str += ": ";
02355 else str += ' ';
02356 if ( !aValue.isEmpty() )
02357 str += aValue;
02358 if (str[str.length()-1] != '\n') str += '\n';
02359
02360 field = new DwField(str, mMsg);
02361 field->Parse();
02362
02363 if ( prepend )
02364 header.AddFieldAt( 1, field );
02365 else
02366 header.AddOrReplaceField( field );
02367 mNeedsAssembly = true;
02368 }
02369
02370
02371
02372 QCString KMMessage::typeStr() const
02373 {
02374 DwHeaders& header = mMsg->Headers();
02375 if (header.HasContentType()) return header.ContentType().TypeStr().c_str();
02376 else return "";
02377 }
02378
02379
02380
02381 int KMMessage::type() const
02382 {
02383 DwHeaders& header = mMsg->Headers();
02384 if (header.HasContentType()) return header.ContentType().Type();
02385 else return DwMime::kTypeNull;
02386 }
02387
02388
02389
02390 void KMMessage::setTypeStr(const QCString& aStr)
02391 {
02392 dwContentType().SetTypeStr(DwString(aStr));
02393 dwContentType().Parse();
02394 mNeedsAssembly = true;
02395 }
02396
02397
02398
02399 void KMMessage::setType(int aType)
02400 {
02401 dwContentType().SetType(aType);
02402 dwContentType().Assemble();
02403 mNeedsAssembly = true;
02404 }
02405
02406
02407
02408
02409 QCString KMMessage::subtypeStr() const
02410 {
02411 DwHeaders& header = mMsg->Headers();
02412 if (header.HasContentType()) return header.ContentType().SubtypeStr().c_str();
02413 else return "";
02414 }
02415
02416
02417
02418 int KMMessage::subtype() const
02419 {
02420 DwHeaders& header = mMsg->Headers();
02421 if (header.HasContentType()) return header.ContentType().Subtype();
02422 else return DwMime::kSubtypeNull;
02423 }
02424
02425
02426
02427 void KMMessage::setSubtypeStr(const QCString& aStr)
02428 {
02429 dwContentType().SetSubtypeStr(DwString(aStr));
02430 dwContentType().Parse();
02431 mNeedsAssembly = true;
02432 }
02433
02434
02435
02436 void KMMessage::setSubtype(int aSubtype)
02437 {
02438 dwContentType().SetSubtype(aSubtype);
02439 dwContentType().Assemble();
02440 mNeedsAssembly = true;
02441 }
02442
02443
02444
02445 void KMMessage::setDwMediaTypeParam( DwMediaType &mType,
02446 const QCString& attr,
02447 const QCString& val )
02448 {
02449 mType.Parse();
02450 DwParameter *param = mType.FirstParameter();
02451 while(param) {
02452 if (!kasciistricmp(param->Attribute().c_str(), attr))
02453 break;
02454 else
02455 param = param->Next();
02456 }
02457 if (!param){
02458 param = new DwParameter;
02459 param->SetAttribute(DwString( attr ));
02460 mType.AddParameter( param );
02461 }
02462 else
02463 mType.SetModified();
02464 param->SetValue(DwString( val ));
02465 mType.Assemble();
02466 }
02467
02468
02469
02470 void KMMessage::setContentTypeParam(const QCString& attr, const QCString& val)
02471 {
02472 if (mNeedsAssembly) mMsg->Assemble();
02473 mNeedsAssembly = false;
02474 setDwMediaTypeParam( dwContentType(), attr, val );
02475 mNeedsAssembly = true;
02476 }
02477
02478
02479
02480 QCString KMMessage::contentTransferEncodingStr() const
02481 {
02482 DwHeaders& header = mMsg->Headers();
02483 if (header.HasContentTransferEncoding())
02484 return header.ContentTransferEncoding().AsString().c_str();
02485 else return "";
02486 }
02487
02488
02489
02490 int KMMessage::contentTransferEncoding( DwEntity *entity ) const
02491 {
02492 if ( !entity )
02493 entity = mMsg;
02494
02495 DwHeaders& header = entity->Headers();
02496 if ( header.HasContentTransferEncoding() )
02497 return header.ContentTransferEncoding().AsEnum();
02498 else return DwMime::kCteNull;
02499 }
02500
02501
02502
02503 void KMMessage::setContentTransferEncodingStr( const QCString& cteString,
02504 DwEntity *entity )
02505 {
02506 if ( !entity )
02507 entity = mMsg;
02508
02509 entity->Headers().ContentTransferEncoding().FromString( cteString );
02510 entity->Headers().ContentTransferEncoding().Parse();
02511 mNeedsAssembly = true;
02512 }
02513
02514
02515
02516 void KMMessage::setContentTransferEncoding( int cte, DwEntity *entity )
02517 {
02518 if ( !entity )
02519 entity = mMsg;
02520
02521 entity->Headers().ContentTransferEncoding().FromEnum( cte );
02522 mNeedsAssembly = true;
02523 }
02524
02525
02526
02527 DwHeaders& KMMessage::headers() const
02528 {
02529 return mMsg->Headers();
02530 }
02531
02532
02533
02534 void KMMessage::setNeedsAssembly()
02535 {
02536 mNeedsAssembly = true;
02537 }
02538
02539
02540
02541 QCString KMMessage::body() const
02542 {
02543 const DwString& body = mMsg->Body().AsString();
02544 QCString str = KMail::Util::CString( body );
02545
02546
02547
02548 return str;
02549 }
02550
02551
02552
02553 QByteArray KMMessage::bodyDecodedBinary() const
02554 {
02555 DwString dwstr;
02556 const DwString& dwsrc = mMsg->Body().AsString();
02557
02558 switch (cte())
02559 {
02560 case DwMime::kCteBase64:
02561 DwDecodeBase64(dwsrc, dwstr);
02562 break;
02563 case DwMime::kCteQuotedPrintable:
02564 DwDecodeQuotedPrintable(dwsrc, dwstr);
02565 break;
02566 default:
02567 dwstr = dwsrc;
02568 break;
02569 }
02570
02571 int len = dwstr.size();
02572 QByteArray ba(len);
02573 memcpy(ba.data(),dwstr.data(),len);
02574 return ba;
02575 }
02576
02577
02578
02579 QCString KMMessage::bodyDecoded() const
02580 {
02581 DwString dwstr;
02582 DwString dwsrc = mMsg->Body().AsString();
02583
02584 switch (cte())
02585 {
02586 case DwMime::kCteBase64:
02587 DwDecodeBase64(dwsrc, dwstr);
02588 break;
02589 case DwMime::kCteQuotedPrintable:
02590 DwDecodeQuotedPrintable(dwsrc, dwstr);
02591 break;
02592 default:
02593 dwstr = dwsrc;
02594 break;
02595 }
02596
02597 return KMail::Util::CString( dwstr );
02598
02599
02600
02601
02602
02603
02604 }
02605
02606
02607
02608 QValueList<int> KMMessage::determineAllowedCtes( const CharFreq& cf,
02609 bool allow8Bit,
02610 bool willBeSigned )
02611 {
02612 QValueList<int> allowedCtes;
02613
02614 switch ( cf.type() ) {
02615 case CharFreq::SevenBitText:
02616 allowedCtes << DwMime::kCte7bit;
02617 case CharFreq::EightBitText:
02618 if ( allow8Bit )
02619 allowedCtes << DwMime::kCte8bit;
02620 case CharFreq::SevenBitData:
02621 if ( cf.printableRatio() > 5.0/6.0 ) {
02622
02623
02624
02625 allowedCtes << DwMime::kCteQp;
02626 allowedCtes << DwMime::kCteBase64;
02627 } else {
02628 allowedCtes << DwMime::kCteBase64;
02629 allowedCtes << DwMime::kCteQp;
02630 }
02631 break;
02632 case CharFreq::EightBitData:
02633 allowedCtes << DwMime::kCteBase64;
02634 break;
02635 case CharFreq::None:
02636 default:
02637
02638 ;
02639 }
02640
02641
02642
02643
02644
02645 if ( ( willBeSigned && cf.hasTrailingWhitespace() ) ||
02646 cf.hasLeadingFrom() ) {
02647 allowedCtes.remove( DwMime::kCte8bit );
02648 allowedCtes.remove( DwMime::kCte7bit );
02649 }
02650
02651 return allowedCtes;
02652 }
02653
02654
02655
02656 void KMMessage::setBodyAndGuessCte( const QByteArray& aBuf,
02657 QValueList<int> & allowedCte,
02658 bool allow8Bit,
02659 bool willBeSigned,
02660 DwEntity *entity )
02661 {
02662 if ( !entity )
02663 entity = mMsg;
02664
02665 CharFreq cf( aBuf );
02666 allowedCte = determineAllowedCtes( cf, allow8Bit, willBeSigned );
02667 setCte( allowedCte[0], entity );
02668 setBodyEncodedBinary( aBuf, entity );
02669 }
02670
02671
02672
02673 void KMMessage::setBodyAndGuessCte( const QCString& aBuf,
02674 QValueList<int> & allowedCte,
02675 bool allow8Bit,
02676 bool willBeSigned,
02677 DwEntity *entity )
02678 {
02679 if ( !entity )
02680 entity = mMsg;
02681
02682 CharFreq cf( aBuf.data(), aBuf.size()-1 );
02683 allowedCte = determineAllowedCtes( cf, allow8Bit, willBeSigned );
02684 setCte( allowedCte[0], entity );
02685 setBodyEncoded( aBuf, entity );
02686 }
02687
02688
02689
02690 void KMMessage::setBodyEncoded(const QCString& aStr, DwEntity *entity )
02691 {
02692 if ( !entity )
02693 entity = mMsg;
02694
02695 DwString dwSrc(aStr.data(), aStr.size()-1 );
02696 DwString dwResult;
02697
02698 switch (cte( entity ))
02699 {
02700 case DwMime::kCteBase64:
02701 DwEncodeBase64(dwSrc, dwResult);
02702 break;
02703 case DwMime::kCteQuotedPrintable:
02704 DwEncodeQuotedPrintable(dwSrc, dwResult);
02705 break;
02706 default:
02707 dwResult = dwSrc;
02708 break;
02709 }
02710
02711 entity->Body().FromString(dwResult);
02712 mNeedsAssembly = true;
02713 }
02714
02715
02716 void KMMessage::setBodyEncodedBinary( const QByteArray& aStr, DwEntity *entity )
02717 {
02718 if ( !entity )
02719 entity = mMsg;
02720
02721 DwString dwSrc(aStr.data(), aStr.size());
02722 DwString dwResult;
02723
02724 switch ( cte( entity ) )
02725 {
02726 case DwMime::kCteBase64:
02727 DwEncodeBase64( dwSrc, dwResult );
02728 break;
02729 case DwMime::kCteQuotedPrintable:
02730 DwEncodeQuotedPrintable( dwSrc, dwResult );
02731 break;
02732 default:
02733 dwResult = dwSrc;
02734 break;
02735 }
02736
02737 entity->Body().FromString( dwResult );
02738 mNeedsAssembly = true;
02739 }
02740
02741
02742
02743 void KMMessage::setBody(const QCString& aStr)
02744 {
02745 mMsg->Body().FromString(KMail::Util::dwString(aStr));
02746 mNeedsAssembly = true;
02747 }
02748 void KMMessage::setBody(const DwString& aStr)
02749 {
02750 mMsg->Body().FromString(aStr);
02751 mNeedsAssembly = true;
02752 }
02753 void KMMessage::setBody(const char* aStr)
02754 {
02755 mMsg->Body().FromString(aStr);
02756 mNeedsAssembly = true;
02757 }
02758
02759
02760 void KMMessage::setMultiPartBody( const QCString & aStr ) {
02761 setBody( aStr );
02762 mMsg->Body().Parse();
02763 mNeedsAssembly = true;
02764 }
02765
02766
02767
02768
02769
02770
02771
02772
02773
02774
02775 int KMMessage::numBodyParts() const
02776 {
02777 int count = 0;
02778 DwBodyPart* part = getFirstDwBodyPart();
02779 QPtrList< DwBodyPart > parts;
02780
02781 while (part)
02782 {
02783
02784 while ( part
02785 && part->hasHeaders()
02786 && part->Headers().HasContentType()
02787 && part->Body().FirstBodyPart()
02788 && (DwMime::kTypeMultipart == part->Headers().ContentType().Type()) )
02789 {
02790 parts.append( part );
02791 part = part->Body().FirstBodyPart();
02792 }
02793
02794 count++;
02795
02796
02797 while (part && !(part->Next()) && !(parts.isEmpty()))
02798 {
02799 part = parts.getLast();
02800 parts.removeLast();
02801 }
02802
02803 if (part && part->Body().Message() &&
02804 part->Body().Message()->Body().FirstBodyPart())
02805 {
02806 part = part->Body().Message()->Body().FirstBodyPart();
02807 } else if (part) {
02808 part = part->Next();
02809 }
02810 }
02811
02812 return count;
02813 }
02814
02815
02816
02817 DwBodyPart * KMMessage::getFirstDwBodyPart() const
02818 {
02819 return mMsg->Body().FirstBodyPart();
02820 }
02821
02822
02823
02824 int KMMessage::partNumber( DwBodyPart * aDwBodyPart ) const
02825 {
02826 DwBodyPart *curpart;
02827 QPtrList< DwBodyPart > parts;
02828 int curIdx = 0;
02829 int idx = 0;
02830
02831
02832 curpart = getFirstDwBodyPart();
02833
02834 while (curpart && !idx) {
02835
02836 while( curpart
02837 && curpart->hasHeaders()
02838 && curpart->Headers().HasContentType()
02839 && curpart->Body().FirstBodyPart()
02840 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) )
02841 {
02842 parts.append( curpart );
02843 curpart = curpart->Body().FirstBodyPart();
02844 }
02845
02846 if (curpart == aDwBodyPart)
02847 idx = curIdx;
02848 curIdx++;
02849
02850
02851 while (curpart && !(curpart->Next()) && !(parts.isEmpty()))
02852 {
02853 curpart = parts.getLast();
02854 parts.removeLast();
02855 } ;
02856 if (curpart)
02857 curpart = curpart->Next();
02858 }
02859 return idx;
02860 }
02861
02862
02863
02864 DwBodyPart * KMMessage::dwBodyPart( int aIdx ) const
02865 {
02866 DwBodyPart *part, *curpart;
02867 QPtrList< DwBodyPart > parts;
02868 int curIdx = 0;
02869
02870
02871 curpart = getFirstDwBodyPart();
02872 part = 0;
02873
02874 while (curpart && !part) {
02875
02876 while( curpart
02877 && curpart->hasHeaders()
02878 && curpart->Headers().HasContentType()
02879 && curpart->Body().FirstBodyPart()
02880 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) )
02881 {
02882 parts.append( curpart );
02883 curpart = curpart->Body().FirstBodyPart();
02884 }
02885
02886 if (curIdx==aIdx)
02887 part = curpart;
02888 curIdx++;
02889
02890
02891 while (curpart && !(curpart->Next()) && !(parts.isEmpty()))
02892 {
02893 curpart = parts.getLast();
02894 parts.removeLast();
02895 }
02896 if (curpart)
02897 curpart = curpart->Next();
02898 }
02899 return part;
02900 }
02901
02902
02903
02904 DwBodyPart * KMMessage::findDwBodyPart( int type, int subtype ) const
02905 {
02906 DwBodyPart *part, *curpart;
02907 QPtrList< DwBodyPart > parts;
02908
02909
02910 curpart = getFirstDwBodyPart();
02911 part = 0;
02912
02913 while (curpart && !part) {
02914
02915 while(curpart
02916 && curpart->hasHeaders()
02917 && curpart->Headers().HasContentType()
02918 && curpart->Body().FirstBodyPart()
02919 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) ) {
02920 parts.append( curpart );
02921 curpart = curpart->Body().FirstBodyPart();
02922 }
02923
02924
02925
02926
02927 if ( curpart && curpart->hasHeaders() && curpart->Headers().HasContentType() ) {
02928 kdDebug(5006) << curpart->Headers().ContentType().TypeStr().c_str()
02929 << " " << curpart->Headers().ContentType().SubtypeStr().c_str() << endl;
02930 }
02931
02932 if (curpart &&
02933 curpart->hasHeaders() &&
02934 curpart->Headers().HasContentType() &&
02935 curpart->Headers().ContentType().Type() == type &&
02936 curpart->Headers().ContentType().Subtype() == subtype) {
02937 part = curpart;
02938 } else {
02939
02940
02941 while (curpart && !(curpart->Next()) && !(parts.isEmpty())) {
02942 curpart = parts.getLast();
02943 parts.removeLast();
02944 } ;
02945 if (curpart)
02946 curpart = curpart->Next();
02947 }
02948 }
02949 return part;
02950 }
02951
02952
02953 DwBodyPart * KMMessage::findDwBodyPart( const QCString& type, const QCString& subtype ) const
02954 {
02955 DwBodyPart *part, *curpart;
02956 QPtrList< DwBodyPart > parts;
02957
02958
02959 curpart = getFirstDwBodyPart();
02960 part = 0;
02961
02962 while (curpart && !part) {
02963
02964 while(curpart
02965 && curpart->hasHeaders()
02966 && curpart->Headers().HasContentType()
02967 && curpart->Body().FirstBodyPart()
02968 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) ) {
02969 parts.append( curpart );
02970 curpart = curpart->Body().FirstBodyPart();
02971 }
02972
02973
02974
02975
02976 if (curpart && curpart->hasHeaders() && curpart->Headers().HasContentType() ) {
02977 kdDebug(5006) << curpart->Headers().ContentType().TypeStr().c_str()
02978 << " " << curpart->Headers().ContentType().SubtypeStr().c_str() << endl;
02979 }
02980
02981 if (curpart &&
02982 curpart->hasHeaders() &&
02983 curpart->Headers().HasContentType() &&
02984 curpart->Headers().ContentType().TypeStr().c_str() == type &&
02985 curpart->Headers().ContentType().SubtypeStr().c_str() == subtype) {
02986 part = curpart;
02987 } else {
02988
02989
02990 while (curpart && !(curpart->Next()) && !(parts.isEmpty())) {
02991 curpart = parts.getLast();
02992 parts.removeLast();
02993 } ;
02994 if (curpart)
02995 curpart = curpart->Next();
02996 }
02997 }
02998 return part;
02999 }
03000
03001
03002 void applyHeadersToMessagePart( DwHeaders& headers, KMMessagePart* aPart )
03003 {
03004
03005
03006
03007
03008
03009
03010
03011
03012
03013
03014 QCString additionalCTypeParams;
03015 if (headers.HasContentType())
03016 {
03017 DwMediaType& ct = headers.ContentType();
03018 aPart->setOriginalContentTypeStr( ct.AsString().c_str() );
03019 aPart->setTypeStr(ct.TypeStr().c_str());
03020 aPart->setSubtypeStr(ct.SubtypeStr().c_str());
03021 DwParameter *param = ct.FirstParameter();
03022 while(param)
03023 {
03024 if (!qstricmp(param->Attribute().c_str(), "charset"))
03025 aPart->setCharset(QCString(param->Value().c_str()).lower());
03026 else if (!qstrnicmp(param->Attribute().c_str(), "name*", 5))
03027 aPart->setName(KMMsgBase::decodeRFC2231String(KMMsgBase::extractRFC2231HeaderField( param->Value().c_str(), "name" )));
03028 else {
03029 additionalCTypeParams += ';';
03030 additionalCTypeParams += param->AsString().c_str();
03031 }
03032 param=param->Next();
03033 }
03034 }
03035 else
03036 {
03037 aPart->setTypeStr("text");
03038 aPart->setSubtypeStr("plain");
03039 }
03040 aPart->setAdditionalCTypeParamStr( additionalCTypeParams );
03041
03042 if (aPart->name().isEmpty())
03043 {
03044 if (headers.HasContentType() && !headers.ContentType().Name().empty()) {
03045 aPart->setName(KMMsgBase::decodeRFC2047String(headers.
03046 ContentType().Name().c_str()) );
03047 } else if (headers.HasSubject() && !headers.Subject().AsString().empty()) {
03048 aPart->setName( KMMsgBase::decodeRFC2047String(headers.
03049 Subject().AsString().c_str()) );
03050 }
03051 }
03052
03053
03054 if (headers.HasContentTransferEncoding())
03055 aPart->setCteStr(headers.ContentTransferEncoding().AsString().c_str());
03056 else
03057 aPart->setCteStr("7bit");
03058
03059
03060 if (headers.HasContentDescription())
03061 aPart->setContentDescription(headers.ContentDescription().AsString().c_str());
03062 else
03063 aPart->setContentDescription("");
03064
03065
03066 if (headers.HasContentDisposition())
03067 aPart->setContentDisposition(headers.ContentDisposition().AsString().c_str());
03068 else
03069 aPart->setContentDisposition("");
03070 }
03071
03072
03073 void KMMessage::bodyPart(DwBodyPart* aDwBodyPart, KMMessagePart* aPart,
03074 bool withBody)
03075 {
03076 if ( !aPart )
03077 return;
03078
03079 aPart->clear();
03080
03081 if( aDwBodyPart && aDwBodyPart->hasHeaders() ) {
03082
03083
03084
03085
03086 QString partId( aDwBodyPart->partId() );
03087 aPart->setPartSpecifier( partId );
03088
03089 DwHeaders& headers = aDwBodyPart->Headers();
03090 applyHeadersToMessagePart( headers, aPart );
03091
03092
03093 if (withBody)
03094 aPart->setBody( aDwBodyPart->Body().AsString() );
03095 else
03096 aPart->setBody( QCString("") );
03097
03098
03099 if ( headers.HasContentId() ) {
03100 const QCString contentId = headers.ContentId().AsString().c_str();
03101
03102 aPart->setContentId( contentId.mid( 1, contentId.length() - 2 ) );
03103 }
03104 }
03105
03106
03107 else
03108 {
03109 aPart->setTypeStr("");
03110 aPart->setSubtypeStr("");
03111 aPart->setCteStr("");
03112
03113
03114
03115 aPart->setContentDescription("");
03116 aPart->setContentDisposition("");
03117 aPart->setBody(QCString(""));
03118 aPart->setContentId("");
03119 }
03120 }
03121
03122
03123
03124 void KMMessage::bodyPart(int aIdx, KMMessagePart* aPart) const
03125 {
03126 if ( !aPart )
03127 return;
03128
03129
03130 if ( DwBodyPart *part = dwBodyPart( aIdx ) ) {
03131 KMMessage::bodyPart(part, aPart);
03132 if( aPart->name().isEmpty() )
03133 aPart->setName( i18n("Attachment: %1").arg( aIdx ) );
03134 }
03135 }
03136
03137
03138
03139 void KMMessage::deleteBodyParts()
03140 {
03141 mMsg->Body().DeleteBodyParts();
03142 }
03143
03144
03145 DwBodyPart* KMMessage::createDWBodyPart(const KMMessagePart* aPart)
03146 {
03147 DwBodyPart* part = DwBodyPart::NewBodyPart(emptyString, 0);
03148
03149 if ( !aPart )
03150 return part;
03151
03152 QCString charset = aPart->charset();
03153 QCString type = aPart->typeStr();
03154 QCString subtype = aPart->subtypeStr();
03155 QCString cte = aPart->cteStr();
03156 QCString contDesc = aPart->contentDescriptionEncoded();
03157 QCString contDisp = aPart->contentDisposition();
03158 QCString encoding = autoDetectCharset(charset, sPrefCharsets, aPart->name());
03159 if (encoding.isEmpty()) encoding = "utf-8";
03160 QCString name = KMMsgBase::encodeRFC2231String(aPart->name(), encoding);
03161 bool RFC2231encoded = aPart->name() != QString(name);
03162 QCString paramAttr = aPart->parameterAttribute();
03163
03164 DwHeaders& headers = part->Headers();
03165
03166 DwMediaType& ct = headers.ContentType();
03167 if (!type.isEmpty() && !subtype.isEmpty())
03168 {
03169 ct.SetTypeStr(type.data());
03170 ct.SetSubtypeStr(subtype.data());
03171 if (!charset.isEmpty()){
03172 DwParameter *param;
03173 param=new DwParameter;
03174 param->SetAttribute("charset");
03175 param->SetValue(charset.data());
03176 ct.AddParameter(param);
03177 }
03178 }
03179
03180 QCString additionalParam = aPart->additionalCTypeParamStr();
03181 if( !additionalParam.isEmpty() )
03182 {
03183 QCString parAV;
03184 DwString parA, parV;
03185 int iL, i1, i2, iM;
03186 iL = additionalParam.length();
03187 i1 = 0;
03188 i2 = additionalParam.find(';', i1, false);
03189 while ( i1 < iL )
03190 {
03191 if( -1 == i2 )
03192 i2 = iL;
03193 if( i1+1 < i2 ) {
03194 parAV = additionalParam.mid( i1, (i2-i1) );
03195 iM = parAV.find('=');
03196 if( -1 < iM )
03197 {
03198 parA = parAV.left( iM );
03199 parV = parAV.right( parAV.length() - iM - 1 );
03200 if( ('"' == parV.at(0)) && ('"' == parV.at(parV.length()-1)) )
03201 {
03202 parV.erase( 0, 1);
03203 parV.erase( parV.length()-1 );
03204 }
03205 }
03206 else
03207 {
03208 parA = parAV;
03209 parV = "";
03210 }
03211 DwParameter *param;
03212 param = new DwParameter;
03213 param->SetAttribute( parA );
03214 param->SetValue( parV );
03215 ct.AddParameter( param );
03216 }
03217 i1 = i2+1;
03218 i2 = additionalParam.find(';', i1, false);
03219 }
03220 }
03221
03222 if ( !name.isEmpty() ) {
03223 if (RFC2231encoded)
03224 {
03225 DwParameter *nameParam;
03226 nameParam = new DwParameter;
03227 nameParam->SetAttribute("name*");
03228 nameParam->SetValue(name.data(),true);
03229 ct.AddParameter(nameParam);
03230 } else {
03231 ct.SetName(name.data());
03232 }
03233 }
03234
03235 if (!paramAttr.isEmpty())
03236 {
03237 QCString encoding = autoDetectCharset(charset, sPrefCharsets,
03238 aPart->parameterValue());
03239 if (encoding.isEmpty()) encoding = "utf-8";
03240 QCString paramValue;
03241 paramValue = KMMsgBase::encodeRFC2231String(aPart->parameterValue(),
03242 encoding);
03243 DwParameter *param = new DwParameter;
03244 if (aPart->parameterValue() != QString(paramValue))
03245 {
03246 param->SetAttribute((paramAttr + '*').data());
03247 param->SetValue(paramValue.data(),true);
03248 } else {
03249 param->SetAttribute(paramAttr.data());
03250 param->SetValue(paramValue.data());
03251 }
03252 ct.AddParameter(param);
03253 }
03254
03255 if (!cte.isEmpty())
03256 headers.Cte().FromString(cte);
03257
03258 if (!contDesc.isEmpty())
03259 headers.ContentDescription().FromString(contDesc);
03260
03261 if (!contDisp.isEmpty())
03262 headers.ContentDisposition().FromString(contDisp);
03263
03264 const DwString bodyStr = aPart->dwBody();
03265 if (!bodyStr.empty())
03266 part->Body().FromString(bodyStr);
03267 else
03268 part->Body().FromString("");
03269
03270 if (!aPart->partSpecifier().isNull())
03271 part->SetPartId( aPart->partSpecifier().latin1() );
03272
03273 if (aPart->decodedSize() > 0)
03274 part->SetBodySize( aPart->decodedSize() );
03275
03276 return part;
03277 }
03278
03279
03280
03281 void KMMessage::addDwBodyPart(DwBodyPart * aDwPart)
03282 {
03283 mMsg->Body().AddBodyPart( aDwPart );
03284 mNeedsAssembly = true;
03285 }
03286
03287
03288
03289 void KMMessage::addBodyPart(const KMMessagePart* aPart)
03290 {
03291 DwBodyPart* part = createDWBodyPart( aPart );
03292 addDwBodyPart( part );
03293 }
03294
03295
03296
03297 QString KMMessage::generateMessageId( const QString& addr )
03298 {
03299 QDateTime datetime = QDateTime::currentDateTime();
03300 QString msgIdStr;
03301
03302 msgIdStr = '<' + datetime.toString( "yyyyMMddhhmm.sszzz" );
03303
03304 QString msgIdSuffix;
03305 KConfigGroup general( KMKernel::config(), "General" );
03306
03307 if( general.readBoolEntry( "useCustomMessageIdSuffix", false ) )
03308 msgIdSuffix = general.readEntry( "myMessageIdSuffix" );
03309
03310 if( !msgIdSuffix.isEmpty() )
03311 msgIdStr += '@' + msgIdSuffix;
03312 else
03313 msgIdStr += '.' + KPIM::encodeIDN( addr );
03314
03315 msgIdStr += '>';
03316
03317 return msgIdStr;
03318 }
03319
03320
03321
03322 QCString KMMessage::html2source( const QCString & src )
03323 {
03324 QCString result( 1 + 6*(src.size()-1) );
03325
03326 QCString::ConstIterator s = src.begin();
03327 QCString::Iterator d = result.begin();
03328 while ( *s ) {
03329 switch ( *s ) {
03330 case '<': {
03331 *d++ = '&';
03332 *d++ = 'l';
03333 *d++ = 't';
03334 *d++ = ';';
03335 ++s;
03336 }
03337 break;
03338 case '\r': {
03339 ++s;
03340 }
03341 break;
03342 case '\n': {
03343 *d++ = '<';
03344 *d++ = 'b';
03345 *d++ = 'r';
03346 *d++ = '>';
03347 ++s;
03348 }
03349 break;
03350 case '>': {
03351 *d++ = '&';
03352 *d++ = 'g';
03353 *d++ = 't';
03354 *d++ = ';';
03355 ++s;
03356 }
03357 break;
03358 case '&': {
03359 *d++ = '&';
03360 *d++ = 'a';
03361 *d++ = 'm';
03362 *d++ = 'p';
03363 *d++ = ';';
03364 ++s;
03365 }
03366 break;
03367 case '"': {
03368 *d++ = '&';
03369 *d++ = 'q';
03370 *d++ = 'u';
03371 *d++ = 'o';
03372 *d++ = 't';
03373 *d++ = ';';
03374 ++s;
03375 }
03376 break;
03377 case '\'': {
03378 *d++ = '&';
03379 *d++ = 'a';
03380 *d++ = 'p';
03381 *d++ = 's';
03382 *d++ = ';';
03383 ++s;
03384 }
03385 break;
03386 default:
03387 *d++ = *s++;
03388 }
03389 }
03390 result.truncate( d - result.begin() );
03391 return result;
03392 }
03393
03394
03395 QString KMMessage::encodeMailtoUrl( const QString& str )
03396 {
03397 QString result;
03398 result = QString::fromLatin1( KMMsgBase::encodeRFC2047String( str,
03399 "utf-8" ) );
03400 result = KURL::encode_string( result );
03401 return result;
03402 }
03403
03404
03405
03406 QString KMMessage::decodeMailtoUrl( const QString& url )
03407 {
03408 QString result;
03409 result = KURL::decode_string( url );
03410 result = KMMsgBase::decodeRFC2047String( result.latin1() );
03411 return result;
03412 }
03413
03414
03415
03416 QCString KMMessage::stripEmailAddr( const QCString& aStr )
03417 {
03418
03419
03420 if ( aStr.isEmpty() )
03421 return QCString();
03422
03423 QCString result;
03424
03425
03426
03427
03428
03429 QCString name;
03430 QCString comment;
03431 QCString angleAddress;
03432 enum { TopLevel, InComment, InAngleAddress } context = TopLevel;
03433 bool inQuotedString = false;
03434 int commentLevel = 0;
03435
03436 for ( char* p = aStr.data(); *p; ++p ) {
03437 switch ( context ) {
03438 case TopLevel : {
03439 switch ( *p ) {
03440 case '"' : inQuotedString = !inQuotedString;
03441 break;
03442 case '(' : if ( !inQuotedString ) {
03443 context = InComment;
03444 commentLevel = 1;
03445 }
03446 else
03447 name += *p;
03448 break;
03449 case '<' : if ( !inQuotedString ) {
03450 context = InAngleAddress;
03451 }
03452 else
03453 name += *p;
03454 break;
03455 case '\\' :
03456 ++p;
03457 if ( *p )
03458 name += *p;
03459 break;
03460 case ',' : if ( !inQuotedString ) {
03461
03462 if ( !result.isEmpty() )
03463 result += ", ";
03464 name = name.stripWhiteSpace();
03465 comment = comment.stripWhiteSpace();
03466 angleAddress = angleAddress.stripWhiteSpace();
03467
03468
03469
03470
03471
03472
03473
03474
03475 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03476
03477
03478 result += comment;
03479 }
03480 else if ( !name.isEmpty() ) {
03481 result += name;
03482 }
03483 else if ( !comment.isEmpty() ) {
03484 result += comment;
03485 }
03486 else if ( !angleAddress.isEmpty() ) {
03487 result += angleAddress;
03488 }
03489 name = QCString();
03490 comment = QCString();
03491 angleAddress = QCString();
03492 }
03493 else
03494 name += *p;
03495 break;
03496 default : name += *p;
03497 }
03498 break;
03499 }
03500 case InComment : {
03501 switch ( *p ) {
03502 case '(' : ++commentLevel;
03503 comment += *p;
03504 break;
03505 case ')' : --commentLevel;
03506 if ( commentLevel == 0 ) {
03507 context = TopLevel;
03508 comment += ' ';
03509 }
03510 else
03511 comment += *p;
03512 break;
03513 case '\\' :
03514 ++p;
03515 if ( *p )
03516 comment += *p;
03517 break;
03518 default : comment += *p;
03519 }
03520 break;
03521 }
03522 case InAngleAddress : {
03523 switch ( *p ) {
03524 case '"' : inQuotedString = !inQuotedString;
03525 angleAddress += *p;
03526 break;
03527 case '>' : if ( !inQuotedString ) {
03528 context = TopLevel;
03529 }
03530 else
03531 angleAddress += *p;
03532 break;
03533 case '\\' :
03534 ++p;
03535 if ( *p )
03536 angleAddress += *p;
03537 break;
03538 default : angleAddress += *p;
03539 }
03540 break;
03541 }
03542 }
03543 }
03544 if ( !result.isEmpty() )
03545 result += ", ";
03546 name = name.stripWhiteSpace();
03547 comment = comment.stripWhiteSpace();
03548 angleAddress = angleAddress.stripWhiteSpace();
03549
03550
03551
03552
03553
03554 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03555
03556
03557 result += comment;
03558 }
03559 else if ( !name.isEmpty() ) {
03560 result += name;
03561 }
03562 else if ( !comment.isEmpty() ) {
03563 result += comment;
03564 }
03565 else if ( !angleAddress.isEmpty() ) {
03566 result += angleAddress;
03567 }
03568
03569
03570
03571 return result;
03572 }
03573
03574
03575 QString KMMessage::stripEmailAddr( const QString& aStr )
03576 {
03577
03578
03579 if ( aStr.isEmpty() )
03580 return QString::null;
03581
03582 QString result;
03583
03584
03585
03586
03587
03588 QString name;
03589 QString comment;
03590 QString angleAddress;
03591 enum { TopLevel, InComment, InAngleAddress } context = TopLevel;
03592 bool inQuotedString = false;
03593 int commentLevel = 0;
03594
03595 QChar ch;
03596 unsigned int strLength(aStr.length());
03597 for ( uint index = 0; index < strLength; ++index ) {
03598 ch = aStr[index];
03599 switch ( context ) {
03600 case TopLevel : {
03601 switch ( ch.latin1() ) {
03602 case '"' : inQuotedString = !inQuotedString;
03603 break;
03604 case '(' : if ( !inQuotedString ) {
03605 context = InComment;
03606 commentLevel = 1;
03607 }
03608 else
03609 name += ch;
03610 break;
03611 case '<' : if ( !inQuotedString ) {
03612 context = InAngleAddress;
03613 }
03614 else
03615 name += ch;
03616 break;
03617 case '\\' :
03618 ++index;
03619 if ( index < aStr.length() )
03620 name += aStr[index];
03621 break;
03622 case ',' : if ( !inQuotedString ) {
03623
03624 if ( !result.isEmpty() )
03625 result += ", ";
03626 name = name.stripWhiteSpace();
03627 comment = comment.stripWhiteSpace();
03628 angleAddress = angleAddress.stripWhiteSpace();
03629
03630
03631
03632
03633
03634
03635
03636
03637 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03638
03639
03640 result += comment;
03641 }
03642 else if ( !name.isEmpty() ) {
03643 result += name;
03644 }
03645 else if ( !comment.isEmpty() ) {
03646 result += comment;
03647 }
03648 else if ( !angleAddress.isEmpty() ) {
03649 result += angleAddress;
03650 }
03651 name = QString::null;
03652 comment = QString::null;
03653 angleAddress = QString::null;
03654 }
03655 else
03656 name += ch;
03657 break;
03658 default : name += ch;
03659 }
03660 break;
03661 }
03662 case InComment : {
03663 switch ( ch.latin1() ) {
03664 case '(' : ++commentLevel;
03665 comment += ch;
03666 break;
03667 case ')' : --commentLevel;
03668 if ( commentLevel == 0 ) {
03669 context = TopLevel;
03670 comment += ' ';
03671 }
03672 else
03673 comment += ch;
03674 break;
03675 case '\\' :
03676 ++index;
03677 if ( index < aStr.length() )
03678 comment += aStr[index];
03679 break;
03680 default : comment += ch;
03681 }
03682 break;
03683 }
03684 case InAngleAddress : {
03685 switch ( ch.latin1() ) {
03686 case '"' : inQuotedString = !inQuotedString;
03687 angleAddress += ch;
03688 break;
03689 case '>' : if ( !inQuotedString ) {
03690 context = TopLevel;
03691 }
03692 else
03693 angleAddress += ch;
03694 break;
03695 case '\\' :
03696 ++index;
03697 if ( index < aStr.length() )
03698 angleAddress += aStr[index];
03699 break;
03700 default : angleAddress += ch;
03701 }
03702 break;
03703 }
03704 }
03705 }
03706 if ( !result.isEmpty() )
03707 result += ", ";
03708 name = name.stripWhiteSpace();
03709 comment = comment.stripWhiteSpace();
03710 angleAddress = angleAddress.stripWhiteSpace();
03711
03712
03713
03714
03715
03716 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03717
03718
03719 result += comment;
03720 }
03721 else if ( !name.isEmpty() ) {
03722 result += name;
03723 }
03724 else if ( !comment.isEmpty() ) {
03725 result += comment;
03726 }
03727 else if ( !angleAddress.isEmpty() ) {
03728 result += angleAddress;
03729 }
03730
03731
03732
03733 return result;
03734 }
03735
03736
03737 QString KMMessage::quoteHtmlChars( const QString& str, bool removeLineBreaks )
03738 {
03739 QString result;
03740
03741 unsigned int strLength(str.length());
03742 result.reserve( 6*strLength );
03743 for( unsigned int i = 0; i < strLength; ++i )
03744 switch ( str[i].latin1() ) {
03745 case '<':
03746 result += "<";
03747 break;
03748 case '>':
03749 result += ">";
03750 break;
03751 case '&':
03752 result += "&";
03753 break;
03754 case '"':
03755 result += """;
03756 break;
03757 case '\n':
03758 if ( !removeLineBreaks )
03759 result += "<br>";
03760 break;
03761 case '\r':
03762
03763 break;
03764 default:
03765 result += str[i];
03766 }
03767
03768 result.squeeze();
03769 return result;
03770 }
03771
03772
03773 QString KMMessage::emailAddrAsAnchor(const QString& aEmail, bool stripped, const QString& cssStyle, bool aLink)
03774 {
03775 if( aEmail.isEmpty() )
03776 return aEmail;
03777
03778 QStringList addressList = KPIM::splitEmailAddrList( aEmail );
03779
03780 QString result;
03781
03782 for( QStringList::ConstIterator it = addressList.begin();
03783 ( it != addressList.end() );
03784 ++it ) {
03785 if( !(*it).isEmpty() ) {
03786 QString address = *it;
03787 if(aLink) {
03788 result += "<a href=\"mailto:"
03789 + KMMessage::encodeMailtoUrl( address )
03790 + "\" "+cssStyle+">";
03791 }
03792 if( stripped )
03793 address = KMMessage::stripEmailAddr( address );
03794 result += KMMessage::quoteHtmlChars( address, true );
03795 if(aLink)
03796 result += "</a>, ";
03797 }
03798 }
03799
03800 if(aLink)
03801 result.truncate( result.length() - 2 );
03802
03803
03804
03805 return result;
03806 }
03807
03808
03809
03810
03811 QStringList KMMessage::stripAddressFromAddressList( const QString& address,
03812 const QStringList& list )
03813 {
03814 QStringList addresses( list );
03815 QString addrSpec( KPIM::getEmailAddress( address ) );
03816 for ( QStringList::Iterator it = addresses.begin();
03817 it != addresses.end(); ) {
03818 if ( kasciistricmp( addrSpec.utf8().data(),
03819 KPIM::getEmailAddress( *it ).utf8().data() ) == 0 ) {
03820 kdDebug(5006) << "Removing " << *it << " from the address list"
03821 << endl;
03822 it = addresses.remove( it );
03823 }
03824 else
03825 ++it;
03826 }
03827 return addresses;
03828 }
03829
03830
03831
03832
03833 QStringList KMMessage::stripMyAddressesFromAddressList( const QStringList& list )
03834 {
03835 QStringList addresses = list;
03836 for( QStringList::Iterator it = addresses.begin();
03837 it != addresses.end(); ) {
03838 kdDebug(5006) << "Check whether " << *it << " is one of my addresses"
03839 << endl;
03840 if( kmkernel->identityManager()->thatIsMe( KPIM::getEmailAddress( *it ) ) ) {
03841 kdDebug(5006) << "Removing " << *it << " from the address list"
03842 << endl;
03843 it = addresses.remove( it );
03844 }
03845 else
03846 ++it;
03847 }
03848 return addresses;
03849 }
03850
03851
03852
03853
03854 bool KMMessage::addressIsInAddressList( const QString& address,
03855 const QStringList& addresses )
03856 {
03857 QString addrSpec = KPIM::getEmailAddress( address );
03858 for( QStringList::ConstIterator it = addresses.begin();
03859 it != addresses.end(); ++it ) {
03860 if ( kasciistricmp( addrSpec.utf8().data(),
03861 KPIM::getEmailAddress( *it ).utf8().data() ) == 0 )
03862 return true;
03863 }
03864 return false;
03865 }
03866
03867
03868
03869
03870 QString KMMessage::expandAliases( const QString& recipients )
03871 {
03872 if ( recipients.isEmpty() )
03873 return QString();
03874
03875 QStringList recipientList = KPIM::splitEmailAddrList( recipients );
03876
03877 QString expandedRecipients;
03878 for ( QStringList::Iterator it = recipientList.begin();
03879 it != recipientList.end(); ++it ) {
03880 if ( !expandedRecipients.isEmpty() )
03881 expandedRecipients += ", ";
03882 QString receiver = (*it).stripWhiteSpace();
03883
03884
03885 QString expandedList = KAddrBookExternal::expandDistributionList( receiver );
03886 if ( !expandedList.isEmpty() ) {
03887 expandedRecipients += expandedList;
03888 continue;
03889 }
03890
03891
03892 QString expandedNickName = KabcBridge::expandNickName( receiver );
03893 if ( !expandedNickName.isEmpty() ) {
03894 expandedRecipients += expandedNickName;
03895 continue;
03896 }
03897
03898
03899
03900 if ( receiver.find('@') == -1 ) {
03901 KConfigGroup general( KMKernel::config(), "General" );
03902 QString defaultdomain = general.readEntry( "Default domain" );
03903 if( !defaultdomain.isEmpty() ) {
03904 expandedRecipients += receiver + "@" + defaultdomain;
03905 }
03906 else {
03907 expandedRecipients += guessEmailAddressFromLoginName( receiver );
03908 }
03909 }
03910 else
03911 expandedRecipients += receiver;
03912 }
03913
03914 return expandedRecipients;
03915 }
03916
03917
03918
03919
03920 QString KMMessage::guessEmailAddressFromLoginName( const QString& loginName )
03921 {
03922 if ( loginName.isEmpty() )
03923 return QString();
03924
03925 char hostnameC[256];
03926
03927 hostnameC[255] = '\0';
03928
03929 if ( gethostname( hostnameC, 255 ) )
03930 hostnameC[0] = '\0';
03931 QString address = loginName;
03932 address += '@';
03933 address += QString::fromLocal8Bit( hostnameC );
03934
03935
03936 const KUser user( loginName );
03937 if ( user.isValid() ) {
03938 QString fullName = user.fullName();
03939 if ( fullName.find( QRegExp( "[^ 0-9A-Za-z\\x0080-\\xFFFF]" ) ) != -1 )
03940 address = '"' + fullName.replace( '\\', "\\" ).replace( '"', "\\" )
03941 + "\" <" + address + '>';
03942 else
03943 address = fullName + " <" + address + '>';
03944 }
03945
03946 return address;
03947 }
03948
03949
03950 void KMMessage::readConfig()
03951 {
03952 KMMsgBase::readConfig();
03953
03954 KConfig *config=KMKernel::config();
03955 KConfigGroupSaver saver(config, "General");
03956
03957 config->setGroup("General");
03958
03959 int languageNr = config->readNumEntry("reply-current-language",0);
03960
03961 {
03962 KConfigGroupSaver saver(config, QString("KMMessage #%1").arg(languageNr));
03963 sReplyLanguage = config->readEntry("language",KGlobal::locale()->language());
03964 sReplyStr = config->readEntry("phrase-reply",
03965 i18n("On %D, you wrote:"));
03966 sReplyAllStr = config->readEntry("phrase-reply-all",
03967 i18n("On %D, %F wrote:"));
03968 sForwardStr = config->readEntry("phrase-forward",
03969 i18n("Forwarded Message"));
03970 sIndentPrefixStr = config->readEntry("indent-prefix",">%_");
03971 }
03972
03973 {
03974 KConfigGroupSaver saver(config, "Composer");
03975 sSmartQuote = GlobalSettings::self()->smartQuote();
03976 sWordWrap = GlobalSettings::self()->wordWrap();
03977 sWrapCol = GlobalSettings::self()->lineWrapWidth();
03978 if ((sWrapCol == 0) || (sWrapCol > 78))
03979 sWrapCol = 78;
03980 if (sWrapCol < 30)
03981 sWrapCol = 30;
03982
03983 sPrefCharsets = config->readListEntry("pref-charsets");
03984 }
03985
03986 {
03987 KConfigGroupSaver saver(config, "Reader");
03988 sHeaderStrategy = HeaderStrategy::create( config->readEntry( "header-set-displayed", "rich" ) );
03989 }
03990 }
03991
03992 QCString KMMessage::defaultCharset()
03993 {
03994 QCString retval;
03995
03996 if (!sPrefCharsets.isEmpty())
03997 retval = sPrefCharsets[0].latin1();
03998
03999 if (retval.isEmpty() || (retval == "locale")) {
04000 retval = QCString(kmkernel->networkCodec()->mimeName());
04001 KPIM::kAsciiToLower( retval.data() );
04002 }
04003
04004 if (retval == "jisx0208.1983-0") retval = "iso-2022-jp";
04005 else if (retval == "ksc5601.1987-0") retval = "euc-kr";
04006 return retval;
04007 }
04008
04009 const QStringList &KMMessage::preferredCharsets()
04010 {
04011 return sPrefCharsets;
04012 }
04013
04014
04015 QCString KMMessage::charset() const
04016 {
04017 if ( mMsg->Headers().HasContentType() ) {
04018 DwMediaType &mType=mMsg->Headers().ContentType();
04019 mType.Parse();
04020 DwParameter *param=mType.FirstParameter();
04021 while(param){
04022 if (!kasciistricmp(param->Attribute().c_str(), "charset"))
04023 return param->Value().c_str();
04024 else param=param->Next();
04025 }
04026 }
04027 return "";
04028 }
04029
04030
04031 void KMMessage::setCharset( const QCString &charset, DwEntity *entity )
04032 {
04033 kdWarning( type() != DwMime::kTypeText )
04034 << "KMMessage::setCharset(): trying to set a charset for a non-textual mimetype." << endl
04035 << "Fix this caller:" << endl
04036 << "====================================================================" << endl
04037 << kdBacktrace( 5 ) << endl
04038 << "====================================================================" << endl;
04039
04040 if ( !entity )
04041 entity = mMsg;
04042
04043 DwMediaType &mType = entity->Headers().ContentType();
04044 mType.Parse();
04045 DwParameter *param = mType.FirstParameter();
04046 while( param ) {
04047
04048
04049 if ( !kasciistricmp( param->Attribute().c_str(), "charset" ) )
04050 break;
04051
04052 param = param->Next();
04053 }
04054 if ( !param ) {
04055 param = new DwParameter;
04056 param->SetAttribute( "charset" );
04057 mType.AddParameter( param );
04058 }
04059 else
04060 mType.SetModified();
04061
04062 QCString lowerCharset = charset;
04063 KPIM::kAsciiToLower( lowerCharset.data() );
04064 param->SetValue( DwString( lowerCharset ) );
04065 mType.Assemble();
04066 }
04067
04068
04069
04070 void KMMessage::setStatus(const KMMsgStatus aStatus, int idx)
04071 {
04072 if (mStatus == aStatus)
04073 return;
04074 KMMsgBase::setStatus(aStatus, idx);
04075 }
04076
04077 void KMMessage::setEncryptionState(const KMMsgEncryptionState s, int idx)
04078 {
04079 if( mEncryptionState == s )
04080 return;
04081 mEncryptionState = s;
04082 mDirty = true;
04083 KMMsgBase::setEncryptionState(s, idx);
04084 }
04085
04086 void KMMessage::setSignatureState(KMMsgSignatureState s, int idx)
04087 {
04088 if( mSignatureState == s )
04089 return;
04090 mSignatureState = s;
04091 mDirty = true;
04092 KMMsgBase::setSignatureState(s, idx);
04093 }
04094
04095 void KMMessage::setMDNSentState( KMMsgMDNSentState status, int idx ) {
04096 if ( mMDNSentState == status )
04097 return;
04098 if ( status == 0 )
04099 status = KMMsgMDNStateUnknown;
04100 mMDNSentState = status;
04101 mDirty = true;
04102 KMMsgBase::setMDNSentState( status, idx );
04103 }
04104
04105
04106 void KMMessage::link( const KMMessage *aMsg, KMMsgStatus aStatus )
04107 {
04108 Q_ASSERT( aStatus == KMMsgStatusReplied
04109 || aStatus == KMMsgStatusForwarded
04110 || aStatus == KMMsgStatusDeleted );
04111
04112 QString message = headerField( "X-KMail-Link-Message" );
04113 if ( !message.isEmpty() )
04114 message += ',';
04115 QString type = headerField( "X-KMail-Link-Type" );
04116 if ( !type.isEmpty() )
04117 type += ',';
04118
04119 message += QString::number( aMsg->getMsgSerNum() );
04120 if ( aStatus == KMMsgStatusReplied )
04121 type += "reply";
04122 else if ( aStatus == KMMsgStatusForwarded )
04123 type += "forward";
04124 else if ( aStatus == KMMsgStatusDeleted )
04125 type += "deleted";
04126
04127 setHeaderField( "X-KMail-Link-Message", message );
04128 setHeaderField( "X-KMail-Link-Type", type );
04129 }
04130
04131
04132 void KMMessage::getLink(int n, ulong *retMsgSerNum, KMMsgStatus *retStatus) const
04133 {
04134 *retMsgSerNum = 0;
04135 *retStatus = KMMsgStatusUnknown;
04136
04137 QString message = headerField("X-KMail-Link-Message");
04138 QString type = headerField("X-KMail-Link-Type");
04139 message = message.section(',', n, n);
04140 type = type.section(',', n, n);
04141
04142 if ( !message.isEmpty() && !type.isEmpty() ) {
04143 *retMsgSerNum = message.toULong();
04144 if ( type == "reply" )
04145 *retStatus = KMMsgStatusReplied;
04146 else if ( type == "forward" )
04147 *retStatus = KMMsgStatusForwarded;
04148 else if ( type == "deleted" )
04149 *retStatus = KMMsgStatusDeleted;
04150 }
04151 }
04152
04153
04154 DwBodyPart* KMMessage::findDwBodyPart( DwBodyPart* part, const QString & partSpecifier )
04155 {
04156 if ( !part ) return 0;
04157 DwBodyPart* current;
04158
04159 if ( part->partId() == partSpecifier )
04160 return part;
04161
04162
04163 if ( part->hasHeaders() &&
04164 part->Headers().HasContentType() &&
04165 part->Body().FirstBodyPart() &&
04166 (DwMime::kTypeMultipart == part->Headers().ContentType().Type() ) &&
04167 (current = findDwBodyPart( part->Body().FirstBodyPart(), partSpecifier )) )
04168 {
04169 return current;
04170 }
04171
04172
04173 if ( part->Body().Message() &&
04174 part->Body().Message()->Body().FirstBodyPart() &&
04175 (current = findDwBodyPart( part->Body().Message()->Body().FirstBodyPart(),
04176 partSpecifier )) )
04177 {
04178 return current;
04179 }
04180
04181
04182 return findDwBodyPart( part->Next(), partSpecifier );
04183 }
04184
04185
04186 void KMMessage::updateBodyPart(const QString partSpecifier, const QByteArray & data)
04187 {
04188 if ( !data.data() || !data.size() )
04189 return;
04190
04191 DwString content( data.data(), data.size() );
04192 if ( numBodyParts() > 0 &&
04193 partSpecifier != "0" &&
04194 partSpecifier != "TEXT" )
04195 {
04196 QString specifier = partSpecifier;
04197 if ( partSpecifier.endsWith(".HEADER") ||
04198 partSpecifier.endsWith(".MIME") ) {
04199
04200 specifier = partSpecifier.section( '.', 0, -2 );
04201 }
04202
04203
04204 mLastUpdated = findDwBodyPart( getFirstDwBodyPart(), specifier );
04205 kdDebug(5006) << "KMMessage::updateBodyPart " << specifier << endl;
04206 if (!mLastUpdated)
04207 {
04208 kdWarning(5006) << "KMMessage::updateBodyPart - can not find part "
04209 << specifier << endl;
04210 return;
04211 }
04212 if ( partSpecifier.endsWith(".MIME") )
04213 {
04214
04215
04216 content.resize( QMAX( content.length(), 2 ) - 2 );
04217
04218
04219 mLastUpdated->Headers().DeleteAllFields();
04220 mLastUpdated->Headers().FromString( content );
04221 mLastUpdated->Headers().Parse();
04222 } else if ( partSpecifier.endsWith(".HEADER") )
04223 {
04224
04225 mLastUpdated->Body().Message()->Headers().FromString( content );
04226 mLastUpdated->Body().Message()->Headers().Parse();
04227 } else {
04228
04229 mLastUpdated->Body().FromString( content );
04230 QString parentSpec = partSpecifier.section( '.', 0, -2 );
04231 if ( !parentSpec.isEmpty() )
04232 {
04233 DwBodyPart* parent = findDwBodyPart( getFirstDwBodyPart(), parentSpec );
04234 if ( parent && parent->hasHeaders() && parent->Headers().HasContentType() )
04235 {
04236 const DwMediaType& contentType = parent->Headers().ContentType();
04237 if ( contentType.Type() == DwMime::kTypeMessage &&
04238 contentType.Subtype() == DwMime::kSubtypeRfc822 )
04239 {
04240
04241
04242 parent->Body().Message()->Body().FromString( content );
04243 }
04244 }
04245 }
04246 }
04247
04248 } else
04249 {
04250
04251 if ( partSpecifier == "TEXT" )
04252 deleteBodyParts();
04253 mMsg->Body().FromString( content );
04254 mMsg->Body().Parse();
04255 }
04256 mNeedsAssembly = true;
04257 if (! partSpecifier.endsWith(".HEADER") )
04258 {
04259
04260 notify();
04261 }
04262 }
04263
04264
04265 void KMMessage::updateAttachmentState( DwBodyPart* part )
04266 {
04267 if ( !part )
04268 part = getFirstDwBodyPart();
04269
04270 if ( !part )
04271 {
04272
04273 setStatus( KMMsgStatusHasNoAttach );
04274 return;
04275 }
04276
04277 bool filenameEmpty = true;
04278 if ( part->hasHeaders() ) {
04279 if ( part->Headers().HasContentDisposition() ) {
04280 DwDispositionType cd = part->Headers().ContentDisposition();
04281 filenameEmpty = cd.Filename().empty();
04282 if ( filenameEmpty ) {
04283
04284 filenameEmpty = KMMsgBase::decodeRFC2231String( KMMsgBase::extractRFC2231HeaderField( cd.AsString().c_str(), "filename" ) ).isEmpty();
04285 }
04286 }
04287 }
04288
04289 if ( part->hasHeaders() &&
04290 ( ( part->Headers().HasContentDisposition() &&
04291 !part->Headers().ContentDisposition().Filename().empty() ) ||
04292 ( part->Headers().HasContentType() &&
04293 !filenameEmpty ) ) )
04294 {
04295
04296 if ( !part->Headers().HasContentType() ||
04297 ( part->Headers().HasContentType() &&
04298 part->Headers().ContentType().Subtype() != DwMime::kSubtypePgpSignature &&
04299 part->Headers().ContentType().Subtype() != DwMime::kSubtypePkcs7Signature ) )
04300 {
04301 setStatus( KMMsgStatusHasAttach );
04302 }
04303 return;
04304 }
04305
04306
04307 if ( part->hasHeaders() &&
04308 part->Headers().HasContentType() &&
04309 part->Body().FirstBodyPart() &&
04310 (DwMime::kTypeMultipart == part->Headers().ContentType().Type() ) )
04311 {
04312 updateAttachmentState( part->Body().FirstBodyPart() );
04313 }
04314
04315
04316 if ( part->Body().Message() &&
04317 part->Body().Message()->Body().FirstBodyPart() )
04318 {
04319 updateAttachmentState( part->Body().Message()->Body().FirstBodyPart() );
04320 }
04321
04322
04323 if ( part->Next() )
04324 updateAttachmentState( part->Next() );
04325 else if ( attachmentState() == KMMsgAttachmentUnknown )
04326 setStatus( KMMsgStatusHasNoAttach );
04327 }
04328
04329 void KMMessage::setBodyFromUnicode( const QString &str, DwEntity *entity )
04330 {
04331 QCString encoding = KMMsgBase::autoDetectCharset( charset(), KMMessage::preferredCharsets(), str );
04332 if ( encoding.isEmpty() )
04333 encoding = "utf-8";
04334 const QTextCodec * codec = KMMsgBase::codecForName( encoding );
04335 assert( codec );
04336 QValueList<int> dummy;
04337 setCharset( encoding, entity );
04338 setBodyAndGuessCte( codec->fromUnicode( str ), dummy, false ,
04339 false, entity );
04340 }
04341
04342 const QTextCodec * KMMessage::codec() const {
04343 const QTextCodec * c = mOverrideCodec;
04344 if ( !c )
04345
04346 c = KMMsgBase::codecForName( charset() );
04347 if ( !c ) {
04348
04349
04350 c = KMMsgBase::codecForName( GlobalSettings::self()->fallbackCharacterEncoding().latin1() );
04351 }
04352 if ( !c )
04353
04354
04355 c = kmkernel->networkCodec();
04356 assert( c );
04357 return c;
04358 }
04359
04360 QString KMMessage::bodyToUnicode(const QTextCodec* codec) const {
04361 if ( !codec )
04362
04363 codec = this->codec();
04364 assert( codec );
04365
04366 return codec->toUnicode( bodyDecoded() );
04367 }
04368
04369
04370 QCString KMMessage::mboxMessageSeparator()
04371 {
04372 QCString str( KPIM::getFirstEmailAddress( rawHeaderField("From") ) );
04373 if ( str.isEmpty() )
04374 str = "unknown@unknown.invalid";
04375 QCString dateStr( dateShortStr() );
04376 if ( dateStr.isEmpty() ) {
04377 time_t t = ::time( 0 );
04378 dateStr = ctime( &t );
04379 const int len = dateStr.length();
04380 if ( dateStr[len-1] == '\n' )
04381 dateStr.truncate( len - 1 );
04382 }
04383 return "From " + str + " " + dateStr + "\n";
04384 }
04385
04386 void KMMessage::deleteWhenUnused()
04387 {
04388 sPendingDeletes << this;
04389 }