kmail Library API Documentation

kmmsgbase.cpp

00001 // kmmsgbase.cpp
00002 
00003 #include <config.h>
00004 
00005 #include "kmmsgbase.h"
00006 
00007 #include "kmfolderindex.h"
00008 #include "kmfolder.h"
00009 #include "kmheaders.h"
00010 #include "kmmsgdict.h"
00011 #include "messageproperty.h"
00012 using KMail::MessageProperty;
00013 
00014 #include <kdebug.h>
00015 #include <kglobal.h>
00016 #include <kcharsets.h>
00017 #include <kmdcodec.h>
00018 #include <krfcdate.h>
00019 
00020 #include <mimelib/mimepp.h>
00021 #include <kmime_codecs.h>
00022 
00023 #include <qtextcodec.h>
00024 #include <qdeepcopy.h>
00025 #include <qregexp.h>
00026 
00027 #include <ctype.h>
00028 #include <stdlib.h>
00029 #include <unistd.h>
00030 
00031 #ifdef HAVE_BYTESWAP_H
00032 #include <byteswap.h>
00033 #endif
00034 
00035 // We define functions as kmail_swap_NN so that we don't get compile errors
00036 // on platforms where bswap_NN happens to be a function instead of a define.
00037 
00038 /* Swap bytes in 16 bit value.  */
00039 #ifdef bswap_16
00040 #define kmail_swap_16(x) bswap_16(x)
00041 #else
00042 #define kmail_swap_16(x) \
00043      ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))
00044 #endif
00045 
00046 /* Swap bytes in 32 bit value.  */
00047 #ifdef bswap_32
00048 #define kmail_swap_32(x) bswap_32(x)
00049 #else
00050 #define kmail_swap_32(x) \
00051      ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >>  8) |           \
00052       (((x) & 0x0000ff00) <<  8) | (((x) & 0x000000ff) << 24))
00053 #endif
00054 
00055 /* Swap bytes in 64 bit value.  */
00056 #ifdef bswap_64
00057 #define kmail_swap_64(x) bswap_64(x)
00058 #else
00059 #define kmail_swap_64(x) \
00060      ((((x) & 0xff00000000000000ull) >> 56)                   \
00061       | (((x) & 0x00ff000000000000ull) >> 40)                     \
00062       | (((x) & 0x0000ff0000000000ull) >> 24)                     \
00063       | (((x) & 0x000000ff00000000ull) >> 8)                      \
00064       | (((x) & 0x00000000ff000000ull) << 8)                      \
00065       | (((x) & 0x0000000000ff0000ull) << 24)                     \
00066       | (((x) & 0x000000000000ff00ull) << 40)                     \
00067       | (((x) & 0x00000000000000ffull) << 56))
00068 #endif
00069 
00070 //-----------------------------------------------------------------------------
00071 KMMsgBase::KMMsgBase(KMFolder* aParentFolder)
00072   : mParent( aParentFolder ), mIndexOffset( 0 ),
00073     mIndexLength( 0 ), mDirty( false ), mEnableUndo( false ), mStatus( KMMsgStatusUnknown )
00074 {
00075 }
00076 
00077 
00078 //-----------------------------------------------------------------------------
00079 KMMsgBase::~KMMsgBase()
00080 {
00081   MessageProperty::forget( this );
00082 }
00083 
00084 KMFolderIndex* KMMsgBase::storage() const
00085 {
00086   // TODO: How did this ever work? What about KMFolderSearch that does
00087   // not inherit KMFolderIndex?
00088   if( mParent )
00089     return static_cast<KMFolderIndex*>( mParent->storage() );
00090   return 0;
00091 }
00092 
00093 //-----------------------------------------------------------------------------
00094 void KMMsgBase::assign(const KMMsgBase* other)
00095 {
00096   mParent = other->mParent;
00097   mDirty  = other->mDirty;
00098   mIndexOffset = other->mIndexOffset;
00099   mIndexLength = other->mIndexLength;
00100   MessageProperty::forget( this );
00101   //bool otherTransfer = MessageProperty::transferInProgress( other );
00102   //MessageProperty::setTransferInProgress( this, otherTransfer );
00103 }
00104 
00105 
00106 //-----------------------------------------------------------------------------
00107 KMMsgBase& KMMsgBase::operator=(const KMMsgBase& other)
00108 {
00109   assign(&other);
00110   return *this;
00111 }
00112 
00113 
00114 //----------------------------------------------------------------------------
00115 KMMsgBase::KMMsgBase( const KMMsgBase& other )
00116 {
00117     assign( &other );
00118 }
00119 
00120 
00121 //-----------------------------------------------------------------------------
00122 bool KMMsgBase::isMessage(void) const
00123 {
00124   return FALSE;
00125 }
00126 //-----------------------------------------------------------------------------
00127 void KMMsgBase::toggleStatus(const KMMsgStatus aStatus, int idx)
00128 {
00129   mDirty = true;
00130   KMMsgStatus oldStatus = status();
00131     if ( status() & aStatus ) {
00132     mStatus &= ~aStatus;
00133   } else {
00134     mStatus |= aStatus;
00135     // Ignored and Watched are toggleable, yet mutually exclusive.
00136     // That is an arbitrary restriction on my part. HAR HAR HAR :) -till
00137     if (aStatus == KMMsgStatusWatched)
00138       mStatus &= ~KMMsgStatusIgnored;
00139     if (aStatus == KMMsgStatusIgnored) {
00140       mStatus &= ~KMMsgStatusWatched;
00141       // Set to read. Don't use setStatus, that emits msgStatusChanged
00142       // and we only want to do that once.
00143       mStatus &= ~KMMsgStatusUnread;
00144       mStatus &= ~KMMsgStatusNew;
00145       mStatus |= KMMsgStatusRead;
00146     }
00147     if (aStatus == KMMsgStatusSpam)
00148       mStatus &= ~KMMsgStatusHam;
00149     if (aStatus == KMMsgStatusHam)
00150       mStatus &= ~KMMsgStatusSpam;
00151   }
00152   if (storage()) {
00153      if (idx < 0)
00154        idx = storage()->find( this );
00155      storage()->msgStatusChanged( oldStatus, status(), idx );
00156      storage()->headerOfMsgChanged(this, idx);
00157   }
00158 
00159 }
00160 
00161 //-----------------------------------------------------------------------------
00162 void KMMsgBase::setStatus(const KMMsgStatus aStatus, int idx)
00163 {
00164   mDirty = TRUE;
00165   KMMsgStatus oldStatus = status();
00166   switch (aStatus) {
00167     case KMMsgStatusRead:
00168       // Unset unread and new, set read
00169       mStatus &= ~KMMsgStatusUnread;
00170       mStatus &= ~KMMsgStatusNew;
00171       mStatus |= KMMsgStatusRead;
00172       break;
00173 
00174     case KMMsgStatusUnread:
00175       // unread overrides read
00176       mStatus &= ~KMMsgStatusOld;
00177       mStatus &= ~KMMsgStatusRead;
00178       mStatus &= ~KMMsgStatusNew;
00179       mStatus |= KMMsgStatusUnread;
00180       break;
00181 
00182     case KMMsgStatusOld:
00183       // old can't be new or unread
00184       mStatus &= ~KMMsgStatusNew;
00185       mStatus &= ~KMMsgStatusUnread;
00186       mStatus |= KMMsgStatusOld;
00187       break;
00188 
00189     case KMMsgStatusNew:
00190       // new overrides old and read
00191       mStatus &= ~KMMsgStatusOld;
00192       mStatus &= ~KMMsgStatusRead;
00193       mStatus &= ~KMMsgStatusUnread;
00194       mStatus |= KMMsgStatusNew;
00195       break;
00196 
00197     case KMMsgStatusDeleted:
00198       mStatus |= KMMsgStatusDeleted;
00199       break;
00200 
00201     case KMMsgStatusReplied:
00202       mStatus |= KMMsgStatusReplied;
00203       break;
00204 
00205     case KMMsgStatusForwarded:
00206       mStatus |= KMMsgStatusForwarded;
00207       break;
00208 
00209     case KMMsgStatusQueued:
00210       mStatus |= KMMsgStatusQueued;
00211       break;
00212 
00213     case KMMsgStatusSent:
00214       mStatus &= ~KMMsgStatusQueued;
00215       mStatus &= ~KMMsgStatusUnread;
00216       mStatus &= ~KMMsgStatusNew;
00217       mStatus |= KMMsgStatusSent;
00218       break;
00219 
00220     case KMMsgStatusFlag:
00221       mStatus |= KMMsgStatusFlag;
00222       break;
00223 
00224     // Watched and ignored are mutually exclusive
00225     case KMMsgStatusWatched:
00226       mStatus &= ~KMMsgStatusIgnored;
00227       mStatus |= KMMsgStatusWatched;
00228       break;
00229 
00230     case KMMsgStatusIgnored:
00231       mStatus &= ~KMMsgStatusWatched;
00232       mStatus |= KMMsgStatusIgnored;
00233       break;
00234     // as are ham and spam
00235     case KMMsgStatusSpam:
00236       mStatus &= ~KMMsgStatusHam;
00237       mStatus |= KMMsgStatusSpam;
00238       break;
00239     case KMMsgStatusHam:
00240       mStatus &= ~KMMsgStatusSpam;
00241       mStatus |= KMMsgStatusHam;
00242       break;
00243     case KMMsgStatusHasAttach:
00244       mStatus &= ~KMMsgStatusHasNoAttach;
00245       mStatus |= KMMsgStatusHasAttach;
00246       break;
00247     case KMMsgStatusHasNoAttach:
00248       mStatus &= ~KMMsgStatusHasAttach;
00249       mStatus |= KMMsgStatusHasNoAttach;
00250       break;
00251     default:
00252       mStatus = aStatus;
00253       break;
00254   }
00255 
00256   if (oldStatus != mStatus && storage()) {
00257     if (idx < 0)
00258       idx = storage()->find( this );
00259     storage()->msgStatusChanged( oldStatus, status(), idx );
00260     storage()->headerOfMsgChanged( this, idx );
00261   }
00262 }
00263 
00264 
00265 
00266 //-----------------------------------------------------------------------------
00267 void KMMsgBase::setStatus(const char* aStatusStr, const char* aXStatusStr)
00268 {
00269   // first try to find status from "X-Status" field if given
00270   if (aXStatusStr) {
00271     if (strchr(aXStatusStr, 'N')) setStatus(KMMsgStatusNew);
00272     if (strchr(aXStatusStr, 'U')) setStatus(KMMsgStatusUnread);
00273     if (strchr(aXStatusStr, 'O')) setStatus(KMMsgStatusOld);
00274     if (strchr(aXStatusStr, 'R')) setStatus(KMMsgStatusRead);
00275     if (strchr(aXStatusStr, 'D')) setStatus(KMMsgStatusDeleted);
00276     if (strchr(aXStatusStr, 'A')) setStatus(KMMsgStatusReplied);
00277     if (strchr(aXStatusStr, 'F')) setStatus(KMMsgStatusForwarded);
00278     if (strchr(aXStatusStr, 'Q')) setStatus(KMMsgStatusQueued);
00279     if (strchr(aXStatusStr, 'S')) setStatus(KMMsgStatusSent);
00280     if (strchr(aXStatusStr, 'G')) setStatus(KMMsgStatusFlag);
00281     if (strchr(aXStatusStr, 'P')) setStatus(KMMsgStatusSpam);
00282     if (strchr(aXStatusStr, 'H')) setStatus(KMMsgStatusHam);
00283     if (strchr(aXStatusStr, 'T')) setStatus(KMMsgStatusHasAttach);
00284     if (strchr(aXStatusStr, 'C')) setStatus(KMMsgStatusHasNoAttach);
00285   }
00286 
00287   // Merge the contents of the "Status" field
00288   if (aStatusStr) {
00289     if ((aStatusStr[0]== 'R' && aStatusStr[1]== 'O') ||
00290         (aStatusStr[0]== 'O' && aStatusStr[1]== 'R')) {
00291       setStatus( KMMsgStatusOld );
00292       setStatus( KMMsgStatusRead );
00293     }
00294     else if (aStatusStr[0] == 'R')
00295       setStatus(KMMsgStatusRead);
00296     else if (aStatusStr[0] == 'D')
00297       setStatus(KMMsgStatusDeleted);
00298     else
00299       setStatus(KMMsgStatusNew);
00300   }
00301 }
00302 
00303 
00304 void KMMsgBase::setEncryptionState( const KMMsgEncryptionState /*status*/, int idx )
00305 {
00306     //kdDebug(5006) << "***setEncryptionState1( " << status << " )" << endl;
00307     mDirty = TRUE;
00308     if (storage())
00309         storage()->headerOfMsgChanged(this, idx);
00310 }
00311 
00312 void KMMsgBase::setEncryptionStateChar( QChar status, int idx )
00313 {
00314     //kdDebug(5006) << "***setEncryptionState2( " << (status.isNull() ? '?' : status.latin1()) << " )" << endl;
00315 
00316     if( status.latin1() == (char)KMMsgEncryptionStateUnknown )
00317         setEncryptionState( KMMsgEncryptionStateUnknown, idx );
00318     else if( status.latin1() == (char)KMMsgNotEncrypted )
00319         setEncryptionState( KMMsgNotEncrypted, idx );
00320     else if( status.latin1() == (char)KMMsgPartiallyEncrypted )
00321         setEncryptionState( KMMsgPartiallyEncrypted, idx );
00322     else if( status.latin1() == (char)KMMsgFullyEncrypted )
00323         setEncryptionState( KMMsgFullyEncrypted, idx );
00324     else
00325         setEncryptionState( KMMsgEncryptionStateUnknown, idx );
00326 }
00327 
00328 
00329 void KMMsgBase::setSignatureState( const KMMsgSignatureState /*status*/, int idx )
00330 {
00331     //kdDebug(5006) << "***setSignatureState1( " << status << " )" << endl;
00332     mDirty = TRUE;
00333     if (storage())
00334          storage()->headerOfMsgChanged(this, idx);
00335 }
00336 
00337 void KMMsgBase::setMDNSentState( KMMsgMDNSentState, int idx ) {
00338   mDirty = true;
00339   if ( storage() )
00340     storage()->headerOfMsgChanged(this, idx);
00341 }
00342 
00343 void KMMsgBase::setSignatureStateChar( QChar status, int idx )
00344 {
00345     //kdDebug(5006) << "***setSignatureState2( " << (status.isNull() ? '?' : status.latin1()) << " )" << endl;
00346 
00347     if( status.latin1() == (char)KMMsgSignatureStateUnknown )
00348         setSignatureState( KMMsgSignatureStateUnknown, idx );
00349     else if( status.latin1() == (char)KMMsgNotSigned )
00350         setSignatureState( KMMsgNotSigned, idx );
00351     else if( status.latin1() == (char)KMMsgPartiallySigned )
00352         setSignatureState( KMMsgPartiallySigned,idx );
00353     else if( status.latin1() == (char)KMMsgFullySigned )
00354         setSignatureState( KMMsgFullySigned, idx );
00355     else
00356         setSignatureState( KMMsgSignatureStateUnknown, idx );
00357 }
00358 
00359 //-----------------------------------------------------------------------------
00360 bool KMMsgBase::isUnread(void) const
00361 {
00362   KMMsgStatus st = status();
00363   return (st & KMMsgStatusUnread);
00364 }
00365 
00366 //-----------------------------------------------------------------------------
00367 bool KMMsgBase::isNew(void) const
00368 {
00369   KMMsgStatus st = status();
00370   return (st & KMMsgStatusNew);
00371 }
00372 
00373 //-----------------------------------------------------------------------------
00374 bool KMMsgBase::isOfUnknownStatus(void) const
00375 {
00376   KMMsgStatus st = status();
00377   return (st == KMMsgStatusUnknown);
00378 }
00379 
00380 //-----------------------------------------------------------------------------
00381 bool KMMsgBase::isOld(void) const
00382 {
00383   KMMsgStatus st = status();
00384   return (st & KMMsgStatusOld);
00385 }
00386 
00387 //-----------------------------------------------------------------------------
00388 bool KMMsgBase::isRead(void) const
00389 {
00390   KMMsgStatus st = status();
00391   return (st & KMMsgStatusRead);
00392 }
00393 
00394 //-----------------------------------------------------------------------------
00395 bool KMMsgBase::isDeleted(void) const
00396 {
00397   KMMsgStatus st = status();
00398   return (st & KMMsgStatusDeleted);
00399 }
00400 
00401 //-----------------------------------------------------------------------------
00402 bool KMMsgBase::isReplied(void) const
00403 {
00404   KMMsgStatus st = status();
00405   return (st & KMMsgStatusReplied);
00406 }
00407 
00408 //-----------------------------------------------------------------------------
00409 bool KMMsgBase::isForwarded(void) const
00410 {
00411   KMMsgStatus st = status();
00412   return (st & KMMsgStatusForwarded);
00413 }
00414 
00415 //-----------------------------------------------------------------------------
00416 bool KMMsgBase::isQueued(void) const
00417 {
00418   KMMsgStatus st = status();
00419   return (st & KMMsgStatusQueued);
00420 }
00421 
00422 //-----------------------------------------------------------------------------
00423 bool KMMsgBase::isSent(void) const
00424 {
00425   KMMsgStatus st = status();
00426   return (st & KMMsgStatusSent);
00427 }
00428 
00429 //-----------------------------------------------------------------------------
00430 bool KMMsgBase::isImportant(void) const
00431 {
00432   KMMsgStatus st = status();
00433   return (st & KMMsgStatusFlag);
00434 }
00435 
00436 //-----------------------------------------------------------------------------
00437 bool KMMsgBase::isWatched(void) const
00438 {
00439   KMMsgStatus st = status();
00440   return (st & KMMsgStatusWatched);
00441 }
00442 
00443 //-----------------------------------------------------------------------------
00444 bool KMMsgBase::isIgnored(void) const
00445 {
00446   KMMsgStatus st = status();
00447   return (st & KMMsgStatusIgnored);
00448 }
00449 
00450 //-----------------------------------------------------------------------------
00451 bool KMMsgBase::isSpam(void) const
00452 {
00453   KMMsgStatus st = status();
00454   return (st & KMMsgStatusSpam);
00455 }
00456 
00457 //-----------------------------------------------------------------------------
00458 bool KMMsgBase::isHam(void) const
00459 {
00460   KMMsgStatus st = status();
00461   return (st & KMMsgStatusHam);
00462 }
00463 
00464 //-----------------------------------------------------------------------------
00465 QCString KMMsgBase::statusToStr(const KMMsgStatus status)
00466 {
00467   QCString sstr;
00468   if (status & KMMsgStatusNew) sstr += 'N';
00469   if (status & KMMsgStatusUnread) sstr += 'U';
00470   if (status & KMMsgStatusOld) sstr += 'O';
00471   if (status & KMMsgStatusRead) sstr += 'R';
00472   if (status & KMMsgStatusDeleted) sstr += 'D';
00473   if (status & KMMsgStatusReplied) sstr += 'A';
00474   if (status & KMMsgStatusForwarded) sstr += 'F';
00475   if (status & KMMsgStatusQueued) sstr += 'Q';
00476   if (status & KMMsgStatusSent) sstr += 'S';
00477   if (status & KMMsgStatusFlag) sstr += 'G';
00478   if (status & KMMsgStatusWatched) sstr += 'W';
00479   if (status & KMMsgStatusIgnored) sstr += 'I';
00480   if (status & KMMsgStatusSpam) sstr += 'P';
00481   if (status & KMMsgStatusHam) sstr += 'H';
00482   if (status & KMMsgStatusHasAttach) sstr += 'T';
00483   if (status & KMMsgStatusHasNoAttach) sstr += 'C';
00484 
00485   return sstr;
00486 }
00487 
00488 //-----------------------------------------------------------------------------
00489 QString KMMsgBase::statusToSortRank()
00490 {
00491   QString sstr = "bcbbbbbbb";
00492 
00493   // put watched ones first, then normal ones, ignored ones last
00494   if (status() & KMMsgStatusWatched) sstr[0] = 'a';
00495   if (status() & KMMsgStatusIgnored) sstr[0] = 'c';
00496 
00497   // Second level. One of new, old, read, unread
00498   if (status() & KMMsgStatusNew) sstr[1] = 'a';
00499   if (status() & KMMsgStatusUnread) sstr[1] = 'b';
00500   //if (status() & KMMsgStatusOld) sstr[1] = 'c';
00501   //if (status() & KMMsgStatusRead) sstr[1] = 'c';
00502 
00503   // Third level. In somewhat arbitrary order.
00504   if (status() & KMMsgStatusDeleted) sstr[2] = 'a';
00505   if (status() & KMMsgStatusFlag) sstr[3] = 'a';
00506   if (status() & KMMsgStatusReplied) sstr[4] = 'a';
00507   if (status() & KMMsgStatusForwarded) sstr[5] = 'a';
00508   if (status() & KMMsgStatusQueued) sstr[6] = 'a';
00509   if (status() & KMMsgStatusSent) sstr[7] = 'a';
00510   if (status() & KMMsgStatusHam) sstr[8] = 'a';
00511   if (status() & KMMsgStatusSpam) sstr[8] = 'c';
00512 
00513   return sstr;
00514 }
00515 
00516 
00517 //-----------------------------------------------------------------------------
00518 void KMMsgBase::setDate(const QCString& aDateStr)
00519 {
00520   setDate( KRFCDate::parseDate( aDateStr ) );
00521 }
00522 
00523 
00524 //-----------------------------------------------------------------------------
00525 QString KMMsgBase::dateStr(void) const
00526 {
00527   time_t d = date();
00528   return KMime::DateFormatter::formatDate(KMime::DateFormatter::Fancy, d);
00529 }
00530 
00531 
00532 //-----------------------------------------------------------------------------
00533 QString KMMsgBase::skipKeyword(const QString& aStr, QChar sepChar,
00534                    bool* hasKeyword)
00535 {
00536   unsigned int i = 0, maxChars = 3;
00537   QString str = aStr;
00538 
00539   while (str[0] == ' ') str.remove(0,1);
00540   if (hasKeyword) *hasKeyword=FALSE;
00541 
00542   for (i=0; i < str.length() && i < maxChars; i++)
00543   {
00544     if (str[i] < 'A' || str[i] == sepChar) break;
00545   }
00546 
00547   if (str[i] == sepChar) // skip following spaces too
00548   {
00549     do {
00550       i++;
00551     } while (str[i] == ' ');
00552     if (hasKeyword) *hasKeyword=TRUE;
00553     return str.mid(i);
00554   }
00555   return str;
00556 }
00557 
00558 
00559 //-----------------------------------------------------------------------------
00560 const QTextCodec* KMMsgBase::codecForName(const QCString& _str)
00561 {
00562   if (_str.isEmpty()) return 0;
00563   return KGlobal::charsets()->codecForName(_str.lower());
00564 }
00565 
00566 
00567 //-----------------------------------------------------------------------------
00568 QCString KMMsgBase::toUsAscii(const QString& _str, bool *ok)
00569 {
00570   bool all_ok =true;
00571   QString result = _str;
00572   int len = result.length();
00573   for (int i = 0; i < len; i++)
00574     if (result.at(i).unicode() >= 128) {
00575       result.at(i) = '?';
00576       all_ok = false;
00577     }
00578   if (ok)
00579     *ok = all_ok;
00580   return result.latin1();
00581 }
00582 
00583 
00584 //-----------------------------------------------------------------------------
00585 QStringList KMMsgBase::supportedEncodings(bool usAscii)
00586 {
00587   QStringList encodingNames = KGlobal::charsets()->availableEncodingNames();
00588   QStringList encodings;
00589   QMap<QString,bool> mimeNames;
00590   for (QStringList::Iterator it = encodingNames.begin();
00591     it != encodingNames.end(); it++)
00592   {
00593     QTextCodec *codec = KGlobal::charsets()->codecForName(*it);
00594     QString mimeName = (codec) ? QString(codec->mimeName()).lower() : (*it);
00595     if (mimeNames.find(mimeName) == mimeNames.end())
00596     {
00597       encodings.append(KGlobal::charsets()->languageForEncoding(*it)
00598         + " ( " + mimeName + " )");
00599       mimeNames.insert(mimeName, TRUE);
00600     }
00601   }
00602   encodings.sort();
00603   if (usAscii) encodings.prepend(KGlobal::charsets()
00604     ->languageForEncoding("us-ascii") + " ( us-ascii )");
00605   return encodings;
00606 }
00607 
00608 namespace {
00609   // don't rely on isblank(), which is a GNU extension in
00610   // <cctype>. But if someone wants to write a configure test for
00611   // isblank(), we can then rename this function to isblank and #ifdef
00612   // it's definition...
00613   inline bool isBlank( char ch ) { return ch == ' ' || ch == '\t' ; }
00614 
00615   QCString unfold( const QCString & header ) {
00616     if ( header.isEmpty() )
00617       return QCString();
00618 
00619     QCString result( header.size() ); // size() >= length()+1 and size() is O(1)
00620     char * d = result.data();
00621 
00622     for ( const char * s = header.data() ; *s ; )
00623       if ( *s == '\r' ) { // ignore
00624     ++s;
00625     continue;
00626       } else if ( *s == '\n' ) { // unfold
00627     while ( isBlank( *++s ) );
00628     *d++ = ' ';
00629       } else
00630     *d++ = *s++;
00631 
00632     *d++ = '\0';
00633 
00634     result.truncate( d - result.data() );
00635     return result;
00636   }
00637 }
00638 
00639 
00640 //-----------------------------------------------------------------------------
00641 QString KMMsgBase::decodeRFC2047String(const QCString& aStr)
00642 {
00643   if ( aStr.isEmpty() )
00644     return QString::null;
00645 
00646   const QCString str = unfold( aStr );
00647 
00648   if ( str.isEmpty() )
00649     return QString::null;
00650 
00651   if ( str.find( "=?" ) < 0 )
00652     return kmkernel->networkCodec()->toUnicode( str );
00653 
00654   QString result;
00655   QCString LWSP_buffer;
00656   bool lastWasEncodedWord = false;
00657   static const int maxLen = 200;
00658 
00659   for ( const char * pos = str.data() ; *pos ; ++pos ) {
00660     // collect LWSP after encoded-words,
00661     // because we might need to throw it out
00662     // (when the next word is an encoded-word)
00663     if ( lastWasEncodedWord && isBlank( pos[0] ) ) {
00664       LWSP_buffer += pos[0];
00665       continue;
00666     }
00667     // verbatimly copy normal text
00668     if (pos[0]!='=' || pos[1]!='?') {
00669       result += LWSP_buffer + pos[0];
00670       LWSP_buffer = 0;
00671       lastWasEncodedWord = FALSE;
00672       continue;
00673     }
00674     // found possible encoded-word
00675     const char * const beg = pos;
00676     {
00677       // parse charset name
00678       QCString charset;
00679       int i = 2;
00680       for (pos+=2; i<maxLen && (*pos!='?'&&(*pos==' '||ispunct(*pos)||isalnum(*pos))); ++i) {
00681     charset += *pos;
00682     pos++;
00683       }
00684       if (*pos!='?' || i<4 || i>=maxLen)
00685     goto invalid_encoded_word;
00686 
00687       // get encoding and check delimiting question marks
00688       const char encoding[2] = { pos[1], '\0' };
00689       if (pos[2]!='?' || (encoding[0]!='Q' && encoding[0]!='q' &&
00690               encoding[0]!='B' && encoding[0]!='b'))
00691     goto invalid_encoded_word;
00692       pos+=3; i+=3; // skip ?x?
00693       const char * enc_start = pos;
00694       // search for end of encoded part
00695       while (i<maxLen && *pos && !(*pos=='?' && *(pos+1)=='=')) {
00696     i++;
00697     pos++;
00698       }
00699       if (i>=maxLen || !*pos)
00700     goto invalid_encoded_word;
00701 
00702       // valid encoding: decode and throw away separating LWSP
00703       const KMime::Codec * c = KMime::Codec::codecForName( encoding );
00704       kdFatal( !c, 5006 ) << "No \"" << encoding << "\" codec!?" << endl;
00705 
00706       QByteArray in; in.setRawData( enc_start, pos - enc_start );
00707       const QByteArray enc = c->decode( in );
00708       in.resetRawData( enc_start, pos - enc_start );
00709 
00710       const QTextCodec * codec = codecForName(charset);
00711       if (!codec) codec = kmkernel->networkCodec();
00712       result += codec->toUnicode(enc);
00713       lastWasEncodedWord = true;
00714 
00715       ++pos; // eat '?' (for loop eats '=')
00716       LWSP_buffer = 0;
00717     }
00718     continue;
00719   invalid_encoded_word:
00720     // invalid encoding, keep separating LWSP.
00721     pos = beg;
00722     if ( !LWSP_buffer.isNull() )
00723       result += LWSP_buffer;
00724     result += "=?";
00725     lastWasEncodedWord = false;
00726     ++pos; // eat '?' (for loop eats '=')
00727     LWSP_buffer = 0;
00728   }
00729   return result;
00730 }
00731 
00732 
00733 //-----------------------------------------------------------------------------
00734 static const QCString especials = "()<>@,;:\"/[]?.= \033";
00735 
00736 QCString KMMsgBase::encodeRFC2047Quoted( const QCString & s, bool base64 ) {
00737   const char * codecName = base64 ? "b" : "q" ;
00738   const KMime::Codec * codec = KMime::Codec::codecForName( codecName );
00739   kdFatal( !codec, 5006 ) << "No \"" << codecName << "\" found!?" << endl;
00740   QByteArray in; in.setRawData( s.data(), s.length() );
00741   const QByteArray result = codec->encode( in );
00742   in.resetRawData( s.data(), s.length() );
00743   return QCString( result.data(), result.size() + 1 );
00744 }
00745 
00746 QCString KMMsgBase::encodeRFC2047String(const QString& _str,
00747   const QCString& charset)
00748 {
00749   static const QString dontQuote = "\"()<>,@";
00750 
00751   if (_str.isEmpty()) return QCString();
00752   if (charset == "us-ascii") return toUsAscii(_str);
00753 
00754   QCString cset;
00755   if (charset.isEmpty()) cset = QCString(kmkernel->networkCodec()->mimeName()).lower();
00756     else cset = charset;
00757   const QTextCodec *codec = codecForName(cset);
00758   if (!codec) codec = kmkernel->networkCodec();
00759 
00760   unsigned int nonAscii = 0;
00761   for (unsigned int i = 0; i < _str.length(); i++)
00762     if (_str.at(i).unicode() >= 128) nonAscii++;
00763   bool useBase64 = (nonAscii * 6 > _str.length());
00764 
00765   unsigned int start, stop, p, pos = 0, encLength;
00766   QCString result;
00767   bool breakLine = FALSE;
00768   const unsigned int maxLen = 75 - 7 - cset.length();
00769 
00770   while (pos < _str.length())
00771   {
00772     start = pos; p = pos;
00773     while (p < _str.length())
00774     {
00775       if (!breakLine && (_str.at(p) == ' ' || dontQuote.find(_str.at(p)) != -1))
00776         start = p + 1;
00777       if (_str.at(p).unicode() >= 128 || _str.at(p).unicode() < 32)
00778         break;
00779       p++;
00780     }
00781     if (breakLine || p < _str.length())
00782     {
00783       while (dontQuote.find(_str.at(start)) != -1) start++;
00784       stop = start;
00785       while (stop < _str.length() && dontQuote.find(_str.at(stop)) == -1)
00786         stop++;
00787       result += _str.mid(pos, start - pos).latin1();
00788       encLength = encodeRFC2047Quoted(codec->fromUnicode(_str.
00789         mid(start, stop - start)), useBase64).length();
00790       breakLine = (encLength > maxLen);
00791       if (breakLine)
00792       {
00793         int dif = (stop - start) / 2;
00794         int step = dif;
00795         while (abs(step) > 1)
00796         {
00797           encLength = encodeRFC2047Quoted(codec->fromUnicode(_str.
00798             mid(start, dif)), useBase64).length();
00799           step = (encLength > maxLen) ? (-abs(step) / 2) : (abs(step) / 2);
00800           dif += step;
00801         }
00802         stop = start + dif;
00803       }
00804       p = stop;
00805       while (p > start && _str.at(p) != ' ') p--;
00806       if (p > start) stop = p;
00807       if (result.right(3) == "?= ") start--;
00808       if (result.right(5) == "?=\n  ") {
00809         start--; result.truncate(result.length() - 1);
00810       }
00811       int lastNewLine = result.findRev("\n ");
00812       if (!result.mid(lastNewLine).stripWhiteSpace().isEmpty()
00813         && result.length() - lastNewLine + encLength + 2 > maxLen)
00814           result += "\n ";
00815       result += "=?";
00816       result += cset;
00817       result += (useBase64) ? "?b?" : "?q?";
00818       result += encodeRFC2047Quoted(codec->fromUnicode(_str.mid(start,
00819         stop - start)), useBase64);
00820       result += "?=";
00821       if (breakLine) result += "\n ";
00822       pos = stop;
00823     } else {
00824       result += _str.mid(pos).latin1();
00825       break;
00826     }
00827   }
00828   return result;
00829 }
00830 
00831 
00832 //-----------------------------------------------------------------------------
00833 QCString KMMsgBase::encodeRFC2231String( const QString& _str,
00834                                          const QCString& charset )
00835 {
00836   if ( _str.isEmpty() )
00837     return QCString();
00838 
00839   QCString cset;
00840   if ( charset.isEmpty() )
00841     cset = QCString( kmkernel->networkCodec()->mimeName() ).lower();
00842   else
00843     cset = charset;
00844   const QTextCodec *codec = codecForName( cset );
00845   QCString latin;
00846   if ( charset == "us-ascii" )
00847     latin = toUsAscii( _str );
00848   else if ( codec )
00849     latin = codec->fromUnicode( _str );
00850   else
00851     latin = _str.local8Bit();
00852 
00853   char *l;
00854   for ( l = latin.data(); *l; ++l ) {
00855     if ( ( *l & 0xE0 == 0 ) || ( *l & 0x80 ) )
00856       // *l is control character or 8-bit char
00857       break;
00858   }
00859   if ( !*l )
00860     return latin;
00861 
00862   QCString result = cset + "''";
00863   for ( l = latin.data(); *l; ++l ) {
00864     bool needsQuoting = ( *l & 0x80 );
00865     if( !needsQuoting ) {
00866       int len = especials.length();
00867       for ( int i = 0; i < len; i++ )
00868         if ( *l == especials[i] ) {
00869           needsQuoting = true;
00870           break;
00871         }
00872     }
00873     if ( needsQuoting ) {
00874       result += '%';
00875       unsigned char hexcode;
00876       hexcode = ( ( *l & 0xF0 ) >> 4 ) + 48;
00877       if ( hexcode >= 58 )
00878         hexcode += 7;
00879       result += hexcode;
00880       hexcode = ( *l & 0x0F ) + 48;
00881       if ( hexcode >= 58 )
00882         hexcode += 7;
00883       result += hexcode;
00884     } else {
00885       result += *l;
00886     }
00887   }
00888   return result;
00889 }
00890 
00891 
00892 //-----------------------------------------------------------------------------
00893 QString KMMsgBase::decodeRFC2231String(const QCString& _str)
00894 {
00895   int p = _str.find('\'');
00896   if (p < 0) return kmkernel->networkCodec()->toUnicode(_str);
00897 
00898   QCString charset = _str.left(p);
00899 
00900   QCString st = _str.mid(_str.findRev('\'') + 1);
00901   char ch, ch2;
00902   p = 0;
00903   while (p < (int)st.length())
00904   {
00905     if (st.at(p) == 37)
00906     {
00907       ch = st.at(p+1) - 48;
00908       if (ch > 16) ch -= 7;
00909       ch2 = st.at(p+2) - 48;
00910       if (ch2 > 16) ch2 -= 7;
00911       st.at(p) = ch * 16 + ch2;
00912       st.remove( p+1, 2 );
00913     }
00914     p++;
00915   }
00916   QString result;
00917   const QTextCodec * codec = codecForName( charset );
00918   if ( !codec )
00919     codec = kmkernel->networkCodec();
00920   return codec->toUnicode( st );
00921 }
00922 
00923 QString KMMsgBase::base64EncodedMD5( const QString & s, bool utf8 ) {
00924   if (s.stripWhiteSpace().isEmpty()) return "";
00925   if ( utf8 )
00926     return base64EncodedMD5( s.stripWhiteSpace().utf8() ); // QCString overload
00927   else
00928     return base64EncodedMD5( s.stripWhiteSpace().latin1() ); // const char * overload
00929 }
00930 
00931 QString KMMsgBase::base64EncodedMD5( const QCString & s ) {
00932   if (s.stripWhiteSpace().isEmpty()) return "";
00933   return base64EncodedMD5( s.stripWhiteSpace().data() );
00934 }
00935 
00936 QString KMMsgBase::base64EncodedMD5( const char * s, int len ) {
00937   if (!s || !len) return "";
00938   static const int Base64EncodedMD5Len = 22;
00939   KMD5 md5( s, len );
00940   return md5.base64Digest().left( Base64EncodedMD5Len );
00941 }
00942 
00943 
00944 //-----------------------------------------------------------------------------
00945 QCString KMMsgBase::autoDetectCharset(const QCString &_encoding, const QStringList &encodingList, const QString &text)
00946 {
00947     QStringList charsets = encodingList;
00948     if (!_encoding.isEmpty())
00949     {
00950        QString currentCharset = QString::fromLatin1(_encoding);
00951        charsets.remove(currentCharset);
00952        charsets.prepend(currentCharset);
00953     }
00954 
00955     QStringList::ConstIterator it = charsets.begin();
00956     for (; it != charsets.end(); ++it)
00957     {
00958        QCString encoding = (*it).latin1();
00959        if (encoding == "locale")
00960           encoding = QCString(kmkernel->networkCodec()->mimeName()).lower();
00961        if (text.isEmpty())
00962          return encoding;
00963        if (encoding == "us-ascii") {
00964          bool ok;
00965          (void) KMMsgBase::toUsAscii(text, &ok);
00966          if (ok)
00967             return encoding;
00968        }
00969        else
00970        {
00971          const QTextCodec *codec = KMMsgBase::codecForName(encoding);
00972          if (!codec) {
00973            kdDebug(5006) << "Auto-Charset: Something is wrong and I can not get a codec. [" << encoding << "]" << endl;
00974          } else {
00975            if (codec->canEncode(text))
00976               return encoding;
00977          }
00978        }
00979     }
00980     return 0;
00981 }
00982 
00983 
00984 //-----------------------------------------------------------------------------
00985 unsigned long KMMsgBase::getMsgSerNum() const
00986 {
00987   unsigned long msn = MessageProperty::serialCache( this );
00988   if (msn)
00989     return msn;
00990   if (mParent) {
00991     int index = mParent->find((KMMsgBase*)this);
00992     msn = kmkernel->msgDict()->getMsgSerNum(mParent, index);
00993     if (msn)
00994       MessageProperty::setSerialCache( this, msn );
00995   }
00996   return msn;
00997 }
00998 
00999 
01000 //-----------------------------------------------------------------------------
01001 bool KMMsgBase::isComplete()
01002 {
01003   return MessageProperty::complete( getMsgSerNum() );
01004 }
01005 
01006 
01007 //-----------------------------------------------------------------------------
01008 void KMMsgBase::setComplete(bool value)
01009 {
01010   MessageProperty::setComplete( getMsgSerNum(), value );
01011   if ( value )
01012     setReadyToShow( true );
01013 }
01014 
01015 //-----------------------------------------------------------------------------
01016 bool KMMsgBase::readyToShow()
01017 {
01018   return MessageProperty::readyToShow( getMsgSerNum() );
01019 }
01020 
01021 
01022 //-----------------------------------------------------------------------------
01023 void KMMsgBase::setReadyToShow(bool value)
01024 {
01025   MessageProperty::setReadyToShow( getMsgSerNum(), value );
01026 }
01027 
01028 
01029 //-----------------------------------------------------------------------------
01030 bool KMMsgBase::transferInProgress()
01031 {
01032   return MessageProperty::transferInProgress( getMsgSerNum() );
01033 }
01034 
01035 
01036 //-----------------------------------------------------------------------------
01037 void KMMsgBase::setTransferInProgress(bool value, bool force)
01038 {
01039   MessageProperty::setTransferInProgress( getMsgSerNum(), value, force );
01040 }
01041 
01042 
01043 //-----------------------------------------------------------------------------
01044 KMMsgAttachmentState KMMsgBase::attachmentState() const
01045 {
01046   KMMsgStatus st = status();
01047   if (st & KMMsgStatusHasAttach)
01048     return KMMsgHasAttachment;
01049   else if (st & KMMsgStatusHasNoAttach)
01050     return KMMsgHasNoAttachment;
01051   else
01052     return KMMsgAttachmentUnknown;
01053 }
01054 
01055 //-----------------------------------------------------------------------------
01056 static void swapEndian(QString &str)
01057 {
01058   uint len = str.length();
01059   str = QDeepCopy<QString>(str);
01060   QChar *unicode = const_cast<QChar*>( str.unicode() );
01061   for (uint i = 0; i < len; i++)
01062     unicode[i] = kmail_swap_16(unicode[i].unicode());
01063 }
01064 
01065 //-----------------------------------------------------------------------------
01066 static int g_chunk_length = 0, g_chunk_offset=0;
01067 static uchar *g_chunk = 0;
01068 
01069 namespace {
01070   template < typename T > void copy_from_stream( T & x ) {
01071     if( g_chunk_offset + int(sizeof(T)) > g_chunk_length ) {
01072       g_chunk_offset = g_chunk_length;
01073       kdDebug( 5006 ) << "This should never happen.. "
01074               << __FILE__ << ":" << __LINE__ << endl;
01075       x = 0;
01076     } else {
01077       // the memcpy is optimized out by the compiler for the values
01078       // of sizeof(T) that is called with
01079       memcpy( &x, g_chunk + g_chunk_offset, sizeof(T) );
01080       g_chunk_offset += sizeof(T);
01081     }
01082   }
01083 }
01084 
01085 //-----------------------------------------------------------------------------
01086 QString KMMsgBase::getStringPart(MsgPartType t) const
01087 {
01088   QString ret;
01089 
01090   g_chunk_offset = 0;
01091   bool using_mmap = FALSE;
01092   bool swapByteOrder = storage()->indexSwapByteOrder();
01093   if (storage()->indexStreamBasePtr()) {
01094     if (g_chunk)
01095     free(g_chunk);
01096     using_mmap = TRUE;
01097     g_chunk = storage()->indexStreamBasePtr() + mIndexOffset;
01098     g_chunk_length = mIndexLength;
01099   } else {
01100     if(!storage()->mIndexStream)
01101       return ret;
01102     if (g_chunk_length < mIndexLength)
01103     g_chunk = (uchar *)realloc(g_chunk, g_chunk_length = mIndexLength);
01104     off_t first_off=ftell(storage()->mIndexStream);
01105     fseek(storage()->mIndexStream, mIndexOffset, SEEK_SET);
01106     fread( g_chunk, mIndexLength, 1, storage()->mIndexStream);
01107     fseek(storage()->mIndexStream, first_off, SEEK_SET);
01108   }
01109 
01110   MsgPartType type;
01111   Q_UINT16 l;
01112   while(g_chunk_offset < mIndexLength) {
01113     Q_UINT32 tmp;
01114     copy_from_stream(tmp);
01115     copy_from_stream(l);
01116     if (swapByteOrder)
01117     {
01118        tmp = kmail_swap_32(tmp);
01119        l = kmail_swap_16(l);
01120     }
01121     type = (MsgPartType) tmp;
01122     if(g_chunk_offset + l > mIndexLength) {
01123     kdDebug(5006) << "This should never happen.. " << __FILE__ << ":" << __LINE__ << endl;
01124     break;
01125     }
01126     if(type == t) {
01127         // This works because the QString constructor does a memcpy.
01128         // Otherwise we would need to be concerned about the alignment.
01129     if(l)
01130         ret = QString((QChar *)(g_chunk + g_chunk_offset), l/2);
01131     break;
01132     }
01133     g_chunk_offset += l;
01134   }
01135   if(using_mmap) {
01136       g_chunk_length = 0;
01137       g_chunk = 0;
01138   }
01139   // Normally we need to swap the byte order because the QStrings are written
01140   // in the style of Qt2 (MSB -> network ordered).
01141   // QStrings in Qt3 expect host ordering.
01142   // On e.g. Intel host ordering is LSB, on e.g. Sparc it is MSB.
01143 
01144 #ifndef WORDS_BIGENDIAN
01145   // #warning Byte order is little endian (swap is true)
01146   swapEndian(ret);
01147 #else
01148   // #warning Byte order is big endian (swap is false)
01149 #endif
01150 
01151   return ret;
01152 }
01153 
01154 //-----------------------------------------------------------------------------
01155 off_t KMMsgBase::getLongPart(MsgPartType t) const
01156 {
01157   off_t ret = 0;
01158 
01159   g_chunk_offset = 0;
01160   bool using_mmap = FALSE;
01161   int sizeOfLong = storage()->indexSizeOfLong();
01162   bool swapByteOrder = storage()->indexSwapByteOrder();
01163   if (storage()->indexStreamBasePtr()) {
01164     if (g_chunk)
01165       free(g_chunk);
01166     using_mmap = TRUE;
01167     g_chunk = storage()->indexStreamBasePtr() + mIndexOffset;
01168     g_chunk_length = mIndexLength;
01169   } else {
01170     if (!storage()->mIndexStream)
01171       return ret;
01172     assert(mIndexLength >= 0);
01173     if (g_chunk_length < mIndexLength)
01174       g_chunk = (uchar *)realloc(g_chunk, g_chunk_length = mIndexLength);
01175     off_t first_off=ftell(storage()->mIndexStream);
01176     fseek(storage()->mIndexStream, mIndexOffset, SEEK_SET);
01177     fread( g_chunk, mIndexLength, 1, storage()->mIndexStream);
01178     fseek(storage()->mIndexStream, first_off, SEEK_SET);
01179   }
01180 
01181   MsgPartType type;
01182   Q_UINT16 l;
01183   while (g_chunk_offset < mIndexLength) {
01184     Q_UINT32 tmp;
01185     copy_from_stream(tmp);
01186     copy_from_stream(l);
01187     if (swapByteOrder)
01188     {
01189        tmp = kmail_swap_32(tmp);
01190        l = kmail_swap_16(l);
01191     }
01192     type = (MsgPartType) tmp;
01193 
01194     if (g_chunk_offset + l > mIndexLength) {
01195       kdDebug(5006) << "This should never happen.. " << __FILE__ << ":" << __LINE__ << endl;
01196       break;
01197     }
01198     if(type == t) {
01199       assert(sizeOfLong == l);
01200       if (sizeOfLong == sizeof(ret))
01201       {
01202      copy_from_stream(ret);
01203          if (swapByteOrder)
01204          {
01205             if (sizeof(ret) == 4)
01206                ret = kmail_swap_32(ret);
01207             else
01208                ret = kmail_swap_64(ret);
01209          }
01210       }
01211       else if (sizeOfLong == 4)
01212       {
01213          // Long is stored as 4 bytes in index file, sizeof(long) = 8
01214          Q_UINT32 ret_32;
01215          copy_from_stream(ret_32);
01216          if (swapByteOrder)
01217             ret_32 = kmail_swap_32(ret_32);
01218          ret = ret_32;
01219       }
01220       else if (sizeOfLong == 8)
01221       {
01222          // Long is stored as 8 bytes in index file, sizeof(long) = 4
01223          Q_UINT32 ret_1;
01224          Q_UINT32 ret_2;
01225          copy_from_stream(ret_1);
01226          copy_from_stream(ret_2);
01227          if (!swapByteOrder)
01228          {
01229             // Index file order is the same as the order of this CPU.
01230 #ifndef WORDS_BIGENDIAN
01231             // Index file order is little endian
01232             ret = ret_1; // We drop the 4 most significant bytes
01233 #else
01234             // Index file order is big endian
01235             ret = ret_2; // We drop the 4 most significant bytes
01236 #endif
01237          }
01238          else
01239          {
01240             // Index file order is different from this CPU.
01241 #ifndef WORDS_BIGENDIAN
01242             // Index file order is big endian
01243             ret = ret_2; // We drop the 4 most significant bytes
01244 #else
01245             // Index file order is little endian
01246             ret = ret_1; // We drop the 4 most significant bytes
01247 #endif
01248             // We swap the result to host order.
01249             ret = kmail_swap_32(ret);
01250          }
01251 
01252       }
01253       break;
01254     }
01255     g_chunk_offset += l;
01256   }
01257   if(using_mmap) {
01258     g_chunk_length = 0;
01259     g_chunk = 0;
01260   }
01261   return ret;
01262 }
01263 
01264 #ifndef WORDS_BIGENDIAN
01265 // We need to use swab to swap bytes to network byte order
01266 #define memcpy_networkorder(to, from, len)  swab((char *)(from), (char *)(to), len)
01267 #else
01268 // We're already in network byte order
01269 #define memcpy_networkorder(to, from, len)  memcpy(to, from, len)
01270 #endif
01271 
01272 #define STORE_DATA_LEN(type, x, len, network_order) do { \
01273     int len2 = (len > 256) ? 256 : len; \
01274     if(csize < (length + (len2 + sizeof(short) + sizeof(MsgPartType)))) \
01275            ret = (uchar *)realloc(ret, csize += len2+sizeof(short)+sizeof(MsgPartType)); \
01276         Q_UINT32 t = (Q_UINT32) type; memcpy(ret+length, &t, sizeof(t)); \
01277         Q_UINT16 l = len2; memcpy(ret+length+sizeof(t), &l, sizeof(l)); \
01278         if (network_order) \
01279            memcpy_networkorder(ret+length+sizeof(t)+sizeof(l), x, len2); \
01280         else \
01281            memcpy(ret+length+sizeof(t)+sizeof(l), x, len2); \
01282         length += len2+sizeof(t)+sizeof(l); \
01283     } while(0)
01284 #define STORE_DATA(type, x) STORE_DATA_LEN(type, &x, sizeof(x), false)
01285 
01286 //-----------------------------------------------------------------------------
01287 const uchar *KMMsgBase::asIndexString(int &length) const
01288 {
01289   unsigned int csize = 256;
01290   static uchar *ret = 0; //different static buffer here for we may use the other buffer in the functions below
01291   if(!ret)
01292     ret = (uchar *)malloc(csize);
01293   length = 0;
01294 
01295   unsigned long tmp;
01296   QString tmp_str;
01297 
01298   //these is at the beginning because it is queried quite often
01299   tmp_str = msgIdMD5().stripWhiteSpace();
01300   STORE_DATA_LEN(MsgIdMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01301   tmp = mLegacyStatus;
01302   STORE_DATA(MsgLegacyStatusPart, tmp);
01303 
01304   //these are completely arbitrary order
01305   tmp_str = fromStrip().stripWhiteSpace();
01306   STORE_DATA_LEN(MsgFromPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01307   tmp_str = subject().stripWhiteSpace();
01308   STORE_DATA_LEN(MsgSubjectPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01309   tmp_str = toStrip().stripWhiteSpace();
01310   STORE_DATA_LEN(MsgToPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01311   tmp_str = replyToIdMD5().stripWhiteSpace();
01312   STORE_DATA_LEN(MsgReplyToIdMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01313   tmp_str = xmark().stripWhiteSpace();
01314   STORE_DATA_LEN(MsgXMarkPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01315   tmp_str = fileName().stripWhiteSpace();
01316   STORE_DATA_LEN(MsgFilePart, tmp_str.unicode(), tmp_str.length() * 2, true);
01317   tmp = msgSize();
01318   STORE_DATA(MsgSizePart, tmp);
01319   tmp = folderOffset();
01320   STORE_DATA(MsgOffsetPart, tmp);
01321   tmp = date();
01322   STORE_DATA(MsgDatePart, tmp);
01323   tmp = (signatureState() << 16) | encryptionState();
01324   STORE_DATA(MsgCryptoStatePart, tmp);
01325   tmp = mdnSentState();
01326   STORE_DATA(MsgMDNSentPart, tmp);
01327 
01328   tmp_str = replyToAuxIdMD5().stripWhiteSpace();
01329   STORE_DATA_LEN(MsgReplyToAuxIdMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01330 
01331   tmp_str = strippedSubjectMD5().stripWhiteSpace();
01332   STORE_DATA_LEN(MsgStrippedSubjectMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01333 
01334   tmp = status();
01335   STORE_DATA(MsgStatusPart, tmp);
01336 
01337   tmp = msgSizeServer();
01338   STORE_DATA(MsgSizeServerPart, tmp);
01339   tmp = UID();
01340   STORE_DATA(MsgUIDPart, tmp);
01341 
01342   return ret;
01343 }
01344 #undef STORE_DATA_LEN
01345 #undef STORE_DATA
01346 
01347 bool KMMsgBase::syncIndexString() const
01348 {
01349   if(!dirty())
01350     return TRUE;
01351   int len;
01352   const uchar *buffer = asIndexString(len);
01353   if (len == mIndexLength) {
01354     Q_ASSERT(storage()->mIndexStream);
01355     fseek(storage()->mIndexStream, mIndexOffset, SEEK_SET);
01356     assert( mIndexOffset > 0 );
01357     fwrite( buffer, len, 1, storage()->mIndexStream);
01358     return TRUE;
01359   }
01360   return FALSE;
01361 }
01362 
01363 static QStringList sReplySubjPrefixes, sForwardSubjPrefixes;
01364 static bool sReplaceSubjPrefix, sReplaceForwSubjPrefix;
01365 
01366 //-----------------------------------------------------------------------------
01367 void KMMsgBase::readConfig()
01368 {
01369   KConfigGroup composerGroup( KMKernel::config(), "Composer" );
01370   sReplySubjPrefixes = composerGroup.readListEntry("reply-prefixes", ',');
01371   if (sReplySubjPrefixes.isEmpty())
01372     sReplySubjPrefixes << "Re\\s*:" << "Re\\[\\d+\\]:" << "Re\\d+:";
01373   sReplaceSubjPrefix = composerGroup.readBoolEntry("replace-reply-prefix", true);
01374   sForwardSubjPrefixes = composerGroup.readListEntry("forward-prefixes", ',');
01375   if (sForwardSubjPrefixes.isEmpty())
01376     sForwardSubjPrefixes << "Fwd:" << "FW:";
01377   sReplaceForwSubjPrefix = composerGroup.readBoolEntry("replace-forward-prefix", true);
01378 }
01379 
01380 //-----------------------------------------------------------------------------
01381 // static
01382 QString KMMsgBase::stripOffPrefixes( const QString& str )
01383 {
01384   return replacePrefixes( str, sReplySubjPrefixes + sForwardSubjPrefixes,
01385                           true, QString::null ).stripWhiteSpace();
01386 }
01387 
01388 //-----------------------------------------------------------------------------
01389 // static
01390 QString KMMsgBase::replacePrefixes( const QString& str,
01391                                     const QStringList& prefixRegExps,
01392                                     bool replace,
01393                                     const QString& newPrefix )
01394 {
01395   bool recognized = false;
01396   // construct a big regexp that
01397   // 1. is anchored to the beginning of str (sans whitespace)
01398   // 2. matches at least one of the part regexps in prefixRegExps
01399   QString bigRegExp = QString::fromLatin1("^(?:\\s+|(?:%1))+\\s*")
01400                       .arg( prefixRegExps.join(")|(?:") );
01401   QRegExp rx( bigRegExp, false /*case insens.*/ );
01402   if ( !rx.isValid() ) {
01403     kdWarning(5006) << "KMMessage::replacePrefixes(): bigRegExp = \""
01404                     << bigRegExp << "\"\n"
01405                     << "prefix regexp is invalid!" << endl;
01406     // try good ole Re/Fwd:
01407     recognized = str.startsWith( newPrefix );
01408   } else { // valid rx
01409     QString tmp = str;
01410     if ( rx.search( tmp ) == 0 ) {
01411       recognized = true;
01412       if ( replace )
01413     return tmp.replace( 0, rx.matchedLength(), newPrefix + ' ' );
01414     }
01415   }
01416   if ( !recognized )
01417     return newPrefix + ' ' + str;
01418   else
01419     return str;
01420 }
01421 
01422 //-----------------------------------------------------------------------------
01423 QString KMMsgBase::cleanSubject() const
01424 {
01425   return cleanSubject( sReplySubjPrefixes + sForwardSubjPrefixes,
01426                true, QString::null ).stripWhiteSpace();
01427 }
01428 
01429 //-----------------------------------------------------------------------------
01430 QString KMMsgBase::cleanSubject( const QStringList & prefixRegExps,
01431                                  bool replace,
01432                                  const QString & newPrefix ) const
01433 {
01434   return KMMsgBase::replacePrefixes( subject(), prefixRegExps, replace,
01435                                      newPrefix );
01436 }
01437 
01438 //-----------------------------------------------------------------------------
01439 QString KMMsgBase::forwardSubject() const {
01440   return cleanSubject( sForwardSubjPrefixes, sReplaceForwSubjPrefix, "Fwd:" );
01441 }
01442 
01443 //-----------------------------------------------------------------------------
01444 QString KMMsgBase::replySubject() const {
01445   return cleanSubject( sReplySubjPrefixes, sReplaceSubjPrefix, "Re:" );
01446 }
KDE Logo
This file is part of the documentation for kmail Library Version 3.3.2.
Documentation copyright © 1996-2004 the KDE developers.
Generated on Wed Mar 23 22:43:52 2005 by doxygen 1.3.9.1 written by Dimitri van Heesch, © 1997-2003