kmail

kmmessage.cpp

00001 // -*- mode: C++; c-file-style: "gnu" -*-
00002 // kmmessage.cpp
00003 
00004 // if you do not want GUI elements in here then set ALLOW_GUI to 0.
00005 #include <config.h>
00006 // needed temporarily until KMime is replacing the partNode helper class:
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 // Values that are set from the config file with KMMessage::readConfig()
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 //helper
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   // aMsg might need assembly
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   // now overwrite a few from the msgInfo
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(); // to be safe
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;//other.mNeedsAssembly;
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   //mFileName = ""; // we might not want to copy the other messages filename (?)
00189   //KMMsgBase::assign( &other );
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 //WARNING: This method updates the memory resident cache of serial numbers
00223 //WARNING: held in MessageProperty, but it does not update the persistent
00224 //WARNING: store of serial numbers on the file system that is managed by
00225 //WARNING: KMMsgDict
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 //FIXME: move to libemailfunctions
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() ); // and another copy again!
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   //kdDebug(5006) << "Setting SignatureState header field to " << str[0] << endl;
00366   setHeaderField("X-KMail-SignatureState", str);
00367 
00368   str[0] = static_cast<char>( mdnSentState() );
00369   setHeaderField("X-KMail-MDN-Sent", str);
00370 
00371   // We better do the assembling ourselves now to prevent the
00372   // mimelib from changing the message *body*.  (khz, 10.8.2002)
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     /* I'm not too sure about this change. Is it not possible
00444        to have a long form of the date used? I don't
00445        like this change to a short XX/XX/YY date format.
00446        At least not for the default. -sanders */
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     // TODO: Replace tabs with spaces first.
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             // Couldn't break before maxLength.
00570             i = maxLength;
00571 //            while( (i < (int) text.length()) && (text[i] != ' '))
00572 //               i++;
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    // Remove empty lines at end of quote
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         // Search if the last non-blank line could be "From" line
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   // initialy parse the complete message to decrypt any encrypted parts
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     // now parse the TEXT message part we want to quote
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   // decrypt
00766   if ( allowDecryption ) {
00767     QPtrList<Kpgp::Block> pgpBlocks;
00768     QStrList nonPgpBlocks;
00769     if ( Kpgp::Module::prepareMessageForDecryption( parsedString,
00770                             pgpBlocks,
00771                             nonPgpBlocks ) ) {
00772       // Only decrypt/strip off the signature if there is only one OpenPGP
00773       // block in the message
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         // try to decrypt this OpenPGP block
00780         block->decrypt();
00781       } else {
00782         // strip off the signature
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   // html -> plaintext conversion, if necessary:
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   // strip the signature (footer):
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 /* = QString::null */,
00826                    bool aStripSignature /* = true */,
00827                    bool allowDecryption /* = true */) const
00828 {
00829   QString content = selection.isEmpty() ?
00830     asPlainText( aStripSignature, allowDecryption ) : selection ;
00831 
00832   // Remove blank lines at the beginning:
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 /* = QString::null */,
00853                                    bool noQuote /* = false */,
00854                                    bool allowDecryption /* = true */,
00855                                    bool selectionIsBody /* = false */,
00856                                    const QString &tmpl /* = QString::null */ )
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   // determine the mailing list posting address
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 ) // matched
00880       mailingListAddresses << rx.cap(1) + '@' + rx.cap(2);
00881   }
00882 
00883   // use the "On ... Joe User wrote:" header by default
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       // assume a Reply-To header mangling mailing list
00893       toStr = replyToStr;
00894     }
00895     else if ( !mailingListAddresses.isEmpty() ) {
00896       toStr = mailingListAddresses[0];
00897     }
00898     else {
00899       // doesn't seem to be a mailing list, reply to From: address
00900       toStr = from();
00901       replyStr = sReplyStr; // reply to author, so use "On ... you wrote:"
00902       replyAll = false;
00903     }
00904     // strip all my addresses from the list of recipients
00905     QStringList recipients = KPIM::splitEmailAddrList( toStr );
00906     toStr = stripMyAddressesFromAddressList( recipients ).join(", ");
00907     // ... unless the list contains only my addresses (reply to self)
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       // assume a Reply-To header mangling mailing list
00922       toStr = replyToStr;
00923     }
00924     // strip all my addresses from the list of recipients
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     // add addresses from the Reply-To header to the list of recipients
00935     if( !replyToStr.isEmpty() ) {
00936       recipients += KPIM::splitEmailAddrList( replyToStr );
00937       // strip all possible mailing list addresses from the list of Reply-To
00938       // addresses
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       // this is a mailing list message
00948       if ( recipients.isEmpty() && !from().isEmpty() ) {
00949         // The sender didn't set a Reply-to address, so we add the From
00950         // address to the list of CC recipients.
00951         ccRecipients += from();
00952         kdDebug(5006) << "Added " << from() << " to the list of CC recipients"
00953                       << endl;
00954       }
00955       // if it is a mailing list, add the posting address
00956       recipients.prepend( mailingListAddresses[0] );
00957     }
00958     else {
00959       // this is a normal message
00960       if ( recipients.isEmpty() && !from().isEmpty() ) {
00961         // in case of replying to a normal message only then add the From
00962         // address to the list of recipients if there was no Reply-to address
00963         recipients += from();
00964         kdDebug(5006) << "Added " << from() << " to the list of recipients"
00965                       << endl;
00966       }
00967     }
00968 
00969     // strip all my addresses from the list of recipients
00970     toStr = stripMyAddressesFromAddressList( recipients ).join(", ");
00971 
00972     // merge To header and CC header into a list of CC recipients
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       // strip all my addresses from the list of CC recipients
00991       ccRecipients = stripMyAddressesFromAddressList( ccRecipients );
00992 
00993       // in case of a reply to self toStr might be empty. if that's the case
00994       // then propagate a cc recipient to To: (if there is any).
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       // reply to self without other recipients
01005       toStr = recipients[0];
01006     }
01007     break;
01008   }
01009   case KMail::ReplyAuthor : {
01010     if ( !replyToStr.isEmpty() ) {
01011       QStringList recipients = KPIM::splitEmailAddrList( replyToStr );
01012       // strip the mailing list post address from the list of Reply-To
01013       // addresses since we want to reply in private
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         // there was only the mailing list post address in the Reply-To header,
01024         // so use the From address instead
01025         toStr = from();
01026       }
01027     }
01028     else if ( !from().isEmpty() ) {
01029       toStr = from();
01030     }
01031     replyStr = sReplyStr; // reply to author, so use "On ... you wrote:"
01032     replyAll = false;
01033     break;
01034   }
01035   case KMail::ReplyNone : {
01036     // the addressees will be set by the caller
01037   }
01038   }
01039 
01040   msg->setTo(toStr);
01041 
01042   refStr = getRefStr();
01043   if (!refStr.isEmpty())
01044     msg->setReferences(refStr);
01045   //In-Reply-To = original msg-id
01046   msg->setReplyToId(msgId());
01047 
01048 //   if (!noQuote) {
01049 //     if( selectionIsBody ){
01050 //       QCString cStr = selection.latin1();
01051 //       msg->setBody( cStr );
01052 //     }else{
01053 //       msg->setBody(asQuotedString(replyStr + "\n", sIndentPrefixStr, selection,
01054 //                sSmartQuote, allowDecryption).utf8());
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   // setStatus(KMMsgStatusReplied);
01069   msg->link(this, KMMsgStatusReplied);
01070 
01071   if ( parent() && parent()->putRepliesInSameFolder() )
01072     msg->setFcc( parent()->idString() );
01073 
01074   // replies to an encrypted message should be encrypted as well
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   // copy the message 1:1
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   // X-KMail-Redirect-From: content
01127   QString strByWayOf = QString("%1 (by way of %2 <%3>)")
01128     .arg( from() )
01129     .arg( ident.fullName() )
01130     .arg( ident.emailAddr() );
01131 
01132   // Resent-From: content
01133   QString strFrom = QString("%1 <%2>")
01134     .arg( ident.fullName() )
01135     .arg( ident.emailAddr() );
01136 
01137   // format the current date to be used in Resent-Date:
01138   QString origDate = msg->headerField( "Date" );
01139   msg->setDateToday();
01140   QString newDate = msg->headerField( "Date" );
01141   // make sure the Date: header is valid
01142   if ( origDate.isEmpty() )
01143     msg->removeHeaderField( "Date" );
01144   else
01145     msg->setHeaderField( "Date", origDate );
01146 
01147   // prepend Resent-*: headers (c.f. RFC2822 3.6.6)
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    // Strip out all headers apart from the content description and other
01195    // whitelisted ones, because we don't want to inherit them.
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 /* = QString::null */ )
01212 {
01213   KMMessage* msg = new KMMessage();
01214   QString id;
01215 
01216   // If this is a multipart mail or if the main part is only the text part,
01217   // Make an identical copy of the mail, minus headers, so attachments are
01218   // preserved
01219   if ( type() == DwMime::kTypeMultipart ||
01220      ( type() == DwMime::kTypeText && subtype() == DwMime::kSubtypePlain ) ) {
01221     // ## slow, we could probably use: delete msg->mMsg; msg->mMsg = new DwMessage( this->mMsg );
01222     msg->fromDwString( this->asDwString() );
01223     // remember the type and subtype, initFromMessage sets the contents type to
01224     // text/plain, via initHeader, for unclear reasons
01225     const int type = msg->type();
01226     const int subtype = msg->subtype();
01227 
01228     msg->sanitizeHeaders();
01229 
01230     // strip blacklisted parts
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     //restore type
01246     msg->setType( type );
01247     msg->setSubtype( subtype );
01248   } else if( type() == DwMime::kTypeText && subtype() == DwMime::kSubtypeHtml ) {
01249     // This is non-multipart html mail. Let`s make it text/plain and allow
01250     // template parser do the hard job.
01251     msg->initFromMessage( this );
01252     msg->setType( DwMime::kTypeText );
01253     msg->setSubtype( DwMime::kSubtypeHtml );
01254     msg->mNeedsAssembly = true;
01255     msg->cleanupHeader();
01256   } else {
01257     // This is a non-multipart, non-text mail (e.g. text/calendar). Construct
01258     // a multipart/mixed mail and add the original body as an attachment.
01259     msg->initFromMessage( this );
01260     msg->removeHeaderField("Content-Type");
01261     msg->removeHeaderField("Content-Transfer-Encoding");
01262     // Modify the ContentType directly (replaces setAutomaticFields(true))
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     // empty text part
01272     KMMessagePart msgPart;
01273     bodyPart( 0, &msgPart );
01274     msg->addBodyPart(&msgPart);
01275     // the old contents of the mail
01276     KMMessagePart secondPart;
01277     secondPart.setType( type() );
01278     secondPart.setSubtype( subtype() );
01279     secondPart.setBody( mMsg->Body().AsString() );
01280     // use the headers of the original mail
01281     applyHeadersToMessagePart( mMsg->Headers(), &secondPart );
01282     msg->addBodyPart(&secondPart);
01283     msg->mNeedsAssembly = true;
01284     msg->cleanupHeader();
01285   }
01286   // QString st = QString::fromUtf8(createForwardBody());
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   // QCString encoding = autoDetectCharset(charset(), sPrefCharsets, msg->body());
01300   // if (encoding.isEmpty()) encoding = "utf-8";
01301   // msg->setCharset(encoding);
01302 
01303   // force utf-8
01304   // msg->setCharset( "utf-8" );
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 ; // map to "mode" in createMDN
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 ; // map to "mode" in createMDN
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   // RFC 2298: At most one MDN may be issued on behalf of each
01382   // particular recipient by their user agent.  That is, once an MDN
01383   // has been issued on behalf of a recipient, no further MDNs may be
01384   // issued on behalf of that recipient, even if another disposition
01385   // is performed on the message.
01386 //#define MDN_DEBUG 1
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   // RFC 2298: An MDN MUST NOT be generated in response to an MDN.
01397   if ( findDwBodyPart( DwMime::kTypeMessage,
01398                DwMime::kSubtypeDispositionNotification ) ) {
01399     setMDNSentState( KMMsgMDNIgnore );
01400     return 0;
01401   }
01402 
01403   // extract where to send to:
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; // set to manual if asked user
01410   QString special; // fill in case of error, warning or failure
01411   KConfigGroup mdnConfig( KMKernel::config(), "MDN" );
01412 
01413   // default:
01414   int mode = mdnConfig.readNumEntry( "default-policy", 0 );
01415   if ( !mode || mode < 0 || mode > 3 ) {
01416     // early out for ignore:
01417     setMDNSentState( KMMsgMDNIgnore );
01418     return 0;
01419   }
01420 
01421   // RFC 2298: An importance of "required" indicates that
01422   // interpretation of the parameter is necessary for proper
01423   // generation of an MDN in response to this request.  If a UA does
01424   // not understand the meaning of the parameter, it MUST NOT generate
01425   // an MDN with any disposition type other than "failed" in response
01426   // to the request.
01427   QString notificationOptions = headerField("Disposition-Notification-Options");
01428   if ( notificationOptions.contains( "required", false ) ) {
01429     // ### hacky; should parse...
01430     // There is a required option that we don't understand. We need to
01431     // ask the user what we should do:
01432     if ( !allowGUI ) return 0; // don't setMDNSentState here!
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(); // clear modifiers
01440   }
01441 
01442   // RFC 2298: [ Confirmation from the user SHOULD be obtained (or no
01443   // MDN sent) ] if there is more than one distinct address in the
01444   // Disposition-Notification-To header.
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; // don't setMDNSentState here!
01449     mode = requestAdviceOnMDN( "mdnMultipleAddressesInReceiptTo" );
01450     s = MDN::SentManually;
01451   }
01452 
01453   // RFC 2298: MDNs SHOULD NOT be sent automatically if the address in
01454   // the Disposition-Notification-To header differs from the address
01455   // in the Return-Path header. [...] Confirmation from the user
01456   // SHOULD be obtained (or no MDN sent) if there is no Return-Path
01457   // header in the message [...]
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; // don't setMDNSentState here!
01464     mode = requestAdviceOnMDN( returnPath.isEmpty() ?
01465                    "mdnReturnPathEmpty" :
01466                    "mdnReturnPathNotInReceiptTo" );
01467     s = MDN::SentManually;
01468   }
01469 
01470   if ( a != KMime::MDN::AutomaticAction ) {
01471     //TODO: only ingore user settings for AutomaticAction if requested
01472     if ( mode == 1 ) { // ask
01473       if ( !allowGUI ) return 0; // don't setMDNSentState here!
01474       mode = requestAdviceOnMDN( "mdnNormalAsk" );
01475       s = MDN::SentManually; // asked user
01476     }
01477 
01478     switch ( mode ) {
01479       case 0: // ignore:
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: // deny
01488         d = MDN::Denied;
01489         m.clear();
01490         break;
01491       case 3:
01492         break;
01493     }
01494   }
01495 
01496 
01497   // extract where to send from:
01498   QString finalRecipient = kmkernel->identityManager()
01499     ->identityForUoidOrDefault( identityUoid() ).fullEmailAddr();
01500 
01501   //
01502   // Generate message:
01503   //
01504 
01505   KMMessage * receipt = new KMMessage();
01506   receipt->initFromMessage( this );
01507   receipt->removeHeaderField("Content-Type");
01508   receipt->removeHeaderField("Content-Transfer-Encoding");
01509   // Modify the ContentType directly (replaces setAutomaticFields(true))
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   // text/plain part:
01522   KMMessagePart firstMsgPart;
01523   firstMsgPart.setTypeStr( "text" );
01524   firstMsgPart.setSubtypeStr( "plain" );
01525   firstMsgPart.setBodyFromUnicode( description );
01526   receipt->addBodyPart( &firstMsgPart );
01527 
01528   // message/disposition-notification part:
01529   KMMessagePart secondMsgPart;
01530   secondMsgPart.setType( DwMime::kTypeMessage );
01531   secondMsgPart.setSubtype( DwMime::kSubtypeDispositionNotification );
01532   //secondMsgPart.setCharset( "us-ascii" );
01533   //secondMsgPart.setCteStr( "7bit" );
01534   secondMsgPart.setBodyEncoded( MDN::dispositionNotificationBodyContent(
01535                         finalRecipient,
01536                 rawHeaderField("Original-Recipient"),
01537                 id(), /* Message-ID */
01538                 d, a, s, m, special ) );
01539   receipt->addBodyPart( &secondMsgPart );
01540 
01541   // message/rfc822 or text/rfc822-headers body part:
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   // Set "MDN sent" status:
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   // Conversion to latin1 is correct here as Mail headers should contain
01635   // ascii only
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   // This will allow to change Content-Type:
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     // Set the type to 'Multipart' and the subtype to 'Mixed'
01766     DwMediaType& contentType = dwContentType();
01767     contentType.SetType(   DwMime::kTypeMultipart);
01768     contentType.SetSubtype(DwMime::kSubtypeMixed );
01769 
01770     // Create a random printable string and set it as the boundary parameter
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   //kdDebug(5006)<<"####  Date = "<<header.Date().AsString().c_str()<<endl;
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   // handle To same as Cc below, bug 80747
01878   return KPIM::normalizeAddressesAndDecodeIDNs( headerFields( "To" ).join( ", " ) );
01879 }
01880 
01881 
01882 //-----------------------------------------------------------------------------
01883 void KMMessage::setTo(const QString& aStr)
01884 {
01885   setHeaderField( "To", aStr, Address );
01886 }
01887 
01888 //-----------------------------------------------------------------------------
01889 QString KMMessage::toStrip() const
01890 {
01891   return stripEmailAddr( to() );
01892 }
01893 
01894 //-----------------------------------------------------------------------------
01895 QString KMMessage::replyTo() const
01896 {
01897   return KPIM::normalizeAddressesAndDecodeIDNs( headerField("Reply-To") );
01898 }
01899 
01900 
01901 //-----------------------------------------------------------------------------
01902 void KMMessage::setReplyTo(const QString& aStr)
01903 {
01904   setHeaderField( "Reply-To", aStr, Address );
01905 }
01906 
01907 
01908 //-----------------------------------------------------------------------------
01909 void KMMessage::setReplyTo(KMMessage* aMsg)
01910 {
01911   setHeaderField( "Reply-To", aMsg->from(), Address );
01912 }
01913 
01914 
01915 //-----------------------------------------------------------------------------
01916 QString KMMessage::cc() const
01917 {
01918   // get the combined contents of all Cc headers (as workaround for invalid
01919   // messages with multiple Cc headers)
01920   return KPIM::normalizeAddressesAndDecodeIDNs( headerFields( "Cc" ).join( ", " ) );
01921 }
01922 
01923 
01924 //-----------------------------------------------------------------------------
01925 void KMMessage::setCc(const QString& aStr)
01926 {
01927   setHeaderField( "Cc", aStr, Address );
01928 }
01929 
01930 
01931 //-----------------------------------------------------------------------------
01932 QString KMMessage::ccStrip() const
01933 {
01934   return stripEmailAddr( cc() );
01935 }
01936 
01937 
01938 //-----------------------------------------------------------------------------
01939 QString KMMessage::bcc() const
01940 {
01941   return KPIM::normalizeAddressesAndDecodeIDNs( headerField("Bcc") );
01942 }
01943 
01944 
01945 //-----------------------------------------------------------------------------
01946 void KMMessage::setBcc(const QString& aStr)
01947 {
01948   setHeaderField( "Bcc", aStr, Address );
01949 }
01950 
01951 //-----------------------------------------------------------------------------
01952 QString KMMessage::fcc() const
01953 {
01954   return headerField( "X-KMail-Fcc" );
01955 }
01956 
01957 
01958 //-----------------------------------------------------------------------------
01959 void KMMessage::setFcc( const QString &aStr )
01960 {
01961   setHeaderField( "X-KMail-Fcc", aStr );
01962 }
01963 
01964 //-----------------------------------------------------------------------------
01965 void KMMessage::setDrafts( const QString &aStr )
01966 {
01967   mDrafts = aStr;
01968 }
01969 
01970 //-----------------------------------------------------------------------------
01971 void KMMessage::setTemplates( const QString &aStr )
01972 {
01973   mTemplates = aStr;
01974 }
01975 
01976 //-----------------------------------------------------------------------------
01977 QString KMMessage::who() const
01978 {
01979   if (mParent)
01980     return KPIM::normalizeAddressesAndDecodeIDNs( headerField(mParent->whoField().utf8()) );
01981   return from();
01982 }
01983 
01984 
01985 //-----------------------------------------------------------------------------
01986 QString KMMessage::from() const
01987 {
01988   return KPIM::normalizeAddressesAndDecodeIDNs( headerField("From") );
01989 }
01990 
01991 
01992 //-----------------------------------------------------------------------------
01993 void KMMessage::setFrom(const QString& bStr)
01994 {
01995   QString aStr = bStr;
01996   if (aStr.isNull())
01997     aStr = "";
01998   setHeaderField( "From", aStr, Address );
01999   mDirty = true;
02000 }
02001 
02002 
02003 //-----------------------------------------------------------------------------
02004 QString KMMessage::fromStrip() const
02005 {
02006   return stripEmailAddr( from() );
02007 }
02008 
02009 //-----------------------------------------------------------------------------
02010 QString KMMessage::sender() const {
02011   AddrSpecList asl = extractAddrSpecs( "Sender" );
02012   if ( asl.empty() )
02013     asl = extractAddrSpecs( "From" );
02014   if ( asl.empty() )
02015     return QString::null;
02016   return asl.front().asString();
02017 }
02018 
02019 //-----------------------------------------------------------------------------
02020 QString KMMessage::subject() const
02021 {
02022   return headerField("Subject");
02023 }
02024 
02025 
02026 //-----------------------------------------------------------------------------
02027 void KMMessage::setSubject(const QString& aStr)
02028 {
02029   setHeaderField("Subject",aStr);
02030   mDirty = true;
02031 }
02032 
02033 
02034 //-----------------------------------------------------------------------------
02035 QString KMMessage::xmark() const
02036 {
02037   return headerField("X-KMail-Mark");
02038 }
02039 
02040 
02041 //-----------------------------------------------------------------------------
02042 void KMMessage::setXMark(const QString& aStr)
02043 {
02044   setHeaderField("X-KMail-Mark", aStr);
02045   mDirty = true;
02046 }
02047 
02048 
02049 //-----------------------------------------------------------------------------
02050 QString KMMessage::replyToId() const
02051 {
02052   int leftAngle, rightAngle;
02053   QString replyTo, references;
02054 
02055   replyTo = headerField("In-Reply-To");
02056   // search the end of the (first) message id in the In-Reply-To header
02057   rightAngle = replyTo.find( '>' );
02058   if (rightAngle != -1)
02059     replyTo.truncate( rightAngle + 1 );
02060   // now search the start of the message id
02061   leftAngle = replyTo.findRev( '<' );
02062   if (leftAngle != -1)
02063     replyTo = replyTo.mid( leftAngle );
02064 
02065   // if we have found a good message id we can return immediately
02066   // We ignore mangled In-Reply-To headers which are created by a
02067   // misconfigured Mutt. They look like this <"from foo"@bar.baz>, i.e.
02068   // they contain double quotes and spaces. We only check for '"'.
02069   if (!replyTo.isEmpty() && (replyTo[0] == '<') &&
02070       ( -1 == replyTo.find( '"' ) ) )
02071     return replyTo;
02072 
02073   references = headerField("References");
02074   leftAngle = references.findRev( '<' );
02075   if (leftAngle != -1)
02076     references = references.mid( leftAngle );
02077   rightAngle = references.find( '>' );
02078   if (rightAngle != -1)
02079     references.truncate( rightAngle + 1 );
02080 
02081   // if we found a good message id in the References header return it
02082   if (!references.isEmpty() && references[0] == '<')
02083     return references;
02084   // else return the broken message id we found in the In-Reply-To header
02085   else
02086     return replyTo;
02087 }
02088 
02089 
02090 //-----------------------------------------------------------------------------
02091 QString KMMessage::replyToIdMD5() const {
02092   return base64EncodedMD5( replyToId() );
02093 }
02094 
02095 //-----------------------------------------------------------------------------
02096 QString KMMessage::references() const
02097 {
02098   int leftAngle, rightAngle;
02099   QString references = headerField( "References" );
02100 
02101   // keep the last two entries for threading
02102   leftAngle = references.findRev( '<' );
02103   leftAngle = references.findRev( '<', leftAngle - 1 );
02104   if( leftAngle != -1 )
02105     references = references.mid( leftAngle );
02106   rightAngle = references.findRev( '>' );
02107   if( rightAngle != -1 )
02108     references.truncate( rightAngle + 1 );
02109 
02110   if( !references.isEmpty() && references[0] == '<' )
02111     return references;
02112   else
02113     return QString::null;
02114 }
02115 
02116 //-----------------------------------------------------------------------------
02117 QString KMMessage::replyToAuxIdMD5() const
02118 {
02119   QString result = references();
02120   // references contains two items, use the first one
02121   // (the second to last reference)
02122   const int rightAngle = result.find( '>' );
02123   if( rightAngle != -1 )
02124     result.truncate( rightAngle + 1 );
02125 
02126   return base64EncodedMD5( result );
02127 }
02128 
02129 //-----------------------------------------------------------------------------
02130 QString KMMessage::strippedSubjectMD5() const {
02131   return base64EncodedMD5( stripOffPrefixes( subject() ), true /*utf8*/ );
02132 }
02133 
02134 //-----------------------------------------------------------------------------
02135 QString KMMessage::subjectMD5() const {
02136   return base64EncodedMD5( subject(), true /*utf8*/ );
02137 }
02138 
02139 //-----------------------------------------------------------------------------
02140 bool KMMessage::subjectIsPrefixed() const {
02141   return subjectMD5() != strippedSubjectMD5();
02142 }
02143 
02144 //-----------------------------------------------------------------------------
02145 void KMMessage::setReplyToId(const QString& aStr)
02146 {
02147   setHeaderField("In-Reply-To", aStr);
02148   mDirty = true;
02149 }
02150 
02151 
02152 //-----------------------------------------------------------------------------
02153 QString KMMessage::msgId() const
02154 {
02155   QString msgId = headerField("Message-Id");
02156 
02157   // search the end of the message id
02158   const int rightAngle = msgId.find( '>' );
02159   if (rightAngle != -1)
02160     msgId.truncate( rightAngle + 1 );
02161   // now search the start of the message id
02162   const int leftAngle = msgId.findRev( '<' );
02163   if (leftAngle != -1)
02164     msgId = msgId.mid( leftAngle );
02165   return msgId;
02166 }
02167 
02168 
02169 //-----------------------------------------------------------------------------
02170 QString KMMessage::msgIdMD5() const {
02171   return base64EncodedMD5( msgId() );
02172 }
02173 
02174 
02175 //-----------------------------------------------------------------------------
02176 void KMMessage::setMsgId(const QString& aStr)
02177 {
02178   setHeaderField("Message-Id", aStr);
02179   mDirty = true;
02180 }
02181 
02182 //-----------------------------------------------------------------------------
02183 size_t KMMessage::msgSizeServer() const {
02184   return headerField( "X-Length" ).toULong();
02185 }
02186 
02187 
02188 //-----------------------------------------------------------------------------
02189 void KMMessage::setMsgSizeServer(size_t size)
02190 {
02191   setHeaderField("X-Length", QCString().setNum(size));
02192   mDirty = true;
02193 }
02194 
02195 //-----------------------------------------------------------------------------
02196 ulong KMMessage::UID() const {
02197   return headerField( "X-UID" ).toULong();
02198 }
02199 
02200 
02201 //-----------------------------------------------------------------------------
02202 void KMMessage::setUID(ulong uid)
02203 {
02204   setHeaderField("X-UID", QCString().setNum(uid));
02205   mDirty = true;
02206 }
02207 
02208 //-----------------------------------------------------------------------------
02209 AddressList KMMessage::splitAddrField( const QCString & str )
02210 {
02211   AddressList result;
02212   const char * scursor = str.begin();
02213   if ( !scursor )
02214     return AddressList();
02215   const char * const send = str.begin() + str.length();
02216   if ( !parseAddressList( scursor, send, result ) )
02217     kdDebug(5006) << "Error in address splitting: parseAddressList returned false!"
02218                   << endl;
02219   return result;
02220 }
02221 
02222 AddressList KMMessage::headerAddrField( const QCString & aName ) const {
02223   return KMMessage::splitAddrField( rawHeaderField( aName ) );
02224 }
02225 
02226 AddrSpecList KMMessage::extractAddrSpecs( const QCString & header ) const {
02227   AddressList al = headerAddrField( header );
02228   AddrSpecList result;
02229   for ( AddressList::const_iterator ait = al.begin() ; ait != al.end() ; ++ait )
02230     for ( MailboxList::const_iterator mit = (*ait).mailboxList.begin() ; mit != (*ait).mailboxList.end() ; ++mit )
02231       result.push_back( (*mit).addrSpec );
02232   return result;
02233 }
02234 
02235 QCString KMMessage::rawHeaderField( const QCString & name ) const {
02236   if ( name.isEmpty() ) return QCString();
02237 
02238   DwHeaders & header = mMsg->Headers();
02239   DwField * field = header.FindField( name );
02240 
02241   if ( !field ) return QCString();
02242 
02243   return header.FieldBody( name.data() ).AsString().c_str();
02244 }
02245 
02246 QValueList<QCString> KMMessage::rawHeaderFields( const QCString& field ) const
02247 {
02248   if ( field.isEmpty() || !mMsg->Headers().FindField( field ) )
02249     return QValueList<QCString>();
02250 
02251   std::vector<DwFieldBody*> v = mMsg->Headers().AllFieldBodies( field.data() );
02252   QValueList<QCString> headerFields;
02253   for ( uint i = 0; i < v.size(); ++i ) {
02254     headerFields.append( v[i]->AsString().c_str() );
02255   }
02256 
02257   return headerFields;
02258 }
02259 
02260 QString KMMessage::headerField(const QCString& aName) const
02261 {
02262   if ( aName.isEmpty() )
02263     return QString::null;
02264 
02265   if ( !mMsg->Headers().FindField( aName ) )
02266     return QString::null;
02267 
02268   return decodeRFC2047String( mMsg->Headers().FieldBody( aName.data() ).AsString().c_str(),
02269                               charset() );
02270 
02271 }
02272 
02273 QStringList KMMessage::headerFields( const QCString& field ) const
02274 {
02275   if ( field.isEmpty() || !mMsg->Headers().FindField( field ) )
02276     return QStringList();
02277 
02278   std::vector<DwFieldBody*> v = mMsg->Headers().AllFieldBodies( field.data() );
02279   QStringList headerFields;
02280   for ( uint i = 0; i < v.size(); ++i ) {
02281     headerFields.append( decodeRFC2047String( v[i]->AsString().c_str(), charset() ) );
02282   }
02283 
02284   return headerFields;
02285 }
02286 
02287 //-----------------------------------------------------------------------------
02288 void KMMessage::removeHeaderField(const QCString& aName)
02289 {
02290   DwHeaders & header = mMsg->Headers();
02291   DwField * field = header.FindField(aName);
02292   if (!field) return;
02293 
02294   header.RemoveField(field);
02295   mNeedsAssembly = true;
02296 }
02297 
02298 //-----------------------------------------------------------------------------
02299 void KMMessage::removeHeaderFields(const QCString& aName)
02300 {
02301   DwHeaders & header = mMsg->Headers();
02302   while ( DwField * field = header.FindField(aName) ) {
02303     header.RemoveField(field);
02304     mNeedsAssembly = true;
02305   }
02306 }
02307 
02308 
02309 //-----------------------------------------------------------------------------
02310 void KMMessage::setHeaderField( const QCString& aName, const QString& bValue,
02311                                 HeaderFieldType type, bool prepend )
02312 {
02313 #if 0
02314   if ( type != Unstructured )
02315     kdDebug(5006) << "KMMessage::setHeaderField( \"" << aName << "\", \""
02316                 << bValue << "\", " << type << " )" << endl;
02317 #endif
02318   if (aName.isEmpty()) return;
02319 
02320   DwHeaders& header = mMsg->Headers();
02321 
02322   DwString str;
02323   DwField* field;
02324   QCString aValue;
02325   if (!bValue.isEmpty())
02326   {
02327     QString value = bValue;
02328     if ( type == Address )
02329       value = KPIM::normalizeAddressesAndEncodeIDNs( value );
02330 #if 0
02331     if ( type != Unstructured )
02332       kdDebug(5006) << "value: \"" << value << "\"" << endl;
02333 #endif
02334     QCString encoding = autoDetectCharset( charset(), sPrefCharsets, value );
02335     if (encoding.isEmpty())
02336        encoding = "utf-8";
02337     aValue = encodeRFC2047String( value, encoding );
02338 #if 0
02339     if ( type != Unstructured )
02340       kdDebug(5006) << "aValue: \"" << aValue << "\"" << endl;
02341 #endif
02342   }
02343   str = aName;
02344   if (str[str.length()-1] != ':') str += ": ";
02345   else str += ' ';
02346   if ( !aValue.isEmpty() )
02347     str += aValue;
02348   if (str[str.length()-1] != '\n') str += '\n';
02349 
02350   field = new DwField(str, mMsg);
02351   field->Parse();
02352 
02353   if ( prepend )
02354     header.AddFieldAt( 1, field );
02355   else
02356     header.AddOrReplaceField( field );
02357   mNeedsAssembly = true;
02358 }
02359 
02360 
02361 //-----------------------------------------------------------------------------
02362 QCString KMMessage::typeStr() const
02363 {
02364   DwHeaders& header = mMsg->Headers();
02365   if (header.HasContentType()) return header.ContentType().TypeStr().c_str();
02366   else return "";
02367 }
02368 
02369 
02370 //-----------------------------------------------------------------------------
02371 int KMMessage::type() const
02372 {
02373   DwHeaders& header = mMsg->Headers();
02374   if (header.HasContentType()) return header.ContentType().Type();
02375   else return DwMime::kTypeNull;
02376 }
02377 
02378 
02379 //-----------------------------------------------------------------------------
02380 void KMMessage::setTypeStr(const QCString& aStr)
02381 {
02382   dwContentType().SetTypeStr(DwString(aStr));
02383   dwContentType().Parse();
02384   mNeedsAssembly = true;
02385 }
02386 
02387 
02388 //-----------------------------------------------------------------------------
02389 void KMMessage::setType(int aType)
02390 {
02391   dwContentType().SetType(aType);
02392   dwContentType().Assemble();
02393   mNeedsAssembly = true;
02394 }
02395 
02396 
02397 
02398 //-----------------------------------------------------------------------------
02399 QCString KMMessage::subtypeStr() const
02400 {
02401   DwHeaders& header = mMsg->Headers();
02402   if (header.HasContentType()) return header.ContentType().SubtypeStr().c_str();
02403   else return "";
02404 }
02405 
02406 
02407 //-----------------------------------------------------------------------------
02408 int KMMessage::subtype() const
02409 {
02410   DwHeaders& header = mMsg->Headers();
02411   if (header.HasContentType()) return header.ContentType().Subtype();
02412   else return DwMime::kSubtypeNull;
02413 }
02414 
02415 
02416 //-----------------------------------------------------------------------------
02417 void KMMessage::setSubtypeStr(const QCString& aStr)
02418 {
02419   dwContentType().SetSubtypeStr(DwString(aStr));
02420   dwContentType().Parse();
02421   mNeedsAssembly = true;
02422 }
02423 
02424 
02425 //-----------------------------------------------------------------------------
02426 void KMMessage::setSubtype(int aSubtype)
02427 {
02428   dwContentType().SetSubtype(aSubtype);
02429   dwContentType().Assemble();
02430   mNeedsAssembly = true;
02431 }
02432 
02433 
02434 //-----------------------------------------------------------------------------
02435 void KMMessage::setDwMediaTypeParam( DwMediaType &mType,
02436                                      const QCString& attr,
02437                                      const QCString& val )
02438 {
02439   mType.Parse();
02440   DwParameter *param = mType.FirstParameter();
02441   while(param) {
02442     if (!kasciistricmp(param->Attribute().c_str(), attr))
02443       break;
02444     else
02445       param = param->Next();
02446   }
02447   if (!param){
02448     param = new DwParameter;
02449     param->SetAttribute(DwString( attr ));
02450     mType.AddParameter( param );
02451   }
02452   else
02453     mType.SetModified();
02454   param->SetValue(DwString( val ));
02455   mType.Assemble();
02456 }
02457 
02458 
02459 //-----------------------------------------------------------------------------
02460 void KMMessage::setContentTypeParam(const QCString& attr, const QCString& val)
02461 {
02462   if (mNeedsAssembly) mMsg->Assemble();
02463   mNeedsAssembly = false;
02464   setDwMediaTypeParam( dwContentType(), attr, val );
02465   mNeedsAssembly = true;
02466 }
02467 
02468 
02469 //-----------------------------------------------------------------------------
02470 QCString KMMessage::contentTransferEncodingStr() const
02471 {
02472   DwHeaders& header = mMsg->Headers();
02473   if (header.HasContentTransferEncoding())
02474     return header.ContentTransferEncoding().AsString().c_str();
02475   else return "";
02476 }
02477 
02478 
02479 //-----------------------------------------------------------------------------
02480 int KMMessage::contentTransferEncoding() const
02481 {
02482   DwHeaders& header = mMsg->Headers();
02483   if (header.HasContentTransferEncoding())
02484     return header.ContentTransferEncoding().AsEnum();
02485   else return DwMime::kCteNull;
02486 }
02487 
02488 
02489 //-----------------------------------------------------------------------------
02490 void KMMessage::setContentTransferEncodingStr(const QCString& aStr)
02491 {
02492   mMsg->Headers().ContentTransferEncoding().FromString(aStr);
02493   mMsg->Headers().ContentTransferEncoding().Parse();
02494   mNeedsAssembly = true;
02495 }
02496 
02497 
02498 //-----------------------------------------------------------------------------
02499 void KMMessage::setContentTransferEncoding(int aCte)
02500 {
02501   mMsg->Headers().ContentTransferEncoding().FromEnum(aCte);
02502   mNeedsAssembly = true;
02503 }
02504 
02505 
02506 //-----------------------------------------------------------------------------
02507 DwHeaders& KMMessage::headers() const
02508 {
02509   return mMsg->Headers();
02510 }
02511 
02512 
02513 //-----------------------------------------------------------------------------
02514 void KMMessage::setNeedsAssembly()
02515 {
02516   mNeedsAssembly = true;
02517 }
02518 
02519 
02520 //-----------------------------------------------------------------------------
02521 QCString KMMessage::body() const
02522 {
02523   const DwString& body = mMsg->Body().AsString();
02524   QCString str = KMail::Util::CString( body );
02525   // Calls length() -> slow
02526   //kdWarning( str.length() != body.length(), 5006 )
02527   //  << "KMMessage::body(): body is binary but used as text!" << endl;
02528   return str;
02529 }
02530 
02531 
02532 //-----------------------------------------------------------------------------
02533 QByteArray KMMessage::bodyDecodedBinary() const
02534 {
02535   DwString dwstr;
02536   const DwString& dwsrc = mMsg->Body().AsString();
02537 
02538   switch (cte())
02539   {
02540   case DwMime::kCteBase64:
02541     DwDecodeBase64(dwsrc, dwstr);
02542     break;
02543   case DwMime::kCteQuotedPrintable:
02544     DwDecodeQuotedPrintable(dwsrc, dwstr);
02545     break;
02546   default:
02547     dwstr = dwsrc;
02548     break;
02549   }
02550 
02551   int len = dwstr.size();
02552   QByteArray ba(len);
02553   memcpy(ba.data(),dwstr.data(),len);
02554   return ba;
02555 }
02556 
02557 
02558 //-----------------------------------------------------------------------------
02559 QCString KMMessage::bodyDecoded() const
02560 {
02561   DwString dwstr;
02562   DwString dwsrc = mMsg->Body().AsString();
02563 
02564   switch (cte())
02565   {
02566   case DwMime::kCteBase64:
02567     DwDecodeBase64(dwsrc, dwstr);
02568     break;
02569   case DwMime::kCteQuotedPrintable:
02570     DwDecodeQuotedPrintable(dwsrc, dwstr);
02571     break;
02572   default:
02573     dwstr = dwsrc;
02574     break;
02575   }
02576 
02577   return KMail::Util::CString( dwstr );
02578 
02579   // Calling QCString::length() is slow
02580   //QCString result = KMail::Util::CString( dwstr );
02581   //kdWarning(result.length() != len, 5006)
02582   //  << "KMMessage::bodyDecoded(): body is binary but used as text!" << endl;
02583   //return result;
02584 }
02585 
02586 
02587 //-----------------------------------------------------------------------------
02588 QValueList<int> KMMessage::determineAllowedCtes( const CharFreq& cf,
02589                                                  bool allow8Bit,
02590                                                  bool willBeSigned )
02591 {
02592   QValueList<int> allowedCtes;
02593 
02594   switch ( cf.type() ) {
02595   case CharFreq::SevenBitText:
02596     allowedCtes << DwMime::kCte7bit;
02597   case CharFreq::EightBitText:
02598     if ( allow8Bit )
02599       allowedCtes << DwMime::kCte8bit;
02600   case CharFreq::SevenBitData:
02601     if ( cf.printableRatio() > 5.0/6.0 ) {
02602       // let n the length of data and p the number of printable chars.
02603       // Then base64 \approx 4n/3; qp \approx p + 3(n-p)
02604       // => qp < base64 iff p > 5n/6.
02605       allowedCtes << DwMime::kCteQp;
02606       allowedCtes << DwMime::kCteBase64;
02607     } else {
02608       allowedCtes << DwMime::kCteBase64;
02609       allowedCtes << DwMime::kCteQp;
02610     }
02611     break;
02612   case CharFreq::EightBitData:
02613     allowedCtes << DwMime::kCteBase64;
02614     break;
02615   case CharFreq::None:
02616   default:
02617     // just nothing (avoid compiler warning)
02618     ;
02619   }
02620 
02621   // In the following cases only QP and Base64 are allowed:
02622   // - the buffer will be OpenPGP/MIME signed and it contains trailing
02623   //   whitespace (cf. RFC 3156)
02624   // - a line starts with "From "
02625   if ( ( willBeSigned && cf.hasTrailingWhitespace() ) ||
02626        cf.hasLeadingFrom() ) {
02627     allowedCtes.remove( DwMime::kCte8bit );
02628     allowedCtes.remove( DwMime::kCte7bit );
02629   }
02630 
02631   return allowedCtes;
02632 }
02633 
02634 
02635 //-----------------------------------------------------------------------------
02636 void KMMessage::setBodyAndGuessCte( const QByteArray& aBuf,
02637                                     QValueList<int> & allowedCte,
02638                                     bool allow8Bit,
02639                                     bool willBeSigned )
02640 {
02641   CharFreq cf( aBuf ); // it's safe to pass null arrays
02642 
02643   allowedCte = determineAllowedCtes( cf, allow8Bit, willBeSigned );
02644 
02645 #ifndef NDEBUG
02646   DwString dwCte;
02647   DwCteEnumToStr(allowedCte[0], dwCte);
02648   kdDebug(5006) << "CharFreq returned " << cf.type() << "/"
02649                 << cf.printableRatio() << " and I chose "
02650                 << dwCte.c_str() << endl;
02651 #endif
02652 
02653   setCte( allowedCte[0] ); // choose best fitting
02654   setBodyEncodedBinary( aBuf );
02655 }
02656 
02657 
02658 //-----------------------------------------------------------------------------
02659 void KMMessage::setBodyAndGuessCte( const QCString& aBuf,
02660                                     QValueList<int> & allowedCte,
02661                                     bool allow8Bit,
02662                                     bool willBeSigned )
02663 {
02664   CharFreq cf( aBuf.data(), aBuf.size()-1 ); // it's safe to pass null strings
02665 
02666   allowedCte = determineAllowedCtes( cf, allow8Bit, willBeSigned );
02667 
02668 #ifndef NDEBUG
02669   DwString dwCte;
02670   DwCteEnumToStr(allowedCte[0], dwCte);
02671   kdDebug(5006) << "CharFreq returned " << cf.type() << "/"
02672                 << cf.printableRatio() << " and I chose "
02673                 << dwCte.c_str() << endl;
02674 #endif
02675 
02676   setCte( allowedCte[0] ); // choose best fitting
02677   setBodyEncoded( aBuf );
02678 }
02679 
02680 
02681 //-----------------------------------------------------------------------------
02682 void KMMessage::setBodyEncoded(const QCString& aStr)
02683 {
02684   DwString dwSrc(aStr.data(), aStr.size()-1 /* not the trailing NUL */);
02685   DwString dwResult;
02686 
02687   switch (cte())
02688   {
02689   case DwMime::kCteBase64:
02690     DwEncodeBase64(dwSrc, dwResult);
02691     break;
02692   case DwMime::kCteQuotedPrintable:
02693     DwEncodeQuotedPrintable(dwSrc, dwResult);
02694     break;
02695   default:
02696     dwResult = dwSrc;
02697     break;
02698   }
02699 
02700   mMsg->Body().FromString(dwResult);
02701   mNeedsAssembly = true;
02702 }
02703 
02704 //-----------------------------------------------------------------------------
02705 void KMMessage::setBodyEncodedBinary(const QByteArray& aStr)
02706 {
02707   DwString dwSrc(aStr.data(), aStr.size());
02708   DwString dwResult;
02709 
02710   switch (cte())
02711   {
02712   case DwMime::kCteBase64:
02713     DwEncodeBase64(dwSrc, dwResult);
02714     break;
02715   case DwMime::kCteQuotedPrintable:
02716     DwEncodeQuotedPrintable(dwSrc, dwResult);
02717     break;
02718   default:
02719     dwResult = dwSrc;
02720     break;
02721   }
02722 
02723   mMsg->Body().FromString(dwResult);
02724   mNeedsAssembly = true;
02725 }
02726 
02727 
02728 //-----------------------------------------------------------------------------
02729 void KMMessage::setBody(const QCString& aStr)
02730 {
02731   mMsg->Body().FromString(KMail::Util::dwString(aStr));
02732   mNeedsAssembly = true;
02733 }
02734 void KMMessage::setBody(const DwString& aStr)
02735 {
02736   mMsg->Body().FromString(aStr);
02737   mNeedsAssembly = true;
02738 }
02739 void KMMessage::setBody(const char* aStr)
02740 {
02741   mMsg->Body().FromString(aStr);
02742   mNeedsAssembly = true;
02743 }
02744 
02745 void KMMessage::setMultiPartBody( const QCString & aStr ) {
02746   setBody( aStr );
02747   mMsg->Body().Parse();
02748   mNeedsAssembly = true;
02749 }
02750 
02751 
02752 // Patched by Daniel Moisset <dmoisset@grulic.org.ar>
02753 // modified numbodyparts, bodypart to take nested body parts as
02754 // a linear sequence.
02755 // third revision, Sep 26 2000
02756 
02757 // this is support structure for traversing tree without recursion
02758 
02759 //-----------------------------------------------------------------------------
02760 int KMMessage::numBodyParts() const
02761 {
02762   int count = 0;
02763   DwBodyPart* part = getFirstDwBodyPart();
02764   QPtrList< DwBodyPart > parts;
02765 
02766   while (part)
02767   {
02768     //dive into multipart messages
02769     while (    part
02770             && part->hasHeaders()
02771             && part->Headers().HasContentType()
02772             && part->Body().FirstBodyPart()
02773             && (DwMime::kTypeMultipart == part->Headers().ContentType().Type()) )
02774     {
02775       parts.append( part );
02776       part = part->Body().FirstBodyPart();
02777     }
02778     // this is where currPart->msgPart contains a leaf message part
02779     count++;
02780     // go up in the tree until reaching a node with next
02781     // (or the last top-level node)
02782     while (part && !(part->Next()) && !(parts.isEmpty()))
02783     {
02784       part = parts.getLast();
02785       parts.removeLast();
02786     }
02787 
02788     if (part && part->Body().Message() &&
02789         part->Body().Message()->Body().FirstBodyPart())
02790     {
02791       part = part->Body().Message()->Body().FirstBodyPart();
02792     } else if (part) {
02793       part = part->Next();
02794     }
02795   }
02796 
02797   return count;
02798 }
02799 
02800 
02801 //-----------------------------------------------------------------------------
02802 DwBodyPart * KMMessage::getFirstDwBodyPart() const
02803 {
02804   return mMsg->Body().FirstBodyPart();
02805 }
02806 
02807 
02808 //-----------------------------------------------------------------------------
02809 int KMMessage::partNumber( DwBodyPart * aDwBodyPart ) const
02810 {
02811   DwBodyPart *curpart;
02812   QPtrList< DwBodyPart > parts;
02813   int curIdx = 0;
02814   int idx = 0;
02815   // Get the DwBodyPart for this index
02816 
02817   curpart = getFirstDwBodyPart();
02818 
02819   while (curpart && !idx) {
02820     //dive into multipart messages
02821     while(    curpart
02822            && curpart->hasHeaders()
02823            && curpart->Headers().HasContentType()
02824            && curpart->Body().FirstBodyPart()
02825            && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) )
02826     {
02827       parts.append( curpart );
02828       curpart = curpart->Body().FirstBodyPart();
02829     }
02830     // this is where currPart->msgPart contains a leaf message part
02831     if (curpart == aDwBodyPart)
02832       idx = curIdx;
02833     curIdx++;
02834     // go up in the tree until reaching a node with next
02835     // (or the last top-level node)
02836     while (curpart && !(curpart->Next()) && !(parts.isEmpty()))
02837     {
02838       curpart = parts.getLast();
02839       parts.removeLast();
02840     } ;
02841     if (curpart)
02842       curpart = curpart->Next();
02843   }
02844   return idx;
02845 }
02846 
02847 
02848 //-----------------------------------------------------------------------------
02849 DwBodyPart * KMMessage::dwBodyPart( int aIdx ) const
02850 {
02851   DwBodyPart *part, *curpart;
02852   QPtrList< DwBodyPart > parts;
02853   int curIdx = 0;
02854   // Get the DwBodyPart for this index
02855 
02856   curpart = getFirstDwBodyPart();
02857   part = 0;
02858 
02859   while (curpart && !part) {
02860     //dive into multipart messages
02861     while(    curpart
02862            && curpart->hasHeaders()
02863            && curpart->Headers().HasContentType()
02864            && curpart->Body().FirstBodyPart()
02865            && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) )
02866     {
02867       parts.append( curpart );
02868       curpart = curpart->Body().FirstBodyPart();
02869     }
02870     // this is where currPart->msgPart contains a leaf message part
02871     if (curIdx==aIdx)
02872         part = curpart;
02873     curIdx++;
02874     // go up in the tree until reaching a node with next
02875     // (or the last top-level node)
02876     while (curpart && !(curpart->Next()) && !(parts.isEmpty()))
02877     {
02878       curpart = parts.getLast();
02879       parts.removeLast();
02880     }
02881     if (curpart)
02882       curpart = curpart->Next();
02883   }
02884   return part;
02885 }
02886 
02887 
02888 //-----------------------------------------------------------------------------
02889 DwBodyPart * KMMessage::findDwBodyPart( int type, int subtype ) const
02890 {
02891   DwBodyPart *part, *curpart;
02892   QPtrList< DwBodyPart > parts;
02893   // Get the DwBodyPart for this index
02894 
02895   curpart = getFirstDwBodyPart();
02896   part = 0;
02897 
02898   while (curpart && !part) {
02899     //dive into multipart messages
02900     while(curpart
02901       && curpart->hasHeaders()
02902       && curpart->Headers().HasContentType()
02903       && curpart->Body().FirstBodyPart()
02904       && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) ) {
02905     parts.append( curpart );
02906     curpart = curpart->Body().FirstBodyPart();
02907     }
02908     // this is where curPart->msgPart contains a leaf message part
02909 
02910     // pending(khz): Find out WHY this look does not travel down *into* an
02911     //               embedded "Message/RfF822" message containing a "Multipart/Mixed"
02912     if ( curpart && curpart->hasHeaders() && curpart->Headers().HasContentType() ) {
02913       kdDebug(5006) << curpart->Headers().ContentType().TypeStr().c_str()
02914         << "  " << curpart->Headers().ContentType().SubtypeStr().c_str() << endl;
02915     }
02916 
02917     if (curpart &&
02918     curpart->hasHeaders() &&
02919         curpart->Headers().HasContentType() &&
02920     curpart->Headers().ContentType().Type() == type &&
02921     curpart->Headers().ContentType().Subtype() == subtype) {
02922     part = curpart;
02923     } else {
02924       // go up in the tree until reaching a node with next
02925       // (or the last top-level node)
02926       while (curpart && !(curpart->Next()) && !(parts.isEmpty())) {
02927     curpart = parts.getLast();
02928     parts.removeLast();
02929       } ;
02930       if (curpart)
02931     curpart = curpart->Next();
02932     }
02933   }
02934   return part;
02935 }
02936 
02937 //-----------------------------------------------------------------------------
02938 DwBodyPart * KMMessage::findDwBodyPart( const QCString& type, const QCString&  subtype ) const
02939 {
02940   DwBodyPart *part, *curpart;
02941   QPtrList< DwBodyPart > parts;
02942   // Get the DwBodyPart for this index
02943 
02944   curpart = getFirstDwBodyPart();
02945   part = 0;
02946 
02947   while (curpart && !part) {
02948     //dive into multipart messages
02949     while(curpart
02950       && curpart->hasHeaders()
02951       && curpart->Headers().HasContentType()
02952       && curpart->Body().FirstBodyPart()
02953       && (DwMime::kTypeMultipart == curpart->Headers().ContentType().Type()) ) {
02954     parts.append( curpart );
02955     curpart = curpart->Body().FirstBodyPart();
02956     }
02957     // this is where curPart->msgPart contains a leaf message part
02958 
02959     // pending(khz): Find out WHY this look does not travel down *into* an
02960     //               embedded "Message/RfF822" message containing a "Multipart/Mixed"
02961     if (curpart && curpart->hasHeaders() && curpart->Headers().HasContentType() ) {
02962       kdDebug(5006) << curpart->Headers().ContentType().TypeStr().c_str()
02963             << "  " << curpart->Headers().ContentType().SubtypeStr().c_str() << endl;
02964     }
02965 
02966     if (curpart &&
02967     curpart->hasHeaders() &&
02968         curpart->Headers().HasContentType() &&
02969     curpart->Headers().ContentType().TypeStr().c_str() == type &&
02970     curpart->Headers().ContentType().SubtypeStr().c_str() == subtype) {
02971     part = curpart;
02972     } else {
02973       // go up in the tree until reaching a node with next
02974       // (or the last top-level node)
02975       while (curpart && !(curpart->Next()) && !(parts.isEmpty())) {
02976     curpart = parts.getLast();
02977     parts.removeLast();
02978       } ;
02979       if (curpart)
02980     curpart = curpart->Next();
02981     }
02982   }
02983   return part;
02984 }
02985 
02986 
02987 void applyHeadersToMessagePart( DwHeaders& headers, KMMessagePart* aPart )
02988 {
02989   // TODO: Instead of manually implementing RFC2231 header encoding (i.e.
02990   //       possibly multiple values given as paramname*0=..; parmaname*1=..;...
02991   //       or par as paramname*0*=..; parmaname*1*=..;..., which should be
02992   //       concatenated), use a generic method to decode the header, using RFC
02993   //       2047 or 2231, or whatever future RFC might be appropriate!
02994   //       Right now, some fields are decoded, while others are not. E.g.
02995   //       Content-Disposition is not decoded here, rather only on demand in
02996   //       KMMsgPart::fileName; Name however is decoded here and stored as a
02997   //       decoded String in KMMsgPart...
02998   // Content-type
02999   QCString additionalCTypeParams;
03000   if (headers.HasContentType())
03001   {
03002     DwMediaType& ct = headers.ContentType();
03003     aPart->setOriginalContentTypeStr( ct.AsString().c_str() );
03004     aPart->setTypeStr(ct.TypeStr().c_str());
03005     aPart->setSubtypeStr(ct.SubtypeStr().c_str());
03006     DwParameter *param = ct.FirstParameter();
03007     while(param)
03008     {
03009       if (!qstricmp(param->Attribute().c_str(), "charset"))
03010         aPart->setCharset(QCString(param->Value().c_str()).lower());
03011       else if (!qstrnicmp(param->Attribute().c_str(), "name*", 5))
03012         aPart->setName(KMMsgBase::decodeRFC2231String(KMMsgBase::extractRFC2231HeaderField( param->Value().c_str(), "name" )));
03013       else {
03014         additionalCTypeParams += ';';
03015         additionalCTypeParams += param->AsString().c_str();
03016       }
03017       param=param->Next();
03018     }
03019   }
03020   else
03021   {
03022     aPart->setTypeStr("text");      // Set to defaults
03023     aPart->setSubtypeStr("plain");
03024   }
03025   aPart->setAdditionalCTypeParamStr( additionalCTypeParams );
03026   // Modification by Markus
03027   if (aPart->name().isEmpty())
03028   {
03029     if (headers.HasContentType() && !headers.ContentType().Name().empty()) {
03030       aPart->setName(KMMsgBase::decodeRFC2047String(headers.
03031             ContentType().Name().c_str()) );
03032     } else if (headers.HasSubject() && !headers.Subject().AsString().empty()) {
03033       aPart->setName( KMMsgBase::decodeRFC2047String(headers.
03034             Subject().AsString().c_str()) );
03035     }
03036   }
03037 
03038   // Content-transfer-encoding
03039   if (headers.HasContentTransferEncoding())
03040     aPart->setCteStr(headers.ContentTransferEncoding().AsString().c_str());
03041   else
03042     aPart->setCteStr("7bit");
03043 
03044   // Content-description
03045   if (headers.HasContentDescription())
03046     aPart->setContentDescription(headers.ContentDescription().AsString().c_str());
03047   else
03048     aPart->setContentDescription("");
03049 
03050   // Content-disposition
03051   if (headers.HasContentDisposition())
03052     aPart->setContentDisposition(headers.ContentDisposition().AsString().c_str());
03053   else
03054     aPart->setContentDisposition("");
03055 }
03056 
03057 //-----------------------------------------------------------------------------
03058 void KMMessage::bodyPart(DwBodyPart* aDwBodyPart, KMMessagePart* aPart,
03059              bool withBody)
03060 {
03061   if ( !aPart )
03062     return;
03063 
03064   aPart->clear();
03065 
03066   if( aDwBodyPart && aDwBodyPart->hasHeaders()  ) {
03067     // This must not be an empty string, because we'll get a
03068     // spurious empty Subject: line in some of the parts.
03069     //aPart->setName(" ");
03070     // partSpecifier
03071     QString partId( aDwBodyPart->partId() );
03072     aPart->setPartSpecifier( partId );
03073 
03074     DwHeaders& headers = aDwBodyPart->Headers();
03075     applyHeadersToMessagePart( headers, aPart );
03076 
03077     // Body
03078     if (withBody)
03079       aPart->setBody( aDwBodyPart->Body().AsString() );
03080     else
03081       aPart->setBody( QCString("") );
03082 
03083     // Content-id
03084     if ( headers.HasContentId() ) {
03085       const QCString contentId = headers.ContentId().AsString().c_str();
03086       // ignore leading '<' and trailing '>'
03087       aPart->setContentId( contentId.mid( 1, contentId.length() - 2 ) );
03088     }
03089   }
03090   // If no valid body part was given,
03091   // set all MultipartBodyPart attributes to empty values.
03092   else
03093   {
03094     aPart->setTypeStr("");
03095     aPart->setSubtypeStr("");
03096     aPart->setCteStr("");
03097     // This must not be an empty string, because we'll get a
03098     // spurious empty Subject: line in some of the parts.
03099     //aPart->setName(" ");
03100     aPart->setContentDescription("");
03101     aPart->setContentDisposition("");
03102     aPart->setBody(QCString(""));
03103     aPart->setContentId("");
03104   }
03105 }
03106 
03107 
03108 //-----------------------------------------------------------------------------
03109 void KMMessage::bodyPart(int aIdx, KMMessagePart* aPart) const
03110 {
03111   if ( !aPart )
03112     return;
03113 
03114   // If the DwBodyPart was found get the header fields and body
03115   if ( DwBodyPart *part = dwBodyPart( aIdx ) ) {
03116     KMMessage::bodyPart(part, aPart);
03117     if( aPart->name().isEmpty() )
03118       aPart->setName( i18n("Attachment: %1").arg( aIdx ) );
03119   }
03120 }
03121 
03122 
03123 //-----------------------------------------------------------------------------
03124 void KMMessage::deleteBodyParts()
03125 {
03126   mMsg->Body().DeleteBodyParts();
03127 }
03128 
03129 void KMMessage::removeBodyPart(DwBodyPart * dwPart)
03130 {
03131   mMsg->Body().RemoveBodyPart( dwPart );
03132   mNeedsAssembly = true;
03133 }
03134 
03135 //-----------------------------------------------------------------------------
03136 DwBodyPart* KMMessage::createDWBodyPart(const KMMessagePart* aPart)
03137 {
03138   DwBodyPart* part = DwBodyPart::NewBodyPart(emptyString, 0);
03139 
03140   if ( !aPart )
03141     return part;
03142 
03143   QCString charset  = aPart->charset();
03144   QCString type     = aPart->typeStr();
03145   QCString subtype  = aPart->subtypeStr();
03146   QCString cte      = aPart->cteStr();
03147   QCString contDesc = aPart->contentDescriptionEncoded();
03148   QCString contDisp = aPart->contentDisposition();
03149   QCString encoding = autoDetectCharset(charset, sPrefCharsets, aPart->name());
03150   if (encoding.isEmpty()) encoding = "utf-8";
03151   QCString name     = KMMsgBase::encodeRFC2231String(aPart->name(), encoding);
03152   bool RFC2231encoded = aPart->name() != QString(name);
03153   QCString paramAttr  = aPart->parameterAttribute();
03154 
03155   DwHeaders& headers = part->Headers();
03156 
03157   DwMediaType& ct = headers.ContentType();
03158   if (!type.isEmpty() && !subtype.isEmpty())
03159   {
03160     ct.SetTypeStr(type.data());
03161     ct.SetSubtypeStr(subtype.data());
03162     if (!charset.isEmpty()){
03163       DwParameter *param;
03164       param=new DwParameter;
03165       param->SetAttribute("charset");
03166       param->SetValue(charset.data());
03167       ct.AddParameter(param);
03168     }
03169   }
03170 
03171   QCString additionalParam = aPart->additionalCTypeParamStr();
03172   if( !additionalParam.isEmpty() )
03173   {
03174     QCString parAV;
03175     DwString parA, parV;
03176     int iL, i1, i2, iM;
03177     iL = additionalParam.length();
03178     i1 = 0;
03179     i2 = additionalParam.find(';', i1, false);
03180     while ( i1 < iL )
03181     {
03182       if( -1 == i2 )
03183     i2 = iL;
03184       if( i1+1 < i2 ) {
03185     parAV = additionalParam.mid( i1, (i2-i1) );
03186     iM = parAV.find('=');
03187     if( -1 < iM )
03188         {
03189       parA = parAV.left( iM );
03190       parV = parAV.right( parAV.length() - iM - 1 );
03191       if( ('"' == parV.at(0)) && ('"' == parV.at(parV.length()-1)) )
03192           {
03193         parV.erase( 0,  1);
03194         parV.erase( parV.length()-1 );
03195       }
03196     }
03197     else
03198         {
03199       parA = parAV;
03200       parV = "";
03201     }
03202     DwParameter *param;
03203     param = new DwParameter;
03204     param->SetAttribute( parA );
03205     param->SetValue(     parV );
03206     ct.AddParameter( param );
03207       }
03208       i1 = i2+1;
03209       i2 = additionalParam.find(';', i1, false);
03210     }
03211   }
03212 
03213   if ( !name.isEmpty() ) {
03214     if (RFC2231encoded)
03215     {
03216       DwParameter *nameParam;
03217       nameParam = new DwParameter;
03218       nameParam->SetAttribute("name*");
03219       nameParam->SetValue(name.data(),true);
03220       ct.AddParameter(nameParam);
03221     } else {
03222       ct.SetName(name.data());
03223     }
03224   }
03225 
03226   if (!paramAttr.isEmpty())
03227   {
03228     QCString encoding = autoDetectCharset(charset, sPrefCharsets,
03229                       aPart->parameterValue());
03230     if (encoding.isEmpty()) encoding = "utf-8";
03231     QCString paramValue;
03232     paramValue = KMMsgBase::encodeRFC2231String(aPart->parameterValue(),
03233                         encoding);
03234     DwParameter *param = new DwParameter;
03235     if (aPart->parameterValue() != QString(paramValue))
03236     {
03237       param->SetAttribute((paramAttr + '*').data());
03238       param->SetValue(paramValue.data(),true);
03239     } else {
03240       param->SetAttribute(paramAttr.data());
03241       param->SetValue(paramValue.data());
03242     }
03243     ct.AddParameter(param);
03244   }
03245 
03246   if (!cte.isEmpty())
03247     headers.Cte().FromString(cte);
03248 
03249   if (!contDesc.isEmpty())
03250     headers.ContentDescription().FromString(contDesc);
03251 
03252   if (!contDisp.isEmpty())
03253     headers.ContentDisposition().FromString(contDisp);
03254 
03255   const DwString bodyStr = aPart->dwBody();
03256   if (!bodyStr.empty())
03257     part->Body().FromString(bodyStr);
03258   else
03259     part->Body().FromString("");
03260 
03261   if (!aPart->partSpecifier().isNull())
03262     part->SetPartId( aPart->partSpecifier().latin1() );
03263 
03264   if (aPart->decodedSize() > 0)
03265     part->SetBodySize( aPart->decodedSize() );
03266 
03267   return part;
03268 }
03269 
03270 
03271 //-----------------------------------------------------------------------------
03272 void KMMessage::addDwBodyPart(DwBodyPart * aDwPart)
03273 {
03274   mMsg->Body().AddBodyPart( aDwPart );
03275   mNeedsAssembly = true;
03276 }
03277 
03278 
03279 //-----------------------------------------------------------------------------
03280 void KMMessage::addBodyPart(const KMMessagePart* aPart)
03281 {
03282   DwBodyPart* part = createDWBodyPart( aPart );
03283   addDwBodyPart( part );
03284 }
03285 
03286 
03287 //-----------------------------------------------------------------------------
03288 QString KMMessage::generateMessageId( const QString& addr )
03289 {
03290   QDateTime datetime = QDateTime::currentDateTime();
03291   QString msgIdStr;
03292 
03293   msgIdStr = '<' + datetime.toString( "yyyyMMddhhmm.sszzz" );
03294 
03295   QString msgIdSuffix;
03296   KConfigGroup general( KMKernel::config(), "General" );
03297 
03298   if( general.readBoolEntry( "useCustomMessageIdSuffix", false ) )
03299     msgIdSuffix = general.readEntry( "myMessageIdSuffix" );
03300 
03301   if( !msgIdSuffix.isEmpty() )
03302     msgIdStr += '@' + msgIdSuffix;
03303   else
03304     msgIdStr += '.' + KPIM::encodeIDN( addr );
03305 
03306   msgIdStr += '>';
03307 
03308   return msgIdStr;
03309 }
03310 
03311 
03312 //-----------------------------------------------------------------------------
03313 QCString KMMessage::html2source( const QCString & src )
03314 {
03315   QCString result( 1 + 6*(src.size()-1) );  // maximal possible length
03316 
03317   QCString::ConstIterator s = src.begin();
03318   QCString::Iterator d = result.begin();
03319   while ( *s ) {
03320     switch ( *s ) {
03321     case '<': {
03322         *d++ = '&';
03323         *d++ = 'l';
03324         *d++ = 't';
03325         *d++ = ';';
03326         ++s;
03327       }
03328       break;
03329     case '\r': {
03330         ++s;
03331       }
03332       break;
03333     case '\n': {
03334         *d++ = '<';
03335         *d++ = 'b';
03336         *d++ = 'r';
03337         *d++ = '>';
03338         ++s;
03339       }
03340       break;
03341     case '>': {
03342         *d++ = '&';
03343         *d++ = 'g';
03344         *d++ = 't';
03345         *d++ = ';';
03346         ++s;
03347       }
03348       break;
03349     case '&': {
03350         *d++ = '&';
03351         *d++ = 'a';
03352         *d++ = 'm';
03353         *d++ = 'p';
03354         *d++ = ';';
03355         ++s;
03356       }
03357       break;
03358     case '"': {
03359         *d++ = '&';
03360         *d++ = 'q';
03361         *d++ = 'u';
03362         *d++ = 'o';
03363         *d++ = 't';
03364         *d++ = ';';
03365         ++s;
03366       }
03367       break;
03368     case '\'': {
03369         *d++ = '&';
03370     *d++ = 'a';
03371     *d++ = 'p';
03372     *d++ = 's';
03373     *d++ = ';';
03374     ++s;
03375       }
03376       break;
03377     default:
03378         *d++ = *s++;
03379     }
03380   }
03381   result.truncate( d - result.begin() ); // adds trailing NUL
03382   return result;
03383 }
03384 
03385 //-----------------------------------------------------------------------------
03386 QString KMMessage::encodeMailtoUrl( const QString& str )
03387 {
03388   QString result;
03389   result = QString::fromLatin1( KMMsgBase::encodeRFC2047String( str,
03390                                                                 "utf-8" ) );
03391   result = KURL::encode_string( result );
03392   return result;
03393 }
03394 
03395 
03396 //-----------------------------------------------------------------------------
03397 QString KMMessage::decodeMailtoUrl( const QString& url )
03398 {
03399   QString result;
03400   result = KURL::decode_string( url );
03401   result = KMMsgBase::decodeRFC2047String( result.latin1() );
03402   return result;
03403 }
03404 
03405 
03406 //-----------------------------------------------------------------------------
03407 QCString KMMessage::stripEmailAddr( const QCString& aStr )
03408 {
03409   //kdDebug(5006) << "KMMessage::stripEmailAddr( " << aStr << " )" << endl;
03410 
03411   if ( aStr.isEmpty() )
03412     return QCString();
03413 
03414   QCString result;
03415 
03416   // The following is a primitive parser for a mailbox-list (cf. RFC 2822).
03417   // The purpose is to extract a displayable string from the mailboxes.
03418   // Comments in the addr-spec are not handled. No error checking is done.
03419 
03420   QCString name;
03421   QCString comment;
03422   QCString angleAddress;
03423   enum { TopLevel, InComment, InAngleAddress } context = TopLevel;
03424   bool inQuotedString = false;
03425   int commentLevel = 0;
03426 
03427   for ( char* p = aStr.data(); *p; ++p ) {
03428     switch ( context ) {
03429     case TopLevel : {
03430       switch ( *p ) {
03431       case '"' : inQuotedString = !inQuotedString;
03432                  break;
03433       case '(' : if ( !inQuotedString ) {
03434                    context = InComment;
03435                    commentLevel = 1;
03436                  }
03437                  else
03438                    name += *p;
03439                  break;
03440       case '<' : if ( !inQuotedString ) {
03441                    context = InAngleAddress;
03442                  }
03443                  else
03444                    name += *p;
03445                  break;
03446       case '\\' : // quoted character
03447                  ++p; // skip the '\'
03448                  if ( *p )
03449                    name += *p;
03450                  break;
03451       case ',' : if ( !inQuotedString ) {
03452                    // next email address
03453                    if ( !result.isEmpty() )
03454                      result += ", ";
03455                    name = name.stripWhiteSpace();
03456                    comment = comment.stripWhiteSpace();
03457                    angleAddress = angleAddress.stripWhiteSpace();
03458                    /*
03459                    kdDebug(5006) << "Name    : \"" << name
03460                                  << "\"" << endl;
03461                    kdDebug(5006) << "Comment : \"" << comment
03462                                  << "\"" << endl;
03463                    kdDebug(5006) << "Address : \"" << angleAddress
03464                                  << "\"" << endl;
03465                    */
03466                    if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03467                      // handle Outlook-style addresses like
03468                      // john.doe@invalid (John Doe)
03469                      result += comment;
03470                    }
03471                    else if ( !name.isEmpty() ) {
03472                      result += name;
03473                    }
03474                    else if ( !comment.isEmpty() ) {
03475                      result += comment;
03476                    }
03477                    else if ( !angleAddress.isEmpty() ) {
03478                      result += angleAddress;
03479                    }
03480                    name = QCString();
03481                    comment = QCString();
03482                    angleAddress = QCString();
03483                  }
03484                  else
03485                    name += *p;
03486                  break;
03487       default :  name += *p;
03488       }
03489       break;
03490     }
03491     case InComment : {
03492       switch ( *p ) {
03493       case '(' : ++commentLevel;
03494                  comment += *p;
03495                  break;
03496       case ')' : --commentLevel;
03497                  if ( commentLevel == 0 ) {
03498                    context = TopLevel;
03499                    comment += ' '; // separate the text of several comments
03500                  }
03501                  else
03502                    comment += *p;
03503                  break;
03504       case '\\' : // quoted character
03505                  ++p; // skip the '\'
03506                  if ( *p )
03507                    comment += *p;
03508                  break;
03509       default :  comment += *p;
03510       }
03511       break;
03512     }
03513     case InAngleAddress : {
03514       switch ( *p ) {
03515       case '"' : inQuotedString = !inQuotedString;
03516                  angleAddress += *p;
03517                  break;
03518       case '>' : if ( !inQuotedString ) {
03519                    context = TopLevel;
03520                  }
03521                  else
03522                    angleAddress += *p;
03523                  break;
03524       case '\\' : // quoted character
03525                  ++p; // skip the '\'
03526                  if ( *p )
03527                    angleAddress += *p;
03528                  break;
03529       default :  angleAddress += *p;
03530       }
03531       break;
03532     }
03533     } // switch ( context )
03534   }
03535   if ( !result.isEmpty() )
03536     result += ", ";
03537   name = name.stripWhiteSpace();
03538   comment = comment.stripWhiteSpace();
03539   angleAddress = angleAddress.stripWhiteSpace();
03540   /*
03541   kdDebug(5006) << "Name    : \"" << name << "\"" << endl;
03542   kdDebug(5006) << "Comment : \"" << comment << "\"" << endl;
03543   kdDebug(5006) << "Address : \"" << angleAddress << "\"" << endl;
03544   */
03545   if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03546     // handle Outlook-style addresses like
03547     // john.doe@invalid (John Doe)
03548     result += comment;
03549   }
03550   else if ( !name.isEmpty() ) {
03551     result += name;
03552   }
03553   else if ( !comment.isEmpty() ) {
03554     result += comment;
03555   }
03556   else if ( !angleAddress.isEmpty() ) {
03557     result += angleAddress;
03558   }
03559 
03560   //kdDebug(5006) << "KMMessage::stripEmailAddr(...) returns \"" << result
03561   //              << "\"" << endl;
03562   return result;
03563 }
03564 
03565 //-----------------------------------------------------------------------------
03566 QString KMMessage::stripEmailAddr( const QString& aStr )
03567 {
03568   //kdDebug(5006) << "KMMessage::stripEmailAddr( " << aStr << " )" << endl;
03569 
03570   if ( aStr.isEmpty() )
03571     return QString::null;
03572 
03573   QString result;
03574 
03575   // The following is a primitive parser for a mailbox-list (cf. RFC 2822).
03576   // The purpose is to extract a displayable string from the mailboxes.
03577   // Comments in the addr-spec are not handled. No error checking is done.
03578 
03579   QString name;
03580   QString comment;
03581   QString angleAddress;
03582   enum { TopLevel, InComment, InAngleAddress } context = TopLevel;
03583   bool inQuotedString = false;
03584   int commentLevel = 0;
03585 
03586   QChar ch;
03587   unsigned int strLength(aStr.length());
03588   for ( uint index = 0; index < strLength; ++index ) {
03589     ch = aStr[index];
03590     switch ( context ) {
03591     case TopLevel : {
03592       switch ( ch.latin1() ) {
03593       case '"' : inQuotedString = !inQuotedString;
03594                  break;
03595       case '(' : if ( !inQuotedString ) {
03596                    context = InComment;
03597                    commentLevel = 1;
03598                  }
03599                  else
03600                    name += ch;
03601                  break;
03602       case '<' : if ( !inQuotedString ) {
03603                    context = InAngleAddress;
03604                  }
03605                  else
03606                    name += ch;
03607                  break;
03608       case '\\' : // quoted character
03609                  ++index; // skip the '\'
03610                  if ( index < aStr.length() )
03611                    name += aStr[index];
03612                  break;
03613       case ',' : if ( !inQuotedString ) {
03614                    // next email address
03615                    if ( !result.isEmpty() )
03616                      result += ", ";
03617                    name = name.stripWhiteSpace();
03618                    comment = comment.stripWhiteSpace();
03619                    angleAddress = angleAddress.stripWhiteSpace();
03620                    /*
03621                    kdDebug(5006) << "Name    : \"" << name
03622                                  << "\"" << endl;
03623                    kdDebug(5006) << "Comment : \"" << comment
03624                                  << "\"" << endl;
03625                    kdDebug(5006) << "Address : \"" << angleAddress
03626                                  << "\"" << endl;
03627                    */
03628                    if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03629                      // handle Outlook-style addresses like
03630                      // john.doe@invalid (John Doe)
03631                      result += comment;
03632                    }
03633                    else if ( !name.isEmpty() ) {
03634                      result += name;
03635                    }
03636                    else if ( !comment.isEmpty() ) {
03637                      result += comment;
03638                    }
03639                    else if ( !angleAddress.isEmpty() ) {
03640                      result += angleAddress;
03641                    }
03642                    name = QString::null;
03643                    comment = QString::null;
03644                    angleAddress = QString::null;
03645                  }
03646                  else
03647                    name += ch;
03648                  break;
03649       default :  name += ch;
03650       }
03651       break;
03652     }
03653     case InComment : {
03654       switch ( ch.latin1() ) {
03655       case '(' : ++commentLevel;
03656                  comment += ch;
03657                  break;
03658       case ')' : --commentLevel;
03659                  if ( commentLevel == 0 ) {
03660                    context = TopLevel;
03661                    comment += ' '; // separate the text of several comments
03662                  }
03663                  else
03664                    comment += ch;
03665                  break;
03666       case '\\' : // quoted character
03667                  ++index; // skip the '\'
03668                  if ( index < aStr.length() )
03669                    comment += aStr[index];
03670                  break;
03671       default :  comment += ch;
03672       }
03673       break;
03674     }
03675     case InAngleAddress : {
03676       switch ( ch.latin1() ) {
03677       case '"' : inQuotedString = !inQuotedString;
03678                  angleAddress += ch;
03679                  break;
03680       case '>' : if ( !inQuotedString ) {
03681                    context = TopLevel;
03682                  }
03683                  else
03684                    angleAddress += ch;
03685                  break;
03686       case '\\' : // quoted character
03687                  ++index; // skip the '\'
03688                  if ( index < aStr.length() )
03689                    angleAddress += aStr[index];
03690                  break;
03691       default :  angleAddress += ch;
03692       }
03693       break;
03694     }
03695     } // switch ( context )
03696   }
03697   if ( !result.isEmpty() )
03698     result += ", ";
03699   name = name.stripWhiteSpace();
03700   comment = comment.stripWhiteSpace();
03701   angleAddress = angleAddress.stripWhiteSpace();
03702   /*
03703   kdDebug(5006) << "Name    : \"" << name << "\"" << endl;
03704   kdDebug(5006) << "Comment : \"" << comment << "\"" << endl;
03705   kdDebug(5006) << "Address : \"" << angleAddress << "\"" << endl;
03706   */
03707   if ( angleAddress.isEmpty() && !comment.isEmpty() ) {
03708     // handle Outlook-style addresses like
03709     // john.doe@invalid (John Doe)
03710     result += comment;
03711   }
03712   else if ( !name.isEmpty() ) {
03713     result += name;
03714   }
03715   else if ( !comment.isEmpty() ) {
03716     result += comment;
03717   }
03718   else if ( !angleAddress.isEmpty() ) {
03719     result += angleAddress;
03720   }
03721 
03722   //kdDebug(5006) << "KMMessage::stripEmailAddr(...) returns \"" << result
03723   //              << "\"" << endl;
03724   return result;
03725 }
03726 
03727 //-----------------------------------------------------------------------------
03728 QString KMMessage::quoteHtmlChars( const QString& str, bool removeLineBreaks )
03729 {
03730   QString result;
03731 
03732   unsigned int strLength(str.length());
03733   result.reserve( 6*strLength ); // maximal possible length
03734   for( unsigned int i = 0; i < strLength; ++i )
03735     switch ( str[i].latin1() ) {
03736     case '<':
03737       result += "&lt;";
03738       break;
03739     case '>':
03740       result += "&gt;";
03741       break;
03742     case '&':
03743       result += "&amp;";
03744       break;
03745     case '"':
03746       result += "&quot;";
03747       break;
03748     case '\n':
03749       if ( !removeLineBreaks )
03750     result += "<br>";
03751       break;
03752     case '\r':
03753       // ignore CR
03754       break;
03755     default:
03756       result += str[i];
03757     }
03758 
03759   result.squeeze();
03760   return result;
03761 }
03762 
03763 //-----------------------------------------------------------------------------
03764 QString KMMessage::emailAddrAsAnchor(const QString& aEmail, bool stripped, const QString& cssStyle, bool aLink)
03765 {
03766   if( aEmail.isEmpty() )
03767     return aEmail;
03768 
03769   QStringList addressList = KPIM::splitEmailAddrList( aEmail );
03770 
03771   QString result;
03772 
03773   for( QStringList::ConstIterator it = addressList.begin();
03774        ( it != addressList.end() );
03775        ++it ) {
03776     if( !(*it).isEmpty() ) {
03777       QString address = *it;
03778       if(aLink) {
03779     result += "<a href=\"mailto:"
03780               + KMMessage::encodeMailtoUrl( address )
03781       + "\" "+cssStyle+">";
03782       }
03783       if( stripped )
03784         address = KMMessage::stripEmailAddr( address );
03785       result += KMMessage::quoteHtmlChars( address, true );
03786       if(aLink)
03787     result += "</a>, ";
03788     }
03789   }
03790   // cut of the trailing ", "
03791   if(aLink)
03792     result.truncate( result.length() - 2 );
03793 
03794   //kdDebug(5006) << "KMMessage::emailAddrAsAnchor('" << aEmail
03795   //              << "') returns:\n-->" << result << "<--" << endl;
03796   return result;
03797 }
03798 
03799 
03800 //-----------------------------------------------------------------------------
03801 //static
03802 QStringList KMMessage::stripAddressFromAddressList( const QString& address,
03803                                                     const QStringList& list )
03804 {
03805   QStringList addresses( list );
03806   QString addrSpec( KPIM::getEmailAddress( address ) );
03807   for ( QStringList::Iterator it = addresses.begin();
03808        it != addresses.end(); ) {
03809     if ( kasciistricmp( addrSpec.utf8().data(),
03810                         KPIM::getEmailAddress( *it ).utf8().data() ) == 0 ) {
03811       kdDebug(5006) << "Removing " << *it << " from the address list"
03812                     << endl;
03813       it = addresses.remove( it );
03814     }
03815     else
03816       ++it;
03817   }
03818   return addresses;
03819 }
03820 
03821 
03822 //-----------------------------------------------------------------------------
03823 //static
03824 QStringList KMMessage::stripMyAddressesFromAddressList( const QStringList& list )
03825 {
03826   QStringList addresses = list;
03827   for( QStringList::Iterator it = addresses.begin();
03828        it != addresses.end(); ) {
03829     kdDebug(5006) << "Check whether " << *it << " is one of my addresses"
03830                   << endl;
03831     if( kmkernel->identityManager()->thatIsMe( KPIM::getEmailAddress( *it ) ) ) {
03832       kdDebug(5006) << "Removing " << *it << " from the address list"
03833                     << endl;
03834       it = addresses.remove( it );
03835     }
03836     else
03837       ++it;
03838   }
03839   return addresses;
03840 }
03841 
03842 
03843 //-----------------------------------------------------------------------------
03844 //static
03845 bool KMMessage::addressIsInAddressList( const QString& address,
03846                                         const QStringList& addresses )
03847 {
03848   QString addrSpec = KPIM::getEmailAddress( address );
03849   for( QStringList::ConstIterator it = addresses.begin();
03850        it != addresses.end(); ++it ) {
03851     if ( kasciistricmp( addrSpec.utf8().data(),
03852                         KPIM::getEmailAddress( *it ).utf8().data() ) == 0 )
03853       return true;
03854   }
03855   return false;
03856 }
03857 
03858 
03859 //-----------------------------------------------------------------------------
03860 //static
03861 QString KMMessage::expandAliases( const QString& recipients )
03862 {
03863   if ( recipients.isEmpty() )
03864     return QString();
03865 
03866   QStringList recipientList = KPIM::splitEmailAddrList( recipients );
03867 
03868   QString expandedRecipients;
03869   for ( QStringList::Iterator it = recipientList.begin();
03870         it != recipientList.end(); ++it ) {
03871     if ( !expandedRecipients.isEmpty() )
03872       expandedRecipients += ", ";
03873     QString receiver = (*it).stripWhiteSpace();
03874 
03875     // try to expand distribution list
03876     QString expandedList = KAddrBookExternal::expandDistributionList( receiver );
03877     if ( !expandedList.isEmpty() ) {
03878       expandedRecipients += expandedList;
03879       continue;
03880     }
03881 
03882     // try to expand nick name
03883     QString expandedNickName = KabcBridge::expandNickName( receiver );
03884     if ( !expandedNickName.isEmpty() ) {
03885       expandedRecipients += expandedNickName;
03886       continue;
03887     }
03888 
03889     // check whether the address is missing the domain part
03890     // FIXME: looking for '@' might be wrong
03891     if ( receiver.find('@') == -1 ) {
03892       KConfigGroup general( KMKernel::config(), "General" );
03893       QString defaultdomain = general.readEntry( "Default domain" );
03894       if( !defaultdomain.isEmpty() ) {
03895         expandedRecipients += receiver + "@" + defaultdomain;
03896       }
03897       else {
03898         expandedRecipients += guessEmailAddressFromLoginName( receiver );
03899       }
03900     }
03901     else
03902       expandedRecipients += receiver;
03903   }
03904 
03905   return expandedRecipients;
03906 }
03907 
03908 
03909 //-----------------------------------------------------------------------------
03910 //static
03911 QString KMMessage::guessEmailAddressFromLoginName( const QString& loginName )
03912 {
03913   if ( loginName.isEmpty() )
03914     return QString();
03915 
03916   char hostnameC[256];
03917   // null terminate this C string
03918   hostnameC[255] = '\0';
03919   // set the string to 0 length if gethostname fails
03920   if ( gethostname( hostnameC, 255 ) )
03921     hostnameC[0] = '\0';
03922   QString address = loginName;
03923   address += '@';
03924   address += QString::fromLocal8Bit( hostnameC );
03925 
03926   // try to determine the real name
03927   const KUser user( loginName );
03928   if ( user.isValid() ) {
03929     QString fullName = user.fullName();
03930     if ( fullName.find( QRegExp( "[^ 0-9A-Za-z\\x0080-\\xFFFF]" ) ) != -1 )
03931       address = '"' + fullName.replace( '\\', "\\" ).replace( '"', "\\" )
03932           + "\" <" + address + '>';
03933     else
03934       address = fullName + " <" + address + '>';
03935   }
03936 
03937   return address;
03938 }
03939 
03940 //-----------------------------------------------------------------------------
03941 void KMMessage::readConfig()
03942 {
03943   KMMsgBase::readConfig();
03944 
03945   KConfig *config=KMKernel::config();
03946   KConfigGroupSaver saver(config, "General");
03947 
03948   config->setGroup("General");
03949 
03950   int languageNr = config->readNumEntry("reply-current-language",0);
03951 
03952   { // area for config group "KMMessage #n"
03953     KConfigGroupSaver saver(config, QString("KMMessage #%1").arg(languageNr));
03954     sReplyLanguage = config->readEntry("language",KGlobal::locale()->language());
03955     sReplyStr = config->readEntry("phrase-reply",
03956       i18n("On %D, you wrote:"));
03957     sReplyAllStr = config->readEntry("phrase-reply-all",
03958       i18n("On %D, %F wrote:"));
03959     sForwardStr = config->readEntry("phrase-forward",
03960       i18n("Forwarded Message"));
03961     sIndentPrefixStr = config->readEntry("indent-prefix",">%_");
03962   }
03963 
03964   { // area for config group "Composer"
03965     KConfigGroupSaver saver(config, "Composer");
03966     sSmartQuote = GlobalSettings::self()->smartQuote();
03967     sWordWrap = GlobalSettings::self()->wordWrap();
03968     sWrapCol = GlobalSettings::self()->lineWrapWidth();
03969     if ((sWrapCol == 0) || (sWrapCol > 78))
03970       sWrapCol = 78;
03971     if (sWrapCol < 30)
03972       sWrapCol = 30;
03973 
03974     sPrefCharsets = config->readListEntry("pref-charsets");
03975   }
03976 
03977   { // area for config group "Reader"
03978     KConfigGroupSaver saver(config, "Reader");
03979     sHeaderStrategy = HeaderStrategy::create( config->readEntry( "header-set-displayed", "rich" ) );
03980   }
03981 }
03982 
03983 QCString KMMessage::defaultCharset()
03984 {
03985   QCString retval;
03986 
03987   if (!sPrefCharsets.isEmpty())
03988     retval = sPrefCharsets[0].latin1();
03989 
03990   if (retval.isEmpty()  || (retval == "locale")) {
03991     retval = QCString(kmkernel->networkCodec()->mimeName());
03992     KPIM::kAsciiToLower( retval.data() );
03993   }
03994 
03995   if (retval == "jisx0208.1983-0") retval = "iso-2022-jp";
03996   else if (retval == "ksc5601.1987-0") retval = "euc-kr";
03997   return retval;
03998 }
03999 
04000 const QStringList &KMMessage::preferredCharsets()
04001 {
04002   return sPrefCharsets;
04003 }
04004 
04005 //-----------------------------------------------------------------------------
04006 QCString KMMessage::charset() const
04007 {
04008   if ( mMsg->Headers().HasContentType() ) {
04009     DwMediaType &mType=mMsg->Headers().ContentType();
04010     mType.Parse();
04011     DwParameter *param=mType.FirstParameter();
04012     while(param){
04013       if (!kasciistricmp(param->Attribute().c_str(), "charset"))
04014         return param->Value().c_str();
04015       else param=param->Next();
04016     }
04017   }
04018   return ""; // us-ascii, but we don't have to specify it
04019 }
04020 
04021 //-----------------------------------------------------------------------------
04022 void KMMessage::setCharset(const QCString& bStr)
04023 {
04024   kdWarning( type() != DwMime::kTypeText )
04025     << "KMMessage::setCharset(): trying to set a charset for a non-textual mimetype." << endl
04026     << "Fix this caller:" << endl
04027     << "====================================================================" << endl
04028     << kdBacktrace( 5 ) << endl
04029     << "====================================================================" << endl;
04030   QCString aStr = bStr;
04031   KPIM::kAsciiToLower( aStr.data() );
04032   DwMediaType &mType = dwContentType();
04033   mType.Parse();
04034   DwParameter *param=mType.FirstParameter();
04035   while(param)
04036     // FIXME use the mimelib functions here for comparison.
04037     if (!kasciistricmp(param->Attribute().c_str(), "charset")) break;
04038     else param=param->Next();
04039   if (!param){
04040     param=new DwParameter;
04041     param->SetAttribute("charset");
04042     mType.AddParameter(param);
04043   }
04044   else
04045     mType.SetModified();
04046   param->SetValue(DwString(aStr));
04047   mType.Assemble();
04048 }
04049 
04050 
04051 //-----------------------------------------------------------------------------
04052 void KMMessage::setStatus(const KMMsgStatus aStatus, int idx)
04053 {
04054   if (mStatus == aStatus)
04055     return;
04056   KMMsgBase::setStatus(aStatus, idx);
04057 }
04058 
04059 void KMMessage::setEncryptionState(const KMMsgEncryptionState s, int idx)
04060 {
04061     if( mEncryptionState == s )
04062         return;
04063     mEncryptionState = s;
04064     mDirty = true;
04065     KMMsgBase::setEncryptionState(s, idx);
04066 }
04067 
04068 void KMMessage::setSignatureState(KMMsgSignatureState s, int idx)
04069 {
04070     if( mSignatureState == s )
04071         return;
04072     mSignatureState = s;
04073     mDirty = true;
04074     KMMsgBase::setSignatureState(s, idx);
04075 }
04076 
04077 void KMMessage::setMDNSentState( KMMsgMDNSentState status, int idx ) {
04078   if ( mMDNSentState == status )
04079     return;
04080   if ( status == 0 )
04081     status = KMMsgMDNStateUnknown;
04082   mMDNSentState = status;
04083   mDirty = true;
04084   KMMsgBase::setMDNSentState( status, idx );
04085 }
04086 
04087 //-----------------------------------------------------------------------------
04088 void KMMessage::link( const KMMessage *aMsg, KMMsgStatus aStatus )
04089 {
04090   Q_ASSERT( aStatus == KMMsgStatusReplied
04091       || aStatus == KMMsgStatusForwarded
04092       || aStatus == KMMsgStatusDeleted );
04093 
04094   QString message = headerField( "X-KMail-Link-Message" );
04095   if ( !message.isEmpty() )
04096     message += ',';
04097   QString type = headerField( "X-KMail-Link-Type" );
04098   if ( !type.isEmpty() )
04099     type += ',';
04100 
04101   message += QString::number( aMsg->getMsgSerNum() );
04102   if ( aStatus == KMMsgStatusReplied )
04103     type += "reply";
04104   else if ( aStatus == KMMsgStatusForwarded )
04105     type += "forward";
04106   else if ( aStatus == KMMsgStatusDeleted )
04107     type += "deleted";
04108 
04109   setHeaderField( "X-KMail-Link-Message", message );
04110   setHeaderField( "X-KMail-Link-Type", type );
04111 }
04112 
04113 //-----------------------------------------------------------------------------
04114 void KMMessage::getLink(int n, ulong *retMsgSerNum, KMMsgStatus *retStatus) const
04115 {
04116   *retMsgSerNum = 0;
04117   *retStatus = KMMsgStatusUnknown;
04118 
04119   QString message = headerField("X-KMail-Link-Message");
04120   QString type = headerField("X-KMail-Link-Type");
04121   message = message.section(',', n, n);
04122   type = type.section(',', n, n);
04123 
04124   if ( !message.isEmpty() && !type.isEmpty() ) {
04125     *retMsgSerNum = message.toULong();
04126     if ( type == "reply" )
04127       *retStatus = KMMsgStatusReplied;
04128     else if ( type == "forward" )
04129       *retStatus = KMMsgStatusForwarded;
04130     else if ( type == "deleted" )
04131       *retStatus = KMMsgStatusDeleted;
04132   }
04133 }
04134 
04135 //-----------------------------------------------------------------------------
04136 DwBodyPart* KMMessage::findDwBodyPart( DwBodyPart* part, const QString & partSpecifier )
04137 {
04138   if ( !part ) return 0;
04139   DwBodyPart* current;
04140 
04141   if ( part->partId() == partSpecifier )
04142     return part;
04143 
04144   // multipart
04145   if ( part->hasHeaders() &&
04146        part->Headers().HasContentType() &&
04147        part->Body().FirstBodyPart() &&
04148        (DwMime::kTypeMultipart == part->Headers().ContentType().Type() ) &&
04149        (current = findDwBodyPart( part->Body().FirstBodyPart(), partSpecifier )) )
04150   {
04151     return current;
04152   }
04153 
04154   // encapsulated message
04155   if ( part->Body().Message() &&
04156        part->Body().Message()->Body().FirstBodyPart() &&
04157        (current = findDwBodyPart( part->Body().Message()->Body().FirstBodyPart(),
04158                                   partSpecifier )) )
04159   {
04160     return current;
04161   }
04162 
04163   // next part
04164   return findDwBodyPart( part->Next(), partSpecifier );
04165 }
04166 
04167 //-----------------------------------------------------------------------------
04168 void KMMessage::updateBodyPart(const QString partSpecifier, const QByteArray & data)
04169 {
04170   if ( !data.data() || !data.size() )
04171     return;
04172 
04173   DwString content( data.data(), data.size() );
04174   if ( numBodyParts() > 0 &&
04175        partSpecifier != "0" &&
04176        partSpecifier != "TEXT" )
04177   {
04178     QString specifier = partSpecifier;
04179     if ( partSpecifier.endsWith(".HEADER") ||
04180          partSpecifier.endsWith(".MIME") ) {
04181       // get the parent bodypart
04182       specifier = partSpecifier.section( '.', 0, -2 );
04183     }
04184 
04185     // search for the bodypart
04186     mLastUpdated = findDwBodyPart( getFirstDwBodyPart(), specifier );
04187     kdDebug(5006) << "KMMessage::updateBodyPart " << specifier << endl;
04188     if (!mLastUpdated)
04189     {
04190       kdWarning(5006) << "KMMessage::updateBodyPart - can not find part "
04191         << specifier << endl;
04192       return;
04193     }
04194     if ( partSpecifier.endsWith(".MIME") )
04195     {
04196       // update headers
04197       // get rid of EOL
04198       content.resize( QMAX( content.length(), 2 ) - 2 );
04199       // we have to delete the fields first as they might have been created by
04200       // an earlier call to DwHeaders::FieldBody
04201       mLastUpdated->Headers().DeleteAllFields();
04202       mLastUpdated->Headers().FromString( content );
04203       mLastUpdated->Headers().Parse();
04204     } else if ( partSpecifier.endsWith(".HEADER") )
04205     {
04206       // update header of embedded message
04207       mLastUpdated->Body().Message()->Headers().FromString( content );
04208       mLastUpdated->Body().Message()->Headers().Parse();
04209     } else {
04210       // update body
04211       mLastUpdated->Body().FromString( content );
04212       QString parentSpec = partSpecifier.section( '.', 0, -2 );
04213       if ( !parentSpec.isEmpty() )
04214       {
04215         DwBodyPart* parent = findDwBodyPart( getFirstDwBodyPart(), parentSpec );
04216         if ( parent && parent->hasHeaders() && parent->Headers().HasContentType() )
04217         {
04218           const DwMediaType& contentType = parent->Headers().ContentType();
04219           if ( contentType.Type() == DwMime::kTypeMessage &&
04220                contentType.Subtype() == DwMime::kSubtypeRfc822 )
04221           {
04222             // an embedded message that is not multipart
04223             // update this directly
04224             parent->Body().Message()->Body().FromString( content );
04225           }
04226         }
04227       }
04228     }
04229 
04230   } else
04231   {
04232     // update text-only messages
04233     if ( partSpecifier == "TEXT" )
04234       deleteBodyParts(); // delete empty parts first
04235     mMsg->Body().FromString( content );
04236     mMsg->Body().Parse();
04237   }
04238   mNeedsAssembly = true;
04239   if (! partSpecifier.endsWith(".HEADER") )
04240   {
04241     // notify observers
04242     notify();
04243   }
04244 }
04245 
04246 //-----------------------------------------------------------------------------
04247 void KMMessage::updateAttachmentState( DwBodyPart* part )
04248 {
04249   if ( !part )
04250     part = getFirstDwBodyPart();
04251 
04252   if ( !part )
04253   {
04254     // kdDebug(5006) << "updateAttachmentState - no part!" << endl;
04255     setStatus( KMMsgStatusHasNoAttach );
04256     return;
04257   }
04258 
04259   bool filenameEmpty = true;
04260   if ( part->hasHeaders() ) {
04261     if ( part->Headers().HasContentDisposition() ) {
04262       DwDispositionType cd = part->Headers().ContentDisposition();
04263       filenameEmpty = cd.Filename().empty();
04264       if ( filenameEmpty ) {
04265         // let's try if it is rfc 2231 encoded which mimelib can't handle
04266         filenameEmpty = KMMsgBase::decodeRFC2231String( KMMsgBase::extractRFC2231HeaderField( cd.AsString().c_str(), "filename" ) ).isEmpty();
04267       }
04268     }
04269   }
04270 
04271   if ( part->hasHeaders() &&
04272        ( ( part->Headers().HasContentDisposition() &&
04273            !part->Headers().ContentDisposition().Filename().empty() ) ||
04274          ( part->Headers().HasContentType() &&
04275            !filenameEmpty ) ) )
04276   {
04277     // now blacklist certain ContentTypes
04278     if ( !part->Headers().HasContentType() ||
04279          ( part->Headers().HasContentType() &&
04280            part->Headers().ContentType().Subtype() != DwMime::kSubtypePgpSignature &&
04281            part->Headers().ContentType().Subtype() != DwMime::kSubtypePkcs7Signature ) )
04282     {
04283       setStatus( KMMsgStatusHasAttach );
04284     }
04285     return;
04286   }
04287 
04288   // multipart
04289   if ( part->hasHeaders() &&
04290        part->Headers().HasContentType() &&
04291        part->Body().FirstBodyPart() &&
04292        (DwMime::kTypeMultipart == part->Headers().ContentType().Type() ) )
04293   {
04294     updateAttachmentState( part->Body().FirstBodyPart() );
04295   }
04296 
04297   // encapsulated message
04298   if ( part->Body().Message() &&
04299        part->Body().Message()->Body().FirstBodyPart() )
04300   {
04301     updateAttachmentState( part->Body().Message()->Body().FirstBodyPart() );
04302   }
04303 
04304   // next part
04305   if ( part->Next() )
04306     updateAttachmentState( part->Next() );
04307   else if ( attachmentState() == KMMsgAttachmentUnknown )
04308     setStatus( KMMsgStatusHasNoAttach );
04309 }
04310 
04311 void KMMessage::setBodyFromUnicode( const QString & str ) {
04312   QCString encoding = KMMsgBase::autoDetectCharset( charset(), KMMessage::preferredCharsets(), str );
04313   if ( encoding.isEmpty() )
04314     encoding = "utf-8";
04315   const QTextCodec * codec = KMMsgBase::codecForName( encoding );
04316   assert( codec );
04317   QValueList<int> dummy;
04318   setCharset( encoding );
04319   setBodyAndGuessCte( codec->fromUnicode( str ), dummy, false /* no 8bit */ );
04320 }
04321 
04322 const QTextCodec * KMMessage::codec() const {
04323   const QTextCodec * c = mOverrideCodec;
04324   if ( !c )
04325     // no override-codec set for this message, try the CT charset parameter:
04326     c = KMMsgBase::codecForName( charset() );
04327   if ( !c ) {
04328     // Ok, no override and nothing in the message, let's use the fallback
04329     // the user configured
04330     c = KMMsgBase::codecForName( GlobalSettings::self()->fallbackCharacterEncoding().latin1() );
04331   }
04332   if ( !c )
04333     // no charset means us-ascii (RFC 2045), so using local encoding should
04334     // be okay
04335     c = kmkernel->networkCodec();
04336   assert( c );
04337   return c;
04338 }
04339 
04340 QString KMMessage::bodyToUnicode(const QTextCodec* codec) const {
04341   if ( !codec )
04342     // No codec was given, so try the charset in the mail
04343     codec = this->codec();
04344   assert( codec );
04345 
04346   return codec->toUnicode( bodyDecoded() );
04347 }
04348 
04349 //-----------------------------------------------------------------------------
04350 QCString KMMessage::mboxMessageSeparator()
04351 {
04352   QCString str( KPIM::getFirstEmailAddress( rawHeaderField("From") ) );
04353   if ( str.isEmpty() )
04354     str = "unknown@unknown.invalid";
04355   QCString dateStr( dateShortStr() );
04356   if ( dateStr.isEmpty() ) {
04357     time_t t = ::time( 0 );
04358     dateStr = ctime( &t );
04359     const int len = dateStr.length();
04360     if ( dateStr[len-1] == '\n' )
04361       dateStr.truncate( len - 1 );
04362   }
04363   return "From " + str + " " + dateStr + "\n";
04364 }
04365 
04366 void KMMessage::deleteWhenUnused()
04367 {
04368   sPendingDeletes << this;
04369 }
KDE Home | KDE Accessibility Home | Description of Access Keys