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() const
02491 {
02492 DwHeaders& header = mMsg->Headers();
02493 if (header.HasContentTransferEncoding())
02494 return header.ContentTransferEncoding().AsEnum();
02495 else return DwMime::kCteNull;
02496 }
02497
02498
02499
02500 void KMMessage::setContentTransferEncodingStr(const QCString& aStr)
02501 {
02502 mMsg->Headers().ContentTransferEncoding().FromString(aStr);
02503 mMsg->Headers().ContentTransferEncoding().Parse();
02504 mNeedsAssembly = true;
02505 }
02506
02507
02508
02509 void KMMessage::setContentTransferEncoding(int aCte)
02510 {
02511 mMsg->Headers().ContentTransferEncoding().FromEnum(aCte);
02512 mNeedsAssembly = true;
02513 }
02514
02515
02516
02517 DwHeaders& KMMessage::headers() const
02518 {
02519 return mMsg->Headers();
02520 }
02521
02522
02523
02524 void KMMessage::setNeedsAssembly()
02525 {
02526 mNeedsAssembly = true;
02527 }
02528
02529
02530
02531 QCString KMMessage::body() const
02532 {
02533 const DwString& body = mMsg->Body().AsString();
02534 QCString str = KMail::Util::CString( body );
02535
02536
02537
02538 return str;
02539 }
02540
02541
02542
02543 QByteArray KMMessage::bodyDecodedBinary() const
02544 {
02545 DwString dwstr;
02546 const DwString& dwsrc = mMsg->Body().AsString();
02547
02548 switch (cte())
02549 {
02550 case DwMime::kCteBase64:
02551 DwDecodeBase64(dwsrc, dwstr);
02552 break;
02553 case DwMime::kCteQuotedPrintable:
02554 DwDecodeQuotedPrintable(dwsrc, dwstr);
02555 break;
02556 default:
02557 dwstr = dwsrc;
02558 break;
02559 }
02560
02561 int len = dwstr.size();
02562 QByteArray ba(len);
02563 memcpy(ba.data(),dwstr.data(),len);
02564 return ba;
02565 }
02566
02567
02568
02569 QCString KMMessage::bodyDecoded() const
02570 {
02571 DwString dwstr;
02572 DwString dwsrc = mMsg->Body().AsString();
02573
02574 switch (cte())
02575 {
02576 case DwMime::kCteBase64:
02577 DwDecodeBase64(dwsrc, dwstr);
02578 break;
02579 case DwMime::kCteQuotedPrintable:
02580 DwDecodeQuotedPrintable(dwsrc, dwstr);
02581 break;
02582 default:
02583 dwstr = dwsrc;
02584 break;
02585 }
02586
02587 return KMail::Util::CString( dwstr );
02588
02589
02590
02591
02592
02593
02594 }
02595
02596
02597
02598 QValueList<int> KMMessage::determineAllowedCtes( const CharFreq& cf,
02599 bool allow8Bit,
02600 bool willBeSigned )
02601 {
02602 QValueList<int> allowedCtes;
02603
02604 switch ( cf.type() ) {
02605 case CharFreq::SevenBitText:
02606 allowedCtes << DwMime::kCte7bit;
02607 case CharFreq::EightBitText:
02608 if ( allow8Bit )
02609 allowedCtes << DwMime::kCte8bit;
02610 case CharFreq::SevenBitData:
02611 if ( cf.printableRatio() > 5.0/6.0 ) {
02612
02613
02614
02615 allowedCtes << DwMime::kCteQp;
02616 allowedCtes << DwMime::kCteBase64;
02617 } else {
02618 allowedCtes << DwMime::kCteBase64;
02619 allowedCtes << DwMime::kCteQp;
02620 }
02621 break;
02622 case CharFreq::EightBitData:
02623 allowedCtes << DwMime::kCteBase64;
02624 break;
02625 case CharFreq::None:
02626 default:
02627
02628 ;
02629 }
02630
02631
02632
02633
02634
02635 if ( ( willBeSigned && cf.hasTrailingWhitespace() ) ||
02636 cf.hasLeadingFrom() ) {
02637 allowedCtes.remove( DwMime::kCte8bit );
02638 allowedCtes.remove( DwMime::kCte7bit );
02639 }
02640
02641 return allowedCtes;
02642 }
02643
02644
02645
02646 void KMMessage::setBodyAndGuessCte( const QByteArray& aBuf,
02647 QValueList<int> & allowedCte,
02648 bool allow8Bit,
02649 bool willBeSigned )
02650 {
02651 CharFreq cf( aBuf );
02652
02653 allowedCte = determineAllowedCtes( cf, allow8Bit, willBeSigned );
02654
02655 #ifndef NDEBUG
02656 DwString dwCte;
02657 DwCteEnumToStr(allowedCte[0], dwCte);
02658 kdDebug(5006) << "CharFreq returned " << cf.type() << "/"
02659 << cf.printableRatio() << " and I chose "
02660 << dwCte.c_str() << endl;
02661 #endif
02662
02663 setCte( allowedCte[0] );
02664 setBodyEncodedBinary( aBuf );
02665 }
02666
02667
02668
02669 void KMMessage::setBodyAndGuessCte( const QCString& aBuf,
02670 QValueList<int> & allowedCte,
02671 bool allow8Bit,
02672 bool willBeSigned )
02673 {
02674 CharFreq cf( aBuf.data(), aBuf.size()-1 );
02675
02676 allowedCte = determineAllowedCtes( cf, allow8Bit, willBeSigned );
02677
02678 #ifndef NDEBUG
02679 DwString dwCte;
02680 DwCteEnumToStr(allowedCte[0], dwCte);
02681 kdDebug(5006) << "CharFreq returned " << cf.type() << "/"
02682 << cf.printableRatio() << " and I chose "
02683 << dwCte.c_str() << endl;
02684 #endif
02685
02686 setCte( allowedCte[0] );
02687 setBodyEncoded( aBuf );
02688 }
02689
02690
02691
02692 void KMMessage::setBodyEncoded(const QCString& aStr)
02693 {
02694 DwString dwSrc(aStr.data(), aStr.size()-1 );
02695 DwString dwResult;
02696
02697 switch (cte())
02698 {
02699 case DwMime::kCteBase64:
02700 DwEncodeBase64(dwSrc, dwResult);
02701 break;
02702 case DwMime::kCteQuotedPrintable:
02703 DwEncodeQuotedPrintable(dwSrc, dwResult);
02704 break;
02705 default:
02706 dwResult = dwSrc;
02707 break;
02708 }
02709
02710 mMsg->Body().FromString(dwResult);
02711 mNeedsAssembly = true;
02712 }
02713
02714
02715 void KMMessage::setBodyEncodedBinary(const QByteArray& aStr)
02716 {
02717 DwString dwSrc(aStr.data(), aStr.size());
02718 DwString dwResult;
02719
02720 switch (cte())
02721 {
02722 case DwMime::kCteBase64:
02723 DwEncodeBase64(dwSrc, dwResult);
02724 break;
02725 case DwMime::kCteQuotedPrintable:
02726 DwEncodeQuotedPrintable(dwSrc, dwResult);
02727 break;
02728 default:
02729 dwResult = dwSrc;
02730 break;
02731 }
02732
02733 mMsg->Body().FromString(dwResult);
02734 mNeedsAssembly = true;
02735 }
02736
02737
02738
02739 void KMMessage::setBody(const QCString& aStr)
02740 {
02741 mMsg->Body().FromString(KMail::Util::dwString(aStr));
02742 mNeedsAssembly = true;
02743 }
02744 void KMMessage::setBody(const DwString& aStr)
02745 {
02746 mMsg->Body().FromString(aStr);
02747 mNeedsAssembly = true;
02748 }
02749 void KMMessage::setBody(const char* aStr)
02750 {
02751 mMsg->Body().FromString(aStr);
02752 mNeedsAssembly = true;
02753 }
02754
02755 void KMMessage::setMultiPartBody( const QCString & aStr ) {
02756 setBody( aStr );
02757 mMsg->Body().Parse();
02758 mNeedsAssembly = true;
02759 }
02760
02761
02762
02763
02764
02765
02766
02767
02768
02769
02770 int KMMessage::numBodyParts() const
02771 {
02772 int count = 0;
02773 DwBodyPart* part = getFirstDwBodyPart();
02774 QPtrList< DwBodyPart > parts;
02775
02776 while (part)
02777 {
02778
02779 while ( part
02780 && part->hasHeaders()
02781 && part->Headers().HasContentType()
02782 && part->Body().FirstBodyPart()
02783 && (DwMime::kTypeMultipart == part->Headers().ContentType().Type()) )
02784 {
02785 parts.append( part );
02786 part = part->Body().FirstBodyPart();
02787 }
02788
02789 count++;
02790
02791
02792 while (part && !(part->Next()) && !(parts.isEmpty()))
02793 {
02794 part = parts.getLast();
02795 parts.removeLast();
02796 }
02797
02798 if (part && part->Body().Message() &&
02799 part->Body().Message()->Body().FirstBodyPart())
02800 {
02801 part = part->Body().Message()->Body().FirstBodyPart();
02802 } else if (part) {
02803 part = part->Next();
02804 }
02805 }
02806
02807 return count;
02808 }
02809
02810
02811
02812 DwBodyPart * KMMessage::getFirstDwBodyPart() const
02813 {
02814 return mMsg->Body().FirstBodyPart();
02815 }
02816
02817
02818
02819 int KMMessage::partNumber( DwBodyPart * aDwBodyPart ) const
02820 {
02821 DwBodyPart *curpart;
02822 QPtrList< DwBodyPart > parts;
02823 int curIdx = 0;
02824 int idx = 0;
02825
02826
02827 curpart = getFirstDwBodyPart();
02828
02829 while (curpart && !idx) {
02830
02831 while( curpart
02832 && curpart->hasHeaders()
02833 && curpart->Headers().HasContentType()
02834 && curpart->Body().FirstBodyPart()
02835 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) )
02836 {
02837 parts.append( curpart );
02838 curpart = curpart->Body().FirstBodyPart();
02839 }
02840
02841 if (curpart == aDwBodyPart)
02842 idx = curIdx;
02843 curIdx++;
02844
02845
02846 while (curpart && !(curpart->Next()) && !(parts.isEmpty()))
02847 {
02848 curpart = parts.getLast();
02849 parts.removeLast();
02850 } ;
02851 if (curpart)
02852 curpart = curpart->Next();
02853 }
02854 return idx;
02855 }
02856
02857
02858
02859 DwBodyPart * KMMessage::dwBodyPart( int aIdx ) const
02860 {
02861 DwBodyPart *part, *curpart;
02862 QPtrList< DwBodyPart > parts;
02863 int curIdx = 0;
02864
02865
02866 curpart = getFirstDwBodyPart();
02867 part = 0;
02868
02869 while (curpart && !part) {
02870
02871 while( curpart
02872 && curpart->hasHeaders()
02873 && curpart->Headers().HasContentType()
02874 && curpart->Body().FirstBodyPart()
02875 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) )
02876 {
02877 parts.append( curpart );
02878 curpart = curpart->Body().FirstBodyPart();
02879 }
02880
02881 if (curIdx==aIdx)
02882 part = curpart;
02883 curIdx++;
02884
02885
02886 while (curpart && !(curpart->Next()) && !(parts.isEmpty()))
02887 {
02888 curpart = parts.getLast();
02889 parts.removeLast();
02890 }
02891 if (curpart)
02892 curpart = curpart->Next();
02893 }
02894 return part;
02895 }
02896
02897
02898
02899 DwBodyPart * KMMessage::findDwBodyPart( int type, int subtype ) const
02900 {
02901 DwBodyPart *part, *curpart;
02902 QPtrList< DwBodyPart > parts;
02903
02904
02905 curpart = getFirstDwBodyPart();
02906 part = 0;
02907
02908 while (curpart && !part) {
02909
02910 while(curpart
02911 && curpart->hasHeaders()
02912 && curpart->Headers().HasContentType()
02913 && curpart->Body().FirstBodyPart()
02914 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) ) {
02915 parts.append( curpart );
02916 curpart = curpart->Body().FirstBodyPart();
02917 }
02918
02919
02920
02921
02922 if ( curpart && curpart->hasHeaders() && curpart->Headers().HasContentType() ) {
02923 kdDebug(5006) << curpart->Headers().ContentType().TypeStr().c_str()
02924 << " " << curpart->Headers().ContentType().SubtypeStr().c_str() << endl;
02925 }
02926
02927 if (curpart &&
02928 curpart->hasHeaders() &&
02929 curpart->Headers().HasContentType() &&
02930 curpart->Headers().ContentType().Type() == type &&
02931 curpart->Headers().ContentType().Subtype() == subtype) {
02932 part = curpart;
02933 } else {
02934
02935
02936 while (curpart && !(curpart->Next()) && !(parts.isEmpty())) {
02937 curpart = parts.getLast();
02938 parts.removeLast();
02939 } ;
02940 if (curpart)
02941 curpart = curpart->Next();
02942 }
02943 }
02944 return part;
02945 }
02946
02947
02948 DwBodyPart * KMMessage::findDwBodyPart( const QCString& type, const QCString& subtype ) const
02949 {
02950 DwBodyPart *part, *curpart;
02951 QPtrList< DwBodyPart > parts;
02952
02953
02954 curpart = getFirstDwBodyPart();
02955 part = 0;
02956
02957 while (curpart && !part) {
02958
02959 while(curpart
02960 && curpart->hasHeaders()
02961 && curpart->Headers().HasContentType()
02962 && curpart->Body().FirstBodyPart()
02963 && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) ) {
02964 parts.append( curpart );
02965 curpart = curpart->Body().FirstBodyPart();
02966 }
02967
02968
02969
02970
02971 if (curpart && curpart->hasHeaders() && curpart->Headers().HasContentType() ) {
02972 kdDebug(5006) << curpart->Headers().ContentType().TypeStr().c_str()
02973 << " " << curpart->Headers().ContentType().SubtypeStr().c_str() << endl;
02974 }
02975
02976 if (curpart &&
02977 curpart->hasHeaders() &&
02978 curpart->Headers().HasContentType() &&
02979 curpart->Headers().ContentType().TypeStr().c_str() == type &&
02980 curpart->Headers().ContentType().SubtypeStr().c_str() == subtype) {
02981 part = curpart;
02982 } else {
02983
02984
02985 while (curpart && !(curpart->Next()) && !(parts.isEmpty())) {
02986 curpart = parts.getLast();
02987 parts.removeLast();
02988 } ;
02989 if (curpart)
02990 curpart = curpart->Next();
02991 }
02992 }
02993 return part;
02994 }
02995
02996
02997 void applyHeadersToMessagePart( DwHeaders& headers, KMMessagePart* aPart )
02998 {
02999
03000
03001
03002
03003
03004
03005
03006
03007
03008
03009 QCString additionalCTypeParams;
03010 if (headers.HasContentType())
03011 {
03012 DwMediaType& ct = headers.ContentType();
03013 aPart->setOriginalContentTypeStr( ct.AsString().c_str() );
03014 aPart->setTypeStr(ct.TypeStr().c_str());
03015 aPart->setSubtypeStr(ct.SubtypeStr().c_str());
03016 DwParameter *param = ct.FirstParameter();
03017 while(param)
03018 {
03019 if (!qstricmp(param->Attribute().c_str(), "charset"))
03020 aPart->setCharset(QCString(param->Value().c_str()).lower());
03021 else if (!qstrnicmp(param->Attribute().c_str(), "name*", 5))
03022 aPart->setName(KMMsgBase::decodeRFC2231String(KMMsgBase::extractRFC2231HeaderField( param->Value().c_str(), "name" )));
03023 else {
03024 additionalCTypeParams += ';';
03025 additionalCTypeParams += param->AsString().c_str();
03026 }
03027 param=param->Next();
03028 }
03029 }
03030 else
03031 {
03032 aPart->setTypeStr("text");
03033 aPart->setSubtypeStr("plain");
03034 }
03035 aPart->setAdditionalCTypeParamStr( additionalCTypeParams );
03036
03037 if (aPart->name().isEmpty())
03038 {
03039 if (headers.HasContentType() && !headers.ContentType().Name().empty()) {
03040 aPart->setName(KMMsgBase::decodeRFC2047String(headers.
03041 ContentType().Name().c_str()) );
03042 } else if (headers.HasSubject() && !headers.Subject().AsString().empty()) {
03043 aPart->setName( KMMsgBase::decodeRFC2047String(headers.
03044 Subject().AsString().c_str()) );
03045 }
03046 }
03047
03048
03049 if (headers.HasContentTransferEncoding())
03050 aPart->setCteStr(headers.ContentTransferEncoding().AsString().c_str());
03051 else
03052 aPart->setCteStr("7bit");
03053
03054
03055 if (headers.HasContentDescription())
03056 aPart->setContentDescription(headers.ContentDescription().AsString().c_str());
03057 else
03058 aPart->setContentDescription("");
03059
03060
03061 if (headers.HasContentDisposition())
03062 aPart->setContentDisposition(headers.ContentDisposition().AsString().c_str());
03063 else
03064 aPart->setContentDisposition("");
03065 }
03066
03067
03068 void KMMessage::bodyPart(DwBodyPart* aDwBodyPart, KMMessagePart* aPart,
03069 bool withBody)
03070 {
03071 if ( !aPart )
03072 return;
03073
03074 aPart->clear();
03075
03076 if( aDwBodyPart && aDwBodyPart->hasHeaders() ) {
03077
03078
03079
03080
03081 QString partId( aDwBodyPart->partId() );
03082 aPart->setPartSpecifier( partId );
03083
03084 DwHeaders& headers = aDwBodyPart->Headers();
03085 applyHeadersToMessagePart( headers, aPart );
03086
03087
03088 if (withBody)
03089 aPart->setBody( aDwBodyPart->Body().AsString() );
03090 else
03091 aPart->setBody( QCString("") );
03092
03093
03094 if ( headers.HasContentId() ) {
03095 const QCString contentId = headers.ContentId().AsString().c_str();
03096
03097 aPart->setContentId( contentId.mid( 1, contentId.length() - 2 ) );
03098 }
03099 }
03100
03101
03102 else
03103 {
03104 aPart->setTypeStr("");
03105 aPart->setSubtypeStr("");
03106 aPart->setCteStr("");
03107
03108
03109
03110 aPart->setContentDescription("");
03111 aPart->setContentDisposition("");
03112 aPart->setBody(QCString(""));
03113 aPart->setContentId("");
03114 }
03115 }
03116
03117
03118
03119 void KMMessage::bodyPart(int aIdx, KMMessagePart* aPart) const
03120 {
03121 if ( !aPart )
03122 return;
03123
03124
03125 if ( DwBodyPart *part = dwBodyPart( aIdx ) ) {
03126 KMMessage::bodyPart(part, aPart);
03127 if( aPart->name().isEmpty() )
03128 aPart->setName( i18n("Attachment: %1").arg( aIdx ) );
03129 }
03130 }
03131
03132
03133
03134 void KMMessage::deleteBodyParts()
03135 {
03136 mMsg->Body().DeleteBodyParts();
03137 }
03138
03139
03140 DwBodyPart* KMMessage::createDWBodyPart(const KMMessagePart* aPart)
03141 {
03142 DwBodyPart* part = DwBodyPart::NewBodyPart(emptyString, 0);
03143
03144 if ( !aPart )
03145 return part;
03146
03147 QCString charset = aPart->charset();
03148 QCString type = aPart->typeStr();
03149 QCString subtype = aPart->subtypeStr();
03150 QCString cte = aPart->cteStr();
03151 QCString contDesc = aPart->contentDescriptionEncoded();
03152 QCString contDisp = aPart->contentDisposition();
03153 QCString encoding = autoDetectCharset(charset, sPrefCharsets, aPart->name());
03154 if (encoding.isEmpty()) encoding = "utf-8";
03155 QCString name = KMMsgBase::encodeRFC2231String(aPart->name(), encoding);
03156 bool RFC2231encoded = aPart->name() != QString(name);
03157 QCString paramAttr = aPart->parameterAttribute();
03158
03159 DwHeaders& headers = part->Headers();
03160
03161 DwMediaType& ct = headers.ContentType();
03162 if (!type.isEmpty() && !subtype.isEmpty())
03163 {
03164 ct.SetTypeStr(type.data());
03165 ct.SetSubtypeStr(subtype.data());
03166 if (!charset.isEmpty()){
03167 DwParameter *param;
03168 param=new DwParameter;
03169 param->SetAttribute("charset");
03170 param->SetValue(charset.data());
03171 ct.AddParameter(param);
03172 }
03173 }
03174
03175 QCString additionalParam = aPart->additionalCTypeParamStr();
03176 if( !additionalParam.isEmpty() )
03177 {
03178 QCString parAV;
03179 DwString parA, parV;
03180 int iL, i1, i2, iM;
03181 iL = additionalParam.length();
03182 i1 = 0;
03183 i2 = additionalParam.find(';', i1, false);
03184 while ( i1 < iL )
03185 {
03186 if( -1 == i2 )
03187 i2 = iL;
03188 if( i1+1 < i2 ) {
03189 parAV = additionalParam.mid( i1, (i2-i1) );
03190 iM = parAV.find('=');
03191 if( -1 < iM )
03192 {
03193 parA = parAV.left( iM );
03194 parV = parAV.right( parAV.length() - iM - 1 );
03195 if( ('"' == parV.at(0)) && ('"' == parV.at(parV.length()-1)) )
03196 {
03197 parV.erase( 0, 1);
03198 parV.erase( parV.length()-1 );
03199 }
03200 }
03201 else
03202 {
03203 parA = parAV;
03204 parV = "";
03205 }
03206 DwParameter *param;
03207 param = new DwParameter;
03208 param->SetAttribute( parA );
03209 param->SetValue( parV );
03210 ct.AddParameter( param );
03211 }
03212 i1 = i2+1;
03213 i2 = additionalParam.find(';', i1, false);
03214 }
03215 }
03216
03217 if ( !name.isEmpty() ) {
03218 if (RFC2231encoded)
03219 {
03220 DwParameter *nameParam;
03221 nameParam = new DwParameter;
03222 nameParam->SetAttribute("name*");
03223 nameParam->SetValue(name.data(),true);
03224 ct.AddParameter(nameParam);
03225 } else {
03226 ct.SetName(name.data());
03227 }
03228 }
03229
03230 if (!paramAttr.isEmpty())
03231 {
03232 QCString encoding = autoDetectCharset(charset, sPrefCharsets,
03233 aPart->parameterValue());
03234 if (encoding.isEmpty()) encoding = "utf-8";
03235 QCString paramValue;
03236 paramValue = KMMsgBase::encodeRFC2231String(aPart->parameterValue(),
03237 encoding);
03238 DwParameter *param = new DwParameter;
03239 if (aPart->parameterValue() != QString(paramValue))
03240 {
03241 param->SetAttribute((paramAttr + '*').data());
03242 param->SetValue(paramValue.data(),true);
03243 } else {
03244 param->SetAttribute(paramAttr.data());
03245 param->SetValue(paramValue.data());
03246 }
03247 ct.AddParameter(param);
03248 }
03249
03250 if (!cte.isEmpty())
03251 headers.Cte().FromString(cte);
03252
03253 if (!contDesc.isEmpty())
03254 headers.ContentDescription().FromString(contDesc);
03255
03256 if (!contDisp.isEmpty())
03257 headers.ContentDisposition().FromString(contDisp);
03258
03259 const DwString bodyStr = aPart->dwBody();
03260 if (!bodyStr.empty())
03261 part->Body().FromString(bodyStr);
03262 else
03263 part->Body().FromString("");
03264
03265 if (!aPart->partSpecifier().isNull())
03266 part->SetPartId( aPart->partSpecifier().latin1() );
03267
03268 if (aPart->decodedSize() > 0)
03269 part->SetBodySize( aPart->decodedSize() );
03270
03271 return part;
03272 }
03273
03274
03275
03276 void KMMessage::addDwBodyPart(DwBodyPart * aDwPart)
03277 {
03278 mMsg->Body().AddBodyPart( aDwPart );
03279 mNeedsAssembly = true;
03280 }
03281
03282
03283
03284 void KMMessage::addBodyPart(const KMMessagePart* aPart)
03285 {
03286 DwBodyPart* part = createDWBodyPart( aPart );
03287 addDwBodyPart( part );
03288 }
03289
03290
03291
03292 QString KMMessage::generateMessageId( const QString& addr )
03293 {
03294 QDateTime datetime = QDateTime::currentDateTime();
03295 QString msgIdStr;
03296
03297 msgIdStr = '<' + datetime.toString( "yyyyMMddhhmm.sszzz" );
03298
03299 QString msgIdSuffix;
03300 KConfigGroup general( KMKernel::config(), "General" );
03301
03302 if( general.readBoolEntry( "useCustomMessageIdSuffix", false ) )
03303 msgIdSuffix = general.readEntry( "myMessageIdSuffix" );
03304
03305 if( !msgIdSuffix.isEmpty() )
03306 msgIdStr += '@' + msgIdSuffix;
03307 else
03308 msgIdStr += '.' + KPIM::encodeIDN( addr );
03309
03310 msgIdStr += '>';
03311
03312 return msgIdStr;
03313 }
03314
03315
03316
03317 QCString KMMessage::html2source( const QCString & src )
03318 {
03319 QCString result( 1 + 6*(src.size()-1) );
03320
03321 QCString::ConstIterator s = src.begin();
03322 QCString::Iterator d = result.begin();
03323 while ( *s ) {
03324 switch ( *s ) {
03325 case '<': {
03326 *d++ = '&';
03327 *d++ = 'l';
03328 *d++ = 't';
03329 *d++ = ';';
03330 ++s;
03331 }
03332 break;
03333 case '\r': {
03334 ++s;
03335 }
03336 break;
03337 case '\n': {
03338 *d++ = '<';
03339 *d++ = 'b';
03340 *d++ = 'r';
03341 *d++ = '>';
03342 ++s;
03343 }
03344 break;
03345 case '>': {
03346 *d++ = '&';
03347 *d++ = 'g';
03348 *d++ = 't';
03349 *d++ = ';';
03350 ++s;
03351 }
03352 break;
03353 case '&': {
03354 *d++ = '&';
03355 *d++ = 'a';
03356 *d++ = 'm';
03357 *d++ = 'p';
03358 *d++ = ';';
03359 ++s;
03360 }
03361 break;
03362 case '"': {
03363 *d++ = '&';
03364 *d++ = 'q';
03365 *d++ = 'u';
03366 *d++ = 'o';
03367 *d++ = 't';
03368 *d++ = ';';
03369 ++s;
03370 }
03371 break;
03372 case '\'': {
03373 *d++ = '&';
03374 *d++ = 'a';
03375 *d++ = 'p';
03376 *d++ = 's';
03377 *d++ = ';';
03378 ++s;
03379 }
03380 break;
03381 default:
03382 *d++ = *s++;
03383 }
03384 }
03385 result.truncate( d - result.begin() );
03386 return result;
03387 }
03388
03389
03390 QString KMMessage::encodeMailtoUrl( const QString& str )
03391 {
03392 QString result;
03393 result = QString::fromLatin1( KMMsgBase::encodeRFC2047String( str,
03394 "utf-8" ) );
03395 result = KURL::encode_string( result );
03396 return result;
03397 }
03398
03399
03400
03401 QString KMMessage::decodeMailtoUrl( const QString& url )
03402 {
03403 QString result;
03404 result = KURL::decode_string( url );
03405 result = KMMsgBase::decodeRFC2047String( result.latin1() );
03406 return result;
03407 }
03408
03409
03410
03411 QCString KMMessage::stripEmailAddr( const QCString& aStr )
03412 {
03413
03414
03415 if ( aStr.isEmpty() )
03416 return QCString();
03417
03418 QCString result;
03419
03420
03421
03422
03423
03424 QCString name;
03425 QCString comment;
03426 QCString angleAddress;
03427 enum { TopLevel, InComment, InAngleAddress } context = TopLevel;
03428 bool inQuotedString = false;
03429 int commentLevel = 0;
03430
03431 for ( char* p = aStr.data(); *p; ++p ) {
03432 switch ( context ) {
03433 case TopLevel : {
03434 switch ( *p ) {
03435 case '"' : inQuotedString = !inQuotedString;
03436 break;
03437 case '(' : if ( !inQuotedString ) {
03438 context = InComment;
03439 commentLevel = 1;
03440 }
03441 else
03442 name += *p;
03443 break;
03444 case '<' : if ( !inQuotedString ) {
03445 context = InAngleAddress;
03446 }
03447 else
03448 name += *p;
03449 break;
03450 case '\\' :
03451 ++p;
03452 if ( *p )
03453 name += *p;
03454 break;
03455 case ',' : if ( !inQuotedString ) {
03456
03457 if ( !result.isEmpty() )
03458 result += ", ";
03459 name = name.stripWhiteSpace();
03460 comment = comment.stripWhiteSpace();
03461 angleAddress = angleAddress.stripWhiteSpace();
03462
03463
03464
03465
03466
03467
03468
03469
03470 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03471
03472
03473 result += comment;
03474 }
03475 else if ( !name.isEmpty() ) {
03476 result += name;
03477 }
03478 else if ( !comment.isEmpty() ) {
03479 result += comment;
03480 }
03481 else if ( !angleAddress.isEmpty() ) {
03482 result += angleAddress;
03483 }
03484 name = QCString();
03485 comment = QCString();
03486 angleAddress = QCString();
03487 }
03488 else
03489 name += *p;
03490 break;
03491 default : name += *p;
03492 }
03493 break;
03494 }
03495 case InComment : {
03496 switch ( *p ) {
03497 case '(' : ++commentLevel;
03498 comment += *p;
03499 break;
03500 case ')' : --commentLevel;
03501 if ( commentLevel == 0 ) {
03502 context = TopLevel;
03503 comment += ' ';
03504 }
03505 else
03506 comment += *p;
03507 break;
03508 case '\\' :
03509 ++p;
03510 if ( *p )
03511 comment += *p;
03512 break;
03513 default : comment += *p;
03514 }
03515 break;
03516 }
03517 case InAngleAddress : {
03518 switch ( *p ) {
03519 case '"' : inQuotedString = !inQuotedString;
03520 angleAddress += *p;
03521 break;
03522 case '>' : if ( !inQuotedString ) {
03523 context = TopLevel;
03524 }
03525 else
03526 angleAddress += *p;
03527 break;
03528 case '\\' :
03529 ++p;
03530 if ( *p )
03531 angleAddress += *p;
03532 break;
03533 default : angleAddress += *p;
03534 }
03535 break;
03536 }
03537 }
03538 }
03539 if ( !result.isEmpty() )
03540 result += ", ";
03541 name = name.stripWhiteSpace();
03542 comment = comment.stripWhiteSpace();
03543 angleAddress = angleAddress.stripWhiteSpace();
03544
03545
03546
03547
03548
03549 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03550
03551
03552 result += comment;
03553 }
03554 else if ( !name.isEmpty() ) {
03555 result += name;
03556 }
03557 else if ( !comment.isEmpty() ) {
03558 result += comment;
03559 }
03560 else if ( !angleAddress.isEmpty() ) {
03561 result += angleAddress;
03562 }
03563
03564
03565
03566 return result;
03567 }
03568
03569
03570 QString KMMessage::stripEmailAddr( const QString& aStr )
03571 {
03572
03573
03574 if ( aStr.isEmpty() )
03575 return QString::null;
03576
03577 QString result;
03578
03579
03580
03581
03582
03583 QString name;
03584 QString comment;
03585 QString angleAddress;
03586 enum { TopLevel, InComment, InAngleAddress } context = TopLevel;
03587 bool inQuotedString = false;
03588 int commentLevel = 0;
03589
03590 QChar ch;
03591 unsigned int strLength(aStr.length());
03592 for ( uint index = 0; index < strLength; ++index ) {
03593 ch = aStr[index];
03594 switch ( context ) {
03595 case TopLevel : {
03596 switch ( ch.latin1() ) {
03597 case '"' : inQuotedString = !inQuotedString;
03598 break;
03599 case '(' : if ( !inQuotedString ) {
03600 context = InComment;
03601 commentLevel = 1;
03602 }
03603 else
03604 name += ch;
03605 break;
03606 case '<' : if ( !inQuotedString ) {
03607 context = InAngleAddress;
03608 }
03609 else
03610 name += ch;
03611 break;
03612 case '\\' :
03613 ++index;
03614 if ( index < aStr.length() )
03615 name += aStr[index];
03616 break;
03617 case ',' : if ( !inQuotedString ) {
03618
03619 if ( !result.isEmpty() )
03620 result += ", ";
03621 name = name.stripWhiteSpace();
03622 comment = comment.stripWhiteSpace();
03623 angleAddress = angleAddress.stripWhiteSpace();
03624
03625
03626
03627
03628
03629
03630
03631
03632 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03633
03634
03635 result += comment;
03636 }
03637 else if ( !name.isEmpty() ) {
03638 result += name;
03639 }
03640 else if ( !comment.isEmpty() ) {
03641 result += comment;
03642 }
03643 else if ( !angleAddress.isEmpty() ) {
03644 result += angleAddress;
03645 }
03646 name = QString::null;
03647 comment = QString::null;
03648 angleAddress = QString::null;
03649 }
03650 else
03651 name += ch;
03652 break;
03653 default : name += ch;
03654 }
03655 break;
03656 }
03657 case InComment : {
03658 switch ( ch.latin1() ) {
03659 case '(' : ++commentLevel;
03660 comment += ch;
03661 break;
03662 case ')' : --commentLevel;
03663 if ( commentLevel == 0 ) {
03664 context = TopLevel;
03665 comment += ' ';
03666 }
03667 else
03668 comment += ch;
03669 break;
03670 case '\\' :
03671 ++index;
03672 if ( index < aStr.length() )
03673 comment += aStr[index];
03674 break;
03675 default : comment += ch;
03676 }
03677 break;
03678 }
03679 case InAngleAddress : {
03680 switch ( ch.latin1() ) {
03681 case '"' : inQuotedString = !inQuotedString;
03682 angleAddress += ch;
03683 break;
03684 case '>' : if ( !inQuotedString ) {
03685 context = TopLevel;
03686 }
03687 else
03688 angleAddress += ch;
03689 break;
03690 case '\\' :
03691 ++index;
03692 if ( index < aStr.length() )
03693 angleAddress += aStr[index];
03694 break;
03695 default : angleAddress += ch;
03696 }
03697 break;
03698 }
03699 }
03700 }
03701 if ( !result.isEmpty() )
03702 result += ", ";
03703 name = name.stripWhiteSpace();
03704 comment = comment.stripWhiteSpace();
03705 angleAddress = angleAddress.stripWhiteSpace();
03706
03707
03708
03709
03710
03711 if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03712
03713
03714 result += comment;
03715 }
03716 else if ( !name.isEmpty() ) {
03717 result += name;
03718 }
03719 else if ( !comment.isEmpty() ) {
03720 result += comment;
03721 }
03722 else if ( !angleAddress.isEmpty() ) {
03723 result += angleAddress;
03724 }
03725
03726
03727
03728 return result;
03729 }
03730
03731
03732 QString KMMessage::quoteHtmlChars( const QString& str, bool removeLineBreaks )
03733 {
03734 QString result;
03735
03736 unsigned int strLength(str.length());
03737 result.reserve( 6*strLength );
03738 for( unsigned int i = 0; i < strLength; ++i )
03739 switch ( str[i].latin1() ) {
03740 case '<':
03741 result += "<";
03742 break;
03743 case '>':
03744 result += ">";
03745 break;
03746 case '&':
03747 result += "&";
03748 break;
03749 case '"':
03750 result += """;
03751 break;
03752 case '\n':
03753 if ( !removeLineBreaks )
03754 result += "<br>";
03755 break;
03756 case '\r':
03757
03758 break;
03759 default:
03760 result += str[i];
03761 }
03762
03763 result.squeeze();
03764 return result;
03765 }
03766
03767
03768 QString KMMessage::emailAddrAsAnchor(const QString& aEmail, bool stripped, const QString& cssStyle, bool aLink)
03769 {
03770 if( aEmail.isEmpty() )
03771 return aEmail;
03772
03773 QStringList addressList = KPIM::splitEmailAddrList( aEmail );
03774
03775 QString result;
03776
03777 for( QStringList::ConstIterator it = addressList.begin();
03778 ( it != addressList.end() );
03779 ++it ) {
03780 if( !(*it).isEmpty() ) {
03781 QString address = *it;
03782 if(aLink) {
03783 result += "<a href=\"mailto:"
03784 + KMMessage::encodeMailtoUrl( address )
03785 + "\" "+cssStyle+">";
03786 }
03787 if( stripped )
03788 address = KMMessage::stripEmailAddr( address );
03789 result += KMMessage::quoteHtmlChars( address, true );
03790 if(aLink)
03791 result += "</a>, ";
03792 }
03793 }
03794
03795 if(aLink)
03796 result.truncate( result.length() - 2 );
03797
03798
03799
03800 return result;
03801 }
03802
03803
03804
03805
03806 QStringList KMMessage::stripAddressFromAddressList( const QString& address,
03807 const QStringList& list )
03808 {
03809 QStringList addresses( list );
03810 QString addrSpec( KPIM::getEmailAddress( address ) );
03811 for ( QStringList::Iterator it = addresses.begin();
03812 it != addresses.end(); ) {
03813 if ( kasciistricmp( addrSpec.utf8().data(),
03814 KPIM::getEmailAddress( *it ).utf8().data() ) == 0 ) {
03815 kdDebug(5006) << "Removing " << *it << " from the address list"
03816 << endl;
03817 it = addresses.remove( it );
03818 }
03819 else
03820 ++it;
03821 }
03822 return addresses;
03823 }
03824
03825
03826
03827
03828 QStringList KMMessage::stripMyAddressesFromAddressList( const QStringList& list )
03829 {
03830 QStringList addresses = list;
03831 for( QStringList::Iterator it = addresses.begin();
03832 it != addresses.end(); ) {
03833 kdDebug(5006) << "Check whether " << *it << " is one of my addresses"
03834 << endl;
03835 if( kmkernel->identityManager()->thatIsMe( KPIM::getEmailAddress( *it ) ) ) {
03836 kdDebug(5006) << "Removing " << *it << " from the address list"
03837 << endl;
03838 it = addresses.remove( it );
03839 }
03840 else
03841 ++it;
03842 }
03843 return addresses;
03844 }
03845
03846
03847
03848
03849 bool KMMessage::addressIsInAddressList( const QString& address,
03850 const QStringList& addresses )
03851 {
03852 QString addrSpec = KPIM::getEmailAddress( address );
03853 for( QStringList::ConstIterator it = addresses.begin();
03854 it != addresses.end(); ++it ) {
03855 if ( kasciistricmp( addrSpec.utf8().data(),
03856 KPIM::getEmailAddress( *it ).utf8().data() ) == 0 )
03857 return true;
03858 }
03859 return false;
03860 }
03861
03862
03863
03864
03865 QString KMMessage::expandAliases( const QString& recipients )
03866 {
03867 if ( recipients.isEmpty() )
03868 return QString();
03869
03870 QStringList recipientList = KPIM::splitEmailAddrList( recipients );
03871
03872 QString expandedRecipients;
03873 for ( QStringList::Iterator it = recipientList.begin();
03874 it != recipientList.end(); ++it ) {
03875 if ( !expandedRecipients.isEmpty() )
03876 expandedRecipients += ", ";
03877 QString receiver = (*it).stripWhiteSpace();
03878
03879
03880 QString expandedList = KAddrBookExternal::expandDistributionList( receiver );
03881 if ( !expandedList.isEmpty() ) {
03882 expandedRecipients += expandedList;
03883 continue;
03884 }
03885
03886
03887 QString expandedNickName = KabcBridge::expandNickName( receiver );
03888 if ( !expandedNickName.isEmpty() ) {
03889 expandedRecipients += expandedNickName;
03890 continue;
03891 }
03892
03893
03894
03895 if ( receiver.find('@') == -1 ) {
03896 KConfigGroup general( KMKernel::config(), "General" );
03897 QString defaultdomain = general.readEntry( "Default domain" );
03898 if( !defaultdomain.isEmpty() ) {
03899 expandedRecipients += receiver + "@" + defaultdomain;
03900 }
03901 else {
03902 expandedRecipients += guessEmailAddressFromLoginName( receiver );
03903 }
03904 }
03905 else
03906 expandedRecipients += receiver;
03907 }
03908
03909 return expandedRecipients;
03910 }
03911
03912
03913
03914
03915 QString KMMessage::guessEmailAddressFromLoginName( const QString& loginName )
03916 {
03917 if ( loginName.isEmpty() )
03918 return QString();
03919
03920 char hostnameC[256];
03921
03922 hostnameC[255] = '\0';
03923
03924 if ( gethostname( hostnameC, 255 ) )
03925 hostnameC[0] = '\0';
03926 QString address = loginName;
03927 address += '@';
03928 address += QString::fromLocal8Bit( hostnameC );
03929
03930
03931 const KUser user( loginName );
03932 if ( user.isValid() ) {
03933 QString fullName = user.fullName();
03934 if ( fullName.find( QRegExp( "[^ 0-9A-Za-z\\x0080-\\xFFFF]" ) ) != -1 )
03935 address = '"' + fullName.replace( '\\', "\\" ).replace( '"', "\\" )
03936 + "\" <" + address + '>';
03937 else
03938 address = fullName + " <" + address + '>';
03939 }
03940
03941 return address;
03942 }
03943
03944
03945 void KMMessage::readConfig()
03946 {
03947 KMMsgBase::readConfig();
03948
03949 KConfig *config=KMKernel::config();
03950 KConfigGroupSaver saver(config, "General");
03951
03952 config->setGroup("General");
03953
03954 int languageNr = config->readNumEntry("reply-current-language",0);
03955
03956 {
03957 KConfigGroupSaver saver(config, QString("KMMessage #%1").arg(languageNr));
03958 sReplyLanguage = config->readEntry("language",KGlobal::locale()->language());
03959 sReplyStr = config->readEntry("phrase-reply",
03960 i18n("On %D, you wrote:"));
03961 sReplyAllStr = config->readEntry("phrase-reply-all",
03962 i18n("On %D, %F wrote:"));
03963 sForwardStr = config->readEntry("phrase-forward",
03964 i18n("Forwarded Message"));
03965 sIndentPrefixStr = config->readEntry("indent-prefix",">%_");
03966 }
03967
03968 {
03969 KConfigGroupSaver saver(config, "Composer");
03970 sSmartQuote = GlobalSettings::self()->smartQuote();
03971 sWordWrap = GlobalSettings::self()->wordWrap();
03972 sWrapCol = GlobalSettings::self()->lineWrapWidth();
03973 if ((sWrapCol == 0) || (sWrapCol > 78))
03974 sWrapCol = 78;
03975 if (sWrapCol < 30)
03976 sWrapCol = 30;
03977
03978 sPrefCharsets = config->readListEntry("pref-charsets");
03979 }
03980
03981 {
03982 KConfigGroupSaver saver(config, "Reader");
03983 sHeaderStrategy = HeaderStrategy::create( config->readEntry( "header-set-displayed", "rich" ) );
03984 }
03985 }
03986
03987 QCString KMMessage::defaultCharset()
03988 {
03989 QCString retval;
03990
03991 if (!sPrefCharsets.isEmpty())
03992 retval = sPrefCharsets[0].latin1();
03993
03994 if (retval.isEmpty() || (retval == "locale")) {
03995 retval = QCString(kmkernel->networkCodec()->mimeName());
03996 KPIM::kAsciiToLower( retval.data() );
03997 }
03998
03999 if (retval == "jisx0208.1983-0") retval = "iso-2022-jp";
04000 else if (retval == "ksc5601.1987-0") retval = "euc-kr";
04001 return retval;
04002 }
04003
04004 const QStringList &KMMessage::preferredCharsets()
04005 {
04006 return sPrefCharsets;
04007 }
04008
04009
04010 QCString KMMessage::charset() const
04011 {
04012 if ( mMsg->Headers().HasContentType() ) {
04013 DwMediaType &mType=mMsg->Headers().ContentType();
04014 mType.Parse();
04015 DwParameter *param=mType.FirstParameter();
04016 while(param){
04017 if (!kasciistricmp(param->Attribute().c_str(), "charset"))
04018 return param->Value().c_str();
04019 else param=param->Next();
04020 }
04021 }
04022 return "";
04023 }
04024
04025
04026 void KMMessage::setCharset(const QCString& bStr)
04027 {
04028 kdWarning( type() != DwMime::kTypeText )
04029 << "KMMessage::setCharset(): trying to set a charset for a non-textual mimetype." << endl
04030 << "Fix this caller:" << endl
04031 << "====================================================================" << endl
04032 << kdBacktrace( 5 ) << endl
04033 << "====================================================================" << endl;
04034 QCString aStr = bStr;
04035 KPIM::kAsciiToLower( aStr.data() );
04036 DwMediaType &mType = dwContentType();
04037 mType.Parse();
04038 DwParameter *param=mType.FirstParameter();
04039 while(param)
04040
04041 if (!kasciistricmp(param->Attribute().c_str(), "charset")) break;
04042 else param=param->Next();
04043 if (!param){
04044 param=new DwParameter;
04045 param->SetAttribute("charset");
04046 mType.AddParameter(param);
04047 }
04048 else
04049 mType.SetModified();
04050 param->SetValue(DwString(aStr));
04051 mType.Assemble();
04052 }
04053
04054
04055
04056 void KMMessage::setStatus(const KMMsgStatus aStatus, int idx)
04057 {
04058 if (mStatus == aStatus)
04059 return;
04060 KMMsgBase::setStatus(aStatus, idx);
04061 }
04062
04063 void KMMessage::setEncryptionState(const KMMsgEncryptionState s, int idx)
04064 {
04065 if( mEncryptionState == s )
04066 return;
04067 mEncryptionState = s;
04068 mDirty = true;
04069 KMMsgBase::setEncryptionState(s, idx);
04070 }
04071
04072 void KMMessage::setSignatureState(KMMsgSignatureState s, int idx)
04073 {
04074 if( mSignatureState == s )
04075 return;
04076 mSignatureState = s;
04077 mDirty = true;
04078 KMMsgBase::setSignatureState(s, idx);
04079 }
04080
04081 void KMMessage::setMDNSentState( KMMsgMDNSentState status, int idx ) {
04082 if ( mMDNSentState == status )
04083 return;
04084 if ( status == 0 )
04085 status = KMMsgMDNStateUnknown;
04086 mMDNSentState = status;
04087 mDirty = true;
04088 KMMsgBase::setMDNSentState( status, idx );
04089 }
04090
04091
04092 void KMMessage::link( const KMMessage *aMsg, KMMsgStatus aStatus )
04093 {
04094 Q_ASSERT( aStatus == KMMsgStatusReplied
04095 || aStatus == KMMsgStatusForwarded
04096 || aStatus == KMMsgStatusDeleted );
04097
04098 QString message = headerField( "X-KMail-Link-Message" );
04099 if ( !message.isEmpty() )
04100 message += ',';
04101 QString type = headerField( "X-KMail-Link-Type" );
04102 if ( !type.isEmpty() )
04103 type += ',';
04104
04105 message += QString::number( aMsg->getMsgSerNum() );
04106 if ( aStatus == KMMsgStatusReplied )
04107 type += "reply";
04108 else if ( aStatus == KMMsgStatusForwarded )
04109 type += "forward";
04110 else if ( aStatus == KMMsgStatusDeleted )
04111 type += "deleted";
04112
04113 setHeaderField( "X-KMail-Link-Message", message );
04114 setHeaderField( "X-KMail-Link-Type", type );
04115 }
04116
04117
04118 void KMMessage::getLink(int n, ulong *retMsgSerNum, KMMsgStatus *retStatus) const
04119 {
04120 *retMsgSerNum = 0;
04121 *retStatus = KMMsgStatusUnknown;
04122
04123 QString message = headerField("X-KMail-Link-Message");
04124 QString type = headerField("X-KMail-Link-Type");
04125 message = message.section(',', n, n);
04126 type = type.section(',', n, n);
04127
04128 if ( !message.isEmpty() && !type.isEmpty() ) {
04129 *retMsgSerNum = message.toULong();
04130 if ( type == "reply" )
04131 *retStatus = KMMsgStatusReplied;
04132 else if ( type == "forward" )
04133 *retStatus = KMMsgStatusForwarded;
04134 else if ( type == "deleted" )
04135 *retStatus = KMMsgStatusDeleted;
04136 }
04137 }
04138
04139
04140 DwBodyPart* KMMessage::findDwBodyPart( DwBodyPart* part, const QString & partSpecifier )
04141 {
04142 if ( !part ) return 0;
04143 DwBodyPart* current;
04144
04145 if ( part->partId() == partSpecifier )
04146 return part;
04147
04148
04149 if ( part->hasHeaders() &&
04150 part->Headers().HasContentType() &&
04151 part->Body().FirstBodyPart() &&
04152 (DwMime::kTypeMultipart == part->Headers().ContentType().Type() ) &&
04153 (current = findDwBodyPart( part->Body().FirstBodyPart(), partSpecifier )) )
04154 {
04155 return current;
04156 }
04157
04158
04159 if ( part->Body().Message() &&
04160 part->Body().Message()->Body().FirstBodyPart() &&
04161 (current = findDwBodyPart( part->Body().Message()->Body().FirstBodyPart(),
04162 partSpecifier )) )
04163 {
04164 return current;
04165 }
04166
04167
04168 return findDwBodyPart( part->Next(), partSpecifier );
04169 }
04170
04171
04172 void KMMessage::updateBodyPart(const QString partSpecifier, const QByteArray & data)
04173 {
04174 if ( !data.data() || !data.size() )
04175 return;
04176
04177 DwString content( data.data(), data.size() );
04178 if ( numBodyParts() > 0 &&
04179 partSpecifier != "0" &&
04180 partSpecifier != "TEXT" )
04181 {
04182 QString specifier = partSpecifier;
04183 if ( partSpecifier.endsWith(".HEADER") ||
04184 partSpecifier.endsWith(".MIME") ) {
04185
04186 specifier = partSpecifier.section( '.', 0, -2 );
04187 }
04188
04189
04190 mLastUpdated = findDwBodyPart( getFirstDwBodyPart(), specifier );
04191 kdDebug(5006) << "KMMessage::updateBodyPart " << specifier << endl;
04192 if (!mLastUpdated)
04193 {
04194 kdWarning(5006) << "KMMessage::updateBodyPart - can not find part "
04195 << specifier << endl;
04196 return;
04197 }
04198 if ( partSpecifier.endsWith(".MIME") )
04199 {
04200
04201
04202 content.resize( QMAX( content.length(), 2 ) - 2 );
04203
04204
04205 mLastUpdated->Headers().DeleteAllFields();
04206 mLastUpdated->Headers().FromString( content );
04207 mLastUpdated->Headers().Parse();
04208 } else if ( partSpecifier.endsWith(".HEADER") )
04209 {
04210
04211 mLastUpdated->Body().Message()->Headers().FromString( content );
04212 mLastUpdated->Body().Message()->Headers().Parse();
04213 } else {
04214
04215 mLastUpdated->Body().FromString( content );
04216 QString parentSpec = partSpecifier.section( '.', 0, -2 );
04217 if ( !parentSpec.isEmpty() )
04218 {
04219 DwBodyPart* parent = findDwBodyPart( getFirstDwBodyPart(), parentSpec );
04220 if ( parent && parent->hasHeaders() && parent->Headers().HasContentType() )
04221 {
04222 const DwMediaType& contentType = parent->Headers().ContentType();
04223 if ( contentType.Type() == DwMime::kTypeMessage &&
04224 contentType.Subtype() == DwMime::kSubtypeRfc822 )
04225 {
04226
04227
04228 parent->Body().Message()->Body().FromString( content );
04229 }
04230 }
04231 }
04232 }
04233
04234 } else
04235 {
04236
04237 if ( partSpecifier == "TEXT" )
04238 deleteBodyParts();
04239 mMsg->Body().FromString( content );
04240 mMsg->Body().Parse();
04241 }
04242 mNeedsAssembly = true;
04243 if (! partSpecifier.endsWith(".HEADER") )
04244 {
04245
04246 notify();
04247 }
04248 }
04249
04250
04251 void KMMessage::updateAttachmentState( DwBodyPart* part )
04252 {
04253 if ( !part )
04254 part = getFirstDwBodyPart();
04255
04256 if ( !part )
04257 {
04258
04259 setStatus( KMMsgStatusHasNoAttach );
04260 return;
04261 }
04262
04263 bool filenameEmpty = true;
04264 if ( part->hasHeaders() ) {
04265 if ( part->Headers().HasContentDisposition() ) {
04266 DwDispositionType cd = part->Headers().ContentDisposition();
04267 filenameEmpty = cd.Filename().empty();
04268 if ( filenameEmpty ) {
04269
04270 filenameEmpty = KMMsgBase::decodeRFC2231String( KMMsgBase::extractRFC2231HeaderField( cd.AsString().c_str(), "filename" ) ).isEmpty();
04271 }
04272 }
04273 }
04274
04275 if ( part->hasHeaders() &&
04276 ( ( part->Headers().HasContentDisposition() &&
04277 !part->Headers().ContentDisposition().Filename().empty() ) ||
04278 ( part->Headers().HasContentType() &&
04279 !filenameEmpty ) ) )
04280 {
04281
04282 if ( !part->Headers().HasContentType() ||
04283 ( part->Headers().HasContentType() &&
04284 part->Headers().ContentType().Subtype() != DwMime::kSubtypePgpSignature &&
04285 part->Headers().ContentType().Subtype() != DwMime::kSubtypePkcs7Signature ) )
04286 {
04287 setStatus( KMMsgStatusHasAttach );
04288 }
04289 return;
04290 }
04291
04292
04293 if ( part->hasHeaders() &&
04294 part->Headers().HasContentType() &&
04295 part->Body().FirstBodyPart() &&
04296 (DwMime::kTypeMultipart == part->Headers().ContentType().Type() ) )
04297 {
04298 updateAttachmentState( part->Body().FirstBodyPart() );
04299 }
04300
04301
04302 if ( part->Body().Message() &&
04303 part->Body().Message()->Body().FirstBodyPart() )
04304 {
04305 updateAttachmentState( part->Body().Message()->Body().FirstBodyPart() );
04306 }
04307
04308
04309 if ( part->Next() )
04310 updateAttachmentState( part->Next() );
04311 else if ( attachmentState() == KMMsgAttachmentUnknown )
04312 setStatus( KMMsgStatusHasNoAttach );
04313 }
04314
04315 void KMMessage::setBodyFromUnicode( const QString & str ) {
04316 QCString encoding = KMMsgBase::autoDetectCharset( charset(), KMMessage::preferredCharsets(), str );
04317 if ( encoding.isEmpty() )
04318 encoding = "utf-8";
04319 const QTextCodec * codec = KMMsgBase::codecForName( encoding );
04320 assert( codec );
04321 QValueList<int> dummy;
04322 setCharset( encoding );
04323 setBodyAndGuessCte( codec->fromUnicode( str ), dummy, false );
04324 }
04325
04326 const QTextCodec * KMMessage::codec() const {
04327 const QTextCodec * c = mOverrideCodec;
04328 if ( !c )
04329
04330 c = KMMsgBase::codecForName( charset() );
04331 if ( !c ) {
04332
04333
04334 c = KMMsgBase::codecForName( GlobalSettings::self()->fallbackCharacterEncoding().latin1() );
04335 }
04336 if ( !c )
04337
04338
04339 c = kmkernel->networkCodec();
04340 assert( c );
04341 return c;
04342 }
04343
04344 QString KMMessage::bodyToUnicode(const QTextCodec* codec) const {
04345 if ( !codec )
04346
04347 codec = this->codec();
04348 assert( codec );
04349
04350 return codec->toUnicode( bodyDecoded() );
04351 }
04352
04353
04354 QCString KMMessage::mboxMessageSeparator()
04355 {
04356 QCString str( KPIM::getFirstEmailAddress( rawHeaderField("From") ) );
04357 if ( str.isEmpty() )
04358 str = "unknown@unknown.invalid";
04359 QCString dateStr( dateShortStr() );
04360 if ( dateStr.isEmpty() ) {
04361 time_t t = ::time( 0 );
04362 dateStr = ctime( &t );
04363 const int len = dateStr.length();
04364 if ( dateStr[len-1] == '\n' )
04365 dateStr.truncate( len - 1 );
04366 }
04367 return "From " + str + " " + dateStr + "\n";
04368 }
04369
04370 void KMMessage::deleteWhenUnused()
04371 {
04372 sPendingDeletes << this;
04373 }