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 bool KMMsgBase::isTodo(void) const
00466 {
00467   KMMsgStatus st = status();
00468   return (st & KMMsgStatusTodo);
00469 }
00470 
00471 //-----------------------------------------------------------------------------
00472 QCString KMMsgBase::statusToStr(const KMMsgStatus status)
00473 {
00474   QCString sstr;
00475   if (status & KMMsgStatusNew) sstr += 'N';
00476   if (status & KMMsgStatusUnread) sstr += 'U';
00477   if (status & KMMsgStatusOld) sstr += 'O';
00478   if (status & KMMsgStatusRead) sstr += 'R';
00479   if (status & KMMsgStatusDeleted) sstr += 'D';
00480   if (status & KMMsgStatusReplied) sstr += 'A';
00481   if (status & KMMsgStatusForwarded) sstr += 'F';
00482   if (status & KMMsgStatusQueued) sstr += 'Q';
00483   if (status & KMMsgStatusSent) sstr += 'S';
00484   if (status & KMMsgStatusFlag) sstr += 'G';
00485   if (status & KMMsgStatusWatched) sstr += 'W';
00486   if (status & KMMsgStatusIgnored) sstr += 'I';
00487   if (status & KMMsgStatusSpam) sstr += 'P';
00488   if (status & KMMsgStatusHam) sstr += 'H';
00489   if (status & KMMsgStatusHasAttach) sstr += 'T';
00490   if (status & KMMsgStatusHasNoAttach) sstr += 'C';
00491 
00492   return sstr;
00493 }
00494 
00495 //-----------------------------------------------------------------------------
00496 QString KMMsgBase::statusToSortRank()
00497 {
00498   QString sstr = "bcbbbbbbb";
00499 
00500   // put watched ones first, then normal ones, ignored ones last
00501   if (status() & KMMsgStatusWatched) sstr[0] = 'a';
00502   if (status() & KMMsgStatusIgnored) sstr[0] = 'c';
00503 
00504   // Second level. One of new, old, read, unread
00505   if (status() & KMMsgStatusNew) sstr[1] = 'a';
00506   if (status() & KMMsgStatusUnread) sstr[1] = 'b';
00507   //if (status() & KMMsgStatusOld) sstr[1] = 'c';
00508   //if (status() & KMMsgStatusRead) sstr[1] = 'c';
00509 
00510   // Third level. In somewhat arbitrary order.
00511   if (status() & KMMsgStatusDeleted) sstr[2] = 'a';
00512   if (status() & KMMsgStatusFlag) sstr[3] = 'a';
00513   if (status() & KMMsgStatusReplied) sstr[4] = 'a';
00514   if (status() & KMMsgStatusForwarded) sstr[5] = 'a';
00515   if (status() & KMMsgStatusQueued) sstr[6] = 'a';
00516   if (status() & KMMsgStatusSent) sstr[7] = 'a';
00517   if (status() & KMMsgStatusHam) sstr[8] = 'a';
00518   if (status() & KMMsgStatusSpam) sstr[8] = 'c';
00519 
00520   return sstr;
00521 }
00522 
00523 
00524 //-----------------------------------------------------------------------------
00525 void KMMsgBase::setDate(const QCString& aDateStr)
00526 {
00527   setDate( KRFCDate::parseDate( aDateStr ) );
00528 }
00529 
00530 
00531 //-----------------------------------------------------------------------------
00532 QString KMMsgBase::dateStr(void) const
00533 {
00534   time_t d = date();
00535   return KMime::DateFormatter::formatDate(KMime::DateFormatter::Fancy, d);
00536 }
00537 
00538 
00539 //-----------------------------------------------------------------------------
00540 QString KMMsgBase::skipKeyword(const QString& aStr, QChar sepChar,
00541                    bool* hasKeyword)
00542 {
00543   unsigned int i = 0, maxChars = 3;
00544   QString str = aStr;
00545 
00546   while (str[0] == ' ') str.remove(0,1);
00547   if (hasKeyword) *hasKeyword=FALSE;
00548 
00549   for (i=0; i < str.length() && i < maxChars; i++)
00550   {
00551     if (str[i] < 'A' || str[i] == sepChar) break;
00552   }
00553 
00554   if (str[i] == sepChar) // skip following spaces too
00555   {
00556     do {
00557       i++;
00558     } while (str[i] == ' ');
00559     if (hasKeyword) *hasKeyword=TRUE;
00560     return str.mid(i);
00561   }
00562   return str;
00563 }
00564 
00565 
00566 //-----------------------------------------------------------------------------
00567 const QTextCodec* KMMsgBase::codecForName(const QCString& _str)
00568 {
00569   if (_str.isEmpty()) return 0;
00570   return KGlobal::charsets()->codecForName(_str.lower());
00571 }
00572 
00573 
00574 //-----------------------------------------------------------------------------
00575 QCString KMMsgBase::toUsAscii(const QString& _str, bool *ok)
00576 {
00577   bool all_ok =true;
00578   QString result = _str;
00579   int len = result.length();
00580   for (int i = 0; i < len; i++)
00581     if (result.at(i).unicode() >= 128) {
00582       result.at(i) = '?';
00583       all_ok = false;
00584     }
00585   if (ok)
00586     *ok = all_ok;
00587   return result.latin1();
00588 }
00589 
00590 
00591 //-----------------------------------------------------------------------------
00592 QStringList KMMsgBase::supportedEncodings(bool usAscii)
00593 {
00594   QStringList encodingNames = KGlobal::charsets()->availableEncodingNames();
00595   QStringList encodings;
00596   QMap<QString,bool> mimeNames;
00597   for (QStringList::Iterator it = encodingNames.begin();
00598     it != encodingNames.end(); it++)
00599   {
00600     QTextCodec *codec = KGlobal::charsets()->codecForName(*it);
00601     QString mimeName = (codec) ? QString(codec->mimeName()).lower() : (*it);
00602     if (mimeNames.find(mimeName) == mimeNames.end())
00603     {
00604       encodings.append(KGlobal::charsets()->languageForEncoding(*it)
00605         + " ( " + mimeName + " )");
00606       mimeNames.insert(mimeName, TRUE);
00607     }
00608   }
00609   encodings.sort();
00610   if (usAscii) encodings.prepend(KGlobal::charsets()
00611     ->languageForEncoding("us-ascii") + " ( us-ascii )");
00612   return encodings;
00613 }
00614 
00615 namespace {
00616   // don't rely on isblank(), which is a GNU extension in
00617   // <cctype>. But if someone wants to write a configure test for
00618   // isblank(), we can then rename this function to isblank and #ifdef
00619   // it's definition...
00620   inline bool isBlank( char ch ) { return ch == ' ' || ch == '\t' ; }
00621 
00622   QCString unfold( const QCString & header ) {
00623     if ( header.isEmpty() )
00624       return QCString();
00625 
00626     QCString result( header.size() ); // size() >= length()+1 and size() is O(1)
00627     char * d = result.data();
00628 
00629     for ( const char * s = header.data() ; *s ; )
00630       if ( *s == '\r' ) { // ignore
00631     ++s;
00632     continue;
00633       } else if ( *s == '\n' ) { // unfold
00634     while ( isBlank( *++s ) );
00635     *d++ = ' ';
00636       } else
00637     *d++ = *s++;
00638 
00639     *d++ = '\0';
00640 
00641     result.truncate( d - result.data() );
00642     return result;
00643   }
00644 }
00645 
00646 
00647 //-----------------------------------------------------------------------------
00648 QString KMMsgBase::decodeRFC2047String(const QCString& aStr)
00649 {
00650   if ( aStr.isEmpty() )
00651     return QString::null;
00652 
00653   const QCString str = unfold( aStr );
00654 
00655   if ( str.isEmpty() )
00656     return QString::null;
00657 
00658   if ( str.find( "=?" ) < 0 )
00659     return kmkernel->networkCodec()->toUnicode( str );
00660 
00661   QString result;
00662   QCString LWSP_buffer;
00663   bool lastWasEncodedWord = false;
00664   static const int maxLen = 200;
00665 
00666   for ( const char * pos = str.data() ; *pos ; ++pos ) {
00667     // collect LWSP after encoded-words,
00668     // because we might need to throw it out
00669     // (when the next word is an encoded-word)
00670     if ( lastWasEncodedWord && isBlank( pos[0] ) ) {
00671       LWSP_buffer += pos[0];
00672       continue;
00673     }
00674     // verbatimly copy normal text
00675     if (pos[0]!='=' || pos[1]!='?') {
00676       result += LWSP_buffer + pos[0];
00677       LWSP_buffer = 0;
00678       lastWasEncodedWord = FALSE;
00679       continue;
00680     }
00681     // found possible encoded-word
00682     const char * const beg = pos;
00683     {
00684       // parse charset name
00685       QCString charset;
00686       int i = 2;
00687       for (pos+=2; i<maxLen && (*pos!='?'&&(*pos==' '||ispunct(*pos)||isalnum(*pos))); ++i) {
00688     charset += *pos;
00689     pos++;
00690       }
00691       if (*pos!='?' || i<4 || i>=maxLen)
00692     goto invalid_encoded_word;
00693 
00694       // get encoding and check delimiting question marks
00695       const char encoding[2] = { pos[1], '\0' };
00696       if (pos[2]!='?' || (encoding[0]!='Q' && encoding[0]!='q' &&
00697               encoding[0]!='B' && encoding[0]!='b'))
00698     goto invalid_encoded_word;
00699       pos+=3; i+=3; // skip ?x?
00700       const char * enc_start = pos;
00701       // search for end of encoded part
00702       while (i<maxLen && *pos && !(*pos=='?' && *(pos+1)=='=')) {
00703     i++;
00704     pos++;
00705       }
00706       if (i>=maxLen || !*pos)
00707     goto invalid_encoded_word;
00708 
00709       // valid encoding: decode and throw away separating LWSP
00710       const KMime::Codec * c = KMime::Codec::codecForName( encoding );
00711       kdFatal( !c, 5006 ) << "No \"" << encoding << "\" codec!?" << endl;
00712 
00713       QByteArray in; in.setRawData( enc_start, pos - enc_start );
00714       const QByteArray enc = c->decode( in );
00715       in.resetRawData( enc_start, pos - enc_start );
00716 
00717       const QTextCodec * codec = codecForName(charset);
00718       if (!codec) codec = kmkernel->networkCodec();
00719       result += codec->toUnicode(enc);
00720       lastWasEncodedWord = true;
00721 
00722       ++pos; // eat '?' (for loop eats '=')
00723       LWSP_buffer = 0;
00724     }
00725     continue;
00726   invalid_encoded_word:
00727     // invalid encoding, keep separating LWSP.
00728     pos = beg;
00729     if ( !LWSP_buffer.isNull() )
00730       result += LWSP_buffer;
00731     result += "=?";
00732     lastWasEncodedWord = false;
00733     ++pos; // eat '?' (for loop eats '=')
00734     LWSP_buffer = 0;
00735   }
00736   return result;
00737 }
00738 
00739 
00740 //-----------------------------------------------------------------------------
00741 static const QCString especials = "()<>@,;:\"/[]?.= \033";
00742 
00743 QCString KMMsgBase::encodeRFC2047Quoted( const QCString & s, bool base64 ) {
00744   const char * codecName = base64 ? "b" : "q" ;
00745   const KMime::Codec * codec = KMime::Codec::codecForName( codecName );
00746   kdFatal( !codec, 5006 ) << "No \"" << codecName << "\" found!?" << endl;
00747   QByteArray in; in.setRawData( s.data(), s.length() );
00748   const QByteArray result = codec->encode( in );
00749   in.resetRawData( s.data(), s.length() );
00750   return QCString( result.data(), result.size() + 1 );
00751 }
00752 
00753 QCString KMMsgBase::encodeRFC2047String(const QString& _str,
00754   const QCString& charset)
00755 {
00756   static const QString dontQuote = "\"()<>,@";
00757 
00758   if (_str.isEmpty()) return QCString();
00759   if (charset == "us-ascii") return toUsAscii(_str);
00760 
00761   QCString cset;
00762   if (charset.isEmpty()) cset = QCString(kmkernel->networkCodec()->mimeName()).lower();
00763     else cset = charset;
00764   const QTextCodec *codec = codecForName(cset);
00765   if (!codec) codec = kmkernel->networkCodec();
00766 
00767   unsigned int nonAscii = 0;
00768   for (unsigned int i = 0; i < _str.length(); i++)
00769     if (_str.at(i).unicode() >= 128) nonAscii++;
00770   bool useBase64 = (nonAscii * 6 > _str.length());
00771 
00772   unsigned int start, stop, p, pos = 0, encLength;
00773   QCString result;
00774   bool breakLine = FALSE;
00775   const unsigned int maxLen = 75 - 7 - cset.length();
00776 
00777   while (pos < _str.length())
00778   {
00779     start = pos; p = pos;
00780     while (p < _str.length())
00781     {
00782       if (!breakLine && (_str.at(p) == ' ' || dontQuote.find(_str.at(p)) != -1))
00783         start = p + 1;
00784       if (_str.at(p).unicode() >= 128 || _str.at(p).unicode() < 32)
00785         break;
00786       p++;
00787     }
00788     if (breakLine || p < _str.length())
00789     {
00790       while (dontQuote.find(_str.at(start)) != -1) start++;
00791       stop = start;
00792       while (stop < _str.length() && dontQuote.find(_str.at(stop)) == -1)
00793         stop++;
00794       result += _str.mid(pos, start - pos).latin1();
00795       encLength = encodeRFC2047Quoted(codec->fromUnicode(_str.
00796         mid(start, stop - start)), useBase64).length();
00797       breakLine = (encLength > maxLen);
00798       if (breakLine)
00799       {
00800         int dif = (stop - start) / 2;
00801         int step = dif;
00802         while (abs(step) > 1)
00803         {
00804           encLength = encodeRFC2047Quoted(codec->fromUnicode(_str.
00805             mid(start, dif)), useBase64).length();
00806           step = (encLength > maxLen) ? (-abs(step) / 2) : (abs(step) / 2);
00807           dif += step;
00808         }
00809         stop = start + dif;
00810       }
00811       p = stop;
00812       while (p > start && _str.at(p) != ' ') p--;
00813       if (p > start) stop = p;
00814       if (result.right(3) == "?= ") start--;
00815       if (result.right(5) == "?=\n  ") {
00816         start--; result.truncate(result.length() - 1);
00817       }
00818       int lastNewLine = result.findRev("\n ");
00819       if (!result.mid(lastNewLine).stripWhiteSpace().isEmpty()
00820         && result.length() - lastNewLine + encLength + 2 > maxLen)
00821           result += "\n ";
00822       result += "=?";
00823       result += cset;
00824       result += (useBase64) ? "?b?" : "?q?";
00825       result += encodeRFC2047Quoted(codec->fromUnicode(_str.mid(start,
00826         stop - start)), useBase64);
00827       result += "?=";
00828       if (breakLine) result += "\n ";
00829       pos = stop;
00830     } else {
00831       result += _str.mid(pos).latin1();
00832       break;
00833     }
00834   }
00835   return result;
00836 }
00837 
00838 
00839 //-----------------------------------------------------------------------------
00840 QCString KMMsgBase::encodeRFC2231String( const QString& _str,
00841                                          const QCString& charset )
00842 {
00843   if ( _str.isEmpty() )
00844     return QCString();
00845 
00846   QCString cset;
00847   if ( charset.isEmpty() )
00848     cset = QCString( kmkernel->networkCodec()->mimeName() ).lower();
00849   else
00850     cset = charset;
00851   const QTextCodec *codec = codecForName( cset );
00852   QCString latin;
00853   if ( charset == "us-ascii" )
00854     latin = toUsAscii( _str );
00855   else if ( codec )
00856     latin = codec->fromUnicode( _str );
00857   else
00858     latin = _str.local8Bit();
00859 
00860   char *l;
00861   for ( l = latin.data(); *l; ++l ) {
00862     if ( ( *l & 0xE0 == 0 ) || ( *l & 0x80 ) )
00863       // *l is control character or 8-bit char
00864       break;
00865   }
00866   if ( !*l )
00867     return latin;
00868 
00869   QCString result = cset + "''";
00870   for ( l = latin.data(); *l; ++l ) {
00871     bool needsQuoting = ( *l & 0x80 );
00872     if( !needsQuoting ) {
00873       int len = especials.length();
00874       for ( int i = 0; i < len; i++ )
00875         if ( *l == especials[i] ) {
00876           needsQuoting = true;
00877           break;
00878         }
00879     }
00880     if ( needsQuoting ) {
00881       result += '%';
00882       unsigned char hexcode;
00883       hexcode = ( ( *l & 0xF0 ) >> 4 ) + 48;
00884       if ( hexcode >= 58 )
00885         hexcode += 7;
00886       result += hexcode;
00887       hexcode = ( *l & 0x0F ) + 48;
00888       if ( hexcode >= 58 )
00889         hexcode += 7;
00890       result += hexcode;
00891     } else {
00892       result += *l;
00893     }
00894   }
00895   return result;
00896 }
00897 
00898 
00899 //-----------------------------------------------------------------------------
00900 QString KMMsgBase::decodeRFC2231String(const QCString& _str)
00901 {
00902   int p = _str.find('\'');
00903   if (p < 0) return kmkernel->networkCodec()->toUnicode(_str);
00904 
00905   QCString charset = _str.left(p);
00906 
00907   QCString st = _str.mid(_str.findRev('\'') + 1);
00908   char ch, ch2;
00909   p = 0;
00910   while (p < (int)st.length())
00911   {
00912     if (st.at(p) == 37)
00913     {
00914       ch = st.at(p+1) - 48;
00915       if (ch > 16) ch -= 7;
00916       ch2 = st.at(p+2) - 48;
00917       if (ch2 > 16) ch2 -= 7;
00918       st.at(p) = ch * 16 + ch2;
00919       st.remove( p+1, 2 );
00920     }
00921     p++;
00922   }
00923   QString result;
00924   const QTextCodec * codec = codecForName( charset );
00925   if ( !codec )
00926     codec = kmkernel->networkCodec();
00927   return codec->toUnicode( st );
00928 }
00929 
00930 QString KMMsgBase::base64EncodedMD5( const QString & s, bool utf8 ) {
00931   if (s.stripWhiteSpace().isEmpty()) return "";
00932   if ( utf8 )
00933     return base64EncodedMD5( s.stripWhiteSpace().utf8() ); // QCString overload
00934   else
00935     return base64EncodedMD5( s.stripWhiteSpace().latin1() ); // const char * overload
00936 }
00937 
00938 QString KMMsgBase::base64EncodedMD5( const QCString & s ) {
00939   if (s.stripWhiteSpace().isEmpty()) return "";
00940   return base64EncodedMD5( s.stripWhiteSpace().data() );
00941 }
00942 
00943 QString KMMsgBase::base64EncodedMD5( const char * s, int len ) {
00944   if (!s || !len) return "";
00945   static const int Base64EncodedMD5Len = 22;
00946   KMD5 md5( s, len );
00947   return md5.base64Digest().left( Base64EncodedMD5Len );
00948 }
00949 
00950 
00951 //-----------------------------------------------------------------------------
00952 QCString KMMsgBase::autoDetectCharset(const QCString &_encoding, const QStringList &encodingList, const QString &text)
00953 {
00954     QStringList charsets = encodingList;
00955     if (!_encoding.isEmpty())
00956     {
00957        QString currentCharset = QString::fromLatin1(_encoding);
00958        charsets.remove(currentCharset);
00959        charsets.prepend(currentCharset);
00960     }
00961 
00962     QStringList::ConstIterator it = charsets.begin();
00963     for (; it != charsets.end(); ++it)
00964     {
00965        QCString encoding = (*it).latin1();
00966        if (encoding == "locale")
00967           encoding = QCString(kmkernel->networkCodec()->mimeName()).lower();
00968        if (text.isEmpty())
00969          return encoding;
00970        if (encoding == "us-ascii") {
00971          bool ok;
00972          (void) KMMsgBase::toUsAscii(text, &ok);
00973          if (ok)
00974             return encoding;
00975        }
00976        else
00977        {
00978          const QTextCodec *codec = KMMsgBase::codecForName(encoding);
00979          if (!codec) {
00980            kdDebug(5006) << "Auto-Charset: Something is wrong and I can not get a codec. [" << encoding << "]" << endl;
00981          } else {
00982            if (codec->canEncode(text))
00983               return encoding;
00984          }
00985        }
00986     }
00987     return 0;
00988 }
00989 
00990 
00991 //-----------------------------------------------------------------------------
00992 unsigned long KMMsgBase::getMsgSerNum() const
00993 {
00994   unsigned long msn = MessageProperty::serialCache( this );
00995   if (msn)
00996     return msn;
00997   if (mParent) {
00998     int index = mParent->find((KMMsgBase*)this);
00999     msn = kmkernel->msgDict()->getMsgSerNum(mParent, index);
01000     if (msn)
01001       MessageProperty::setSerialCache( this, msn );
01002   }
01003   return msn;
01004 }
01005 
01006 
01007 //-----------------------------------------------------------------------------
01008 bool KMMsgBase::readyToShow()
01009 {
01010   return MessageProperty::readyToShow( getMsgSerNum() );
01011 }
01012 
01013 
01014 //-----------------------------------------------------------------------------
01015 void KMMsgBase::setReadyToShow(bool value)
01016 {
01017   MessageProperty::setReadyToShow( getMsgSerNum(), value );
01018 }
01019 
01020 
01021 //-----------------------------------------------------------------------------
01022 bool KMMsgBase::transferInProgress()
01023 {
01024   return MessageProperty::transferInProgress( getMsgSerNum() );
01025 }
01026 
01027 
01028 //-----------------------------------------------------------------------------
01029 void KMMsgBase::setTransferInProgress(bool value, bool force)
01030 {
01031   MessageProperty::setTransferInProgress( getMsgSerNum(), value, force );
01032 }
01033 
01034 
01035 //-----------------------------------------------------------------------------
01036 KMMsgAttachmentState KMMsgBase::attachmentState() const
01037 {
01038   KMMsgStatus st = status();
01039   if (st & KMMsgStatusHasAttach)
01040     return KMMsgHasAttachment;
01041   else if (st & KMMsgStatusHasNoAttach)
01042     return KMMsgHasNoAttachment;
01043   else
01044     return KMMsgAttachmentUnknown;
01045 }
01046 
01047 //-----------------------------------------------------------------------------
01048 static void swapEndian(QString &str)
01049 {
01050   uint len = str.length();
01051   str = QDeepCopy<QString>(str);
01052   QChar *unicode = const_cast<QChar*>( str.unicode() );
01053   for (uint i = 0; i < len; i++)
01054     unicode[i] = kmail_swap_16(unicode[i].unicode());
01055 }
01056 
01057 //-----------------------------------------------------------------------------
01058 static int g_chunk_length = 0, g_chunk_offset=0;
01059 static uchar *g_chunk = 0;
01060 
01061 namespace {
01062   template < typename T > void copy_from_stream( T & x ) {
01063     if( g_chunk_offset + int(sizeof(T)) > g_chunk_length ) {
01064       g_chunk_offset = g_chunk_length;
01065       kdDebug( 5006 ) << "This should never happen.. "
01066               << __FILE__ << ":" << __LINE__ << endl;
01067       x = 0;
01068     } else {
01069       // the memcpy is optimized out by the compiler for the values
01070       // of sizeof(T) that is called with
01071       memcpy( &x, g_chunk + g_chunk_offset, sizeof(T) );
01072       g_chunk_offset += sizeof(T);
01073     }
01074   }
01075 }
01076 
01077 //-----------------------------------------------------------------------------
01078 QString KMMsgBase::getStringPart(MsgPartType t) const
01079 {
01080   QString ret;
01081 
01082   g_chunk_offset = 0;
01083   bool using_mmap = FALSE;
01084   bool swapByteOrder = storage()->indexSwapByteOrder();
01085   if (storage()->indexStreamBasePtr()) {
01086     if (g_chunk)
01087     free(g_chunk);
01088     using_mmap = TRUE;
01089     g_chunk = storage()->indexStreamBasePtr() + mIndexOffset;
01090     g_chunk_length = mIndexLength;
01091   } else {
01092     if(!storage()->mIndexStream)
01093       return ret;
01094     if (g_chunk_length < mIndexLength)
01095     g_chunk = (uchar *)realloc(g_chunk, g_chunk_length = mIndexLength);
01096     off_t first_off=ftell(storage()->mIndexStream);
01097     fseek(storage()->mIndexStream, mIndexOffset, SEEK_SET);
01098     fread( g_chunk, mIndexLength, 1, storage()->mIndexStream);
01099     fseek(storage()->mIndexStream, first_off, SEEK_SET);
01100   }
01101 
01102   MsgPartType type;
01103   Q_UINT16 l;
01104   while(g_chunk_offset < mIndexLength) {
01105     Q_UINT32 tmp;
01106     copy_from_stream(tmp);
01107     copy_from_stream(l);
01108     if (swapByteOrder)
01109     {
01110        tmp = kmail_swap_32(tmp);
01111        l = kmail_swap_16(l);
01112     }
01113     type = (MsgPartType) tmp;
01114     if(g_chunk_offset + l > mIndexLength) {
01115     kdDebug(5006) << "This should never happen.. " << __FILE__ << ":" << __LINE__ << endl;
01116     break;
01117     }
01118     if(type == t) {
01119         // This works because the QString constructor does a memcpy.
01120         // Otherwise we would need to be concerned about the alignment.
01121     if(l)
01122         ret = QString((QChar *)(g_chunk + g_chunk_offset), l/2);
01123     break;
01124     }
01125     g_chunk_offset += l;
01126   }
01127   if(using_mmap) {
01128       g_chunk_length = 0;
01129       g_chunk = 0;
01130   }
01131   // Normally we need to swap the byte order because the QStrings are written
01132   // in the style of Qt2 (MSB -> network ordered).
01133   // QStrings in Qt3 expect host ordering.
01134   // On e.g. Intel host ordering is LSB, on e.g. Sparc it is MSB.
01135 
01136 #ifndef WORDS_BIGENDIAN
01137   // #warning Byte order is little endian (swap is true)
01138   swapEndian(ret);
01139 #else
01140   // #warning Byte order is big endian (swap is false)
01141 #endif
01142 
01143   return ret;
01144 }
01145 
01146 //-----------------------------------------------------------------------------
01147 off_t KMMsgBase::getLongPart(MsgPartType t) const
01148 {
01149   off_t ret = 0;
01150 
01151   g_chunk_offset = 0;
01152   bool using_mmap = FALSE;
01153   int sizeOfLong = storage()->indexSizeOfLong();
01154   bool swapByteOrder = storage()->indexSwapByteOrder();
01155   if (storage()->indexStreamBasePtr()) {
01156     if (g_chunk)
01157       free(g_chunk);
01158     using_mmap = TRUE;
01159     g_chunk = storage()->indexStreamBasePtr() + mIndexOffset;
01160     g_chunk_length = mIndexLength;
01161   } else {
01162     if (!storage()->mIndexStream)
01163       return ret;
01164     assert(mIndexLength >= 0);
01165     if (g_chunk_length < mIndexLength)
01166       g_chunk = (uchar *)realloc(g_chunk, g_chunk_length = mIndexLength);
01167     off_t first_off=ftell(storage()->mIndexStream);
01168     fseek(storage()->mIndexStream, mIndexOffset, SEEK_SET);
01169     fread( g_chunk, mIndexLength, 1, storage()->mIndexStream);
01170     fseek(storage()->mIndexStream, first_off, SEEK_SET);
01171   }
01172 
01173   MsgPartType type;
01174   Q_UINT16 l;
01175   while (g_chunk_offset < mIndexLength) {
01176     Q_UINT32 tmp;
01177     copy_from_stream(tmp);
01178     copy_from_stream(l);
01179     if (swapByteOrder)
01180     {
01181        tmp = kmail_swap_32(tmp);
01182        l = kmail_swap_16(l);
01183     }
01184     type = (MsgPartType) tmp;
01185 
01186     if (g_chunk_offset + l > mIndexLength) {
01187       kdDebug(5006) << "This should never happen.. " << __FILE__ << ":" << __LINE__ << endl;
01188       break;
01189     }
01190     if(type == t) {
01191       assert(sizeOfLong == l);
01192       if (sizeOfLong == sizeof(ret))
01193       {
01194      copy_from_stream(ret);
01195          if (swapByteOrder)
01196          {
01197             if (sizeof(ret) == 4)
01198                ret = kmail_swap_32(ret);
01199             else
01200                ret = kmail_swap_64(ret);
01201          }
01202       }
01203       else if (sizeOfLong == 4)
01204       {
01205          // Long is stored as 4 bytes in index file, sizeof(long) = 8
01206          Q_UINT32 ret_32;
01207          copy_from_stream(ret_32);
01208          if (swapByteOrder)
01209             ret_32 = kmail_swap_32(ret_32);
01210          ret = ret_32;
01211       }
01212       else if (sizeOfLong == 8)
01213       {
01214          // Long is stored as 8 bytes in index file, sizeof(long) = 4
01215          Q_UINT32 ret_1;
01216          Q_UINT32 ret_2;
01217          copy_from_stream(ret_1);
01218          copy_from_stream(ret_2);
01219          if (!swapByteOrder)
01220          {
01221             // Index file order is the same as the order of this CPU.
01222 #ifndef WORDS_BIGENDIAN
01223             // Index file order is little endian
01224             ret = ret_1; // We drop the 4 most significant bytes
01225 #else
01226             // Index file order is big endian
01227             ret = ret_2; // We drop the 4 most significant bytes
01228 #endif
01229          }
01230          else
01231          {
01232             // Index file order is different from this CPU.
01233 #ifndef WORDS_BIGENDIAN
01234             // Index file order is big endian
01235             ret = ret_2; // We drop the 4 most significant bytes
01236 #else
01237             // Index file order is little endian
01238             ret = ret_1; // We drop the 4 most significant bytes
01239 #endif
01240             // We swap the result to host order.
01241             ret = kmail_swap_32(ret);
01242          }
01243 
01244       }
01245       break;
01246     }
01247     g_chunk_offset += l;
01248   }
01249   if(using_mmap) {
01250     g_chunk_length = 0;
01251     g_chunk = 0;
01252   }
01253   return ret;
01254 }
01255 
01256 #ifndef WORDS_BIGENDIAN
01257 // We need to use swab to swap bytes to network byte order
01258 #define memcpy_networkorder(to, from, len)  swab((char *)(from), (char *)(to), len)
01259 #else
01260 // We're already in network byte order
01261 #define memcpy_networkorder(to, from, len)  memcpy(to, from, len)
01262 #endif
01263 
01264 #define STORE_DATA_LEN(type, x, len, network_order) do { \
01265     int len2 = (len > 256) ? 256 : len; \
01266     if(csize < (length + (len2 + sizeof(short) + sizeof(MsgPartType)))) \
01267            ret = (uchar *)realloc(ret, csize += len2+sizeof(short)+sizeof(MsgPartType)); \
01268         Q_UINT32 t = (Q_UINT32) type; memcpy(ret+length, &t, sizeof(t)); \
01269         Q_UINT16 l = len2; memcpy(ret+length+sizeof(t), &l, sizeof(l)); \
01270         if (network_order) \
01271            memcpy_networkorder(ret+length+sizeof(t)+sizeof(l), x, len2); \
01272         else \
01273            memcpy(ret+length+sizeof(t)+sizeof(l), x, len2); \
01274         length += len2+sizeof(t)+sizeof(l); \
01275     } while(0)
01276 #define STORE_DATA(type, x) STORE_DATA_LEN(type, &x, sizeof(x), false)
01277 
01278 //-----------------------------------------------------------------------------
01279 const uchar *KMMsgBase::asIndexString(int &length) const
01280 {
01281   unsigned int csize = 256;
01282   static uchar *ret = 0; //different static buffer here for we may use the other buffer in the functions below
01283   if(!ret)
01284     ret = (uchar *)malloc(csize);
01285   length = 0;
01286 
01287   unsigned long tmp;
01288   QString tmp_str;
01289 
01290   //these is at the beginning because it is queried quite often
01291   tmp_str = msgIdMD5().stripWhiteSpace();
01292   STORE_DATA_LEN(MsgIdMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01293   tmp = mLegacyStatus;
01294   STORE_DATA(MsgLegacyStatusPart, tmp);
01295 
01296   //these are completely arbitrary order
01297   tmp_str = fromStrip().stripWhiteSpace();
01298   STORE_DATA_LEN(MsgFromPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01299   tmp_str = subject().stripWhiteSpace();
01300   STORE_DATA_LEN(MsgSubjectPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01301   tmp_str = toStrip().stripWhiteSpace();
01302   STORE_DATA_LEN(MsgToPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01303   tmp_str = replyToIdMD5().stripWhiteSpace();
01304   STORE_DATA_LEN(MsgReplyToIdMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01305   tmp_str = xmark().stripWhiteSpace();
01306   STORE_DATA_LEN(MsgXMarkPart, tmp_str.unicode(), tmp_str.length() * 2, true);
01307   tmp_str = fileName().stripWhiteSpace();
01308   STORE_DATA_LEN(MsgFilePart, tmp_str.unicode(), tmp_str.length() * 2, true);
01309   tmp = msgSize();
01310   STORE_DATA(MsgSizePart, tmp);
01311   tmp = folderOffset();
01312   STORE_DATA(MsgOffsetPart, tmp);
01313   tmp = date();
01314   STORE_DATA(MsgDatePart, tmp);
01315   tmp = (signatureState() << 16) | encryptionState();
01316   STORE_DATA(MsgCryptoStatePart, tmp);
01317   tmp = mdnSentState();
01318   STORE_DATA(MsgMDNSentPart, tmp);
01319 
01320   tmp_str = replyToAuxIdMD5().stripWhiteSpace();
01321   STORE_DATA_LEN(MsgReplyToAuxIdMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01322 
01323   tmp_str = strippedSubjectMD5().stripWhiteSpace();
01324   STORE_DATA_LEN(MsgStrippedSubjectMD5Part, tmp_str.unicode(), tmp_str.length() * 2, true);
01325 
01326   tmp = status();
01327   STORE_DATA(MsgStatusPart, tmp);
01328 
01329   tmp = msgSizeServer();
01330   STORE_DATA(MsgSizeServerPart, tmp);
01331   tmp = UID();
01332   STORE_DATA(MsgUIDPart, tmp);
01333 
01334   return ret;
01335 }
01336 #undef STORE_DATA_LEN
01337 #undef STORE_DATA
01338 
01339 bool KMMsgBase::syncIndexString() const
01340 {
01341   if(!dirty())
01342     return TRUE;
01343   int len;
01344   const uchar *buffer = asIndexString(len);
01345   if (len == mIndexLength) {
01346     Q_ASSERT(storage()->mIndexStream);
01347     fseek(storage()->mIndexStream, mIndexOffset, SEEK_SET);
01348     assert( mIndexOffset > 0 );
01349     fwrite( buffer, len, 1, storage()->mIndexStream);
01350     return TRUE;
01351   }
01352   return FALSE;
01353 }
01354 
01355 static QStringList sReplySubjPrefixes, sForwardSubjPrefixes;
01356 static bool sReplaceSubjPrefix, sReplaceForwSubjPrefix;
01357 
01358 //-----------------------------------------------------------------------------
01359 void KMMsgBase::readConfig()
01360 {
01361   KConfigGroup composerGroup( KMKernel::config(), "Composer" );
01362   sReplySubjPrefixes = composerGroup.readListEntry("reply-prefixes", ',');
01363   if (sReplySubjPrefixes.isEmpty())
01364     sReplySubjPrefixes << "Re\\s*:" << "Re\\[\\d+\\]:" << "Re\\d+:";
01365   sReplaceSubjPrefix = composerGroup.readBoolEntry("replace-reply-prefix", true);
01366   sForwardSubjPrefixes = composerGroup.readListEntry("forward-prefixes", ',');
01367   if (sForwardSubjPrefixes.isEmpty())
01368     sForwardSubjPrefixes << "Fwd:" << "FW:";
01369   sReplaceForwSubjPrefix = composerGroup.readBoolEntry("replace-forward-prefix", true);
01370 }
01371 
01372 //-----------------------------------------------------------------------------
01373 // static
01374 QString KMMsgBase::stripOffPrefixes( const QString& str )
01375 {
01376   return replacePrefixes( str, sReplySubjPrefixes + sForwardSubjPrefixes,
01377                           true, QString::null ).stripWhiteSpace();
01378 }
01379 
01380 //-----------------------------------------------------------------------------
01381 // static
01382 QString KMMsgBase::replacePrefixes( const QString& str,
01383                                     const QStringList& prefixRegExps,
01384                                     bool replace,
01385                                     const QString& newPrefix )
01386 {
01387   bool recognized = false;
01388   // construct a big regexp that
01389   // 1. is anchored to the beginning of str (sans whitespace)
01390   // 2. matches at least one of the part regexps in prefixRegExps
01391   QString bigRegExp = QString::fromLatin1("^(?:\\s+|(?:%1))+\\s*")
01392                       .arg( prefixRegExps.join(")|(?:") );
01393   QRegExp rx( bigRegExp, false /*case insens.*/ );
01394   if ( !rx.isValid() ) {
01395     kdWarning(5006) << "KMMessage::replacePrefixes(): bigRegExp = \""
01396                     << bigRegExp << "\"\n"
01397                     << "prefix regexp is invalid!" << endl;
01398     // try good ole Re/Fwd:
01399     recognized = str.startsWith( newPrefix );
01400   } else { // valid rx
01401     QString tmp = str;
01402     if ( rx.search( tmp ) == 0 ) {
01403       recognized = true;
01404       if ( replace )
01405     return tmp.replace( 0, rx.matchedLength(), newPrefix + ' ' );
01406     }
01407   }
01408   if ( !recognized )
01409     return newPrefix + ' ' + str;
01410   else
01411     return str;
01412 }
01413 
01414 //-----------------------------------------------------------------------------
01415 QString KMMsgBase::cleanSubject() const
01416 {
01417   return cleanSubject( sReplySubjPrefixes + sForwardSubjPrefixes,
01418                true, QString::null ).stripWhiteSpace();
01419 }
01420 
01421 //-----------------------------------------------------------------------------
01422 QString KMMsgBase::cleanSubject( const QStringList & prefixRegExps,
01423                                  bool replace,
01424                                  const QString & newPrefix ) const
01425 {
01426   return KMMsgBase::replacePrefixes( subject(), prefixRegExps, replace,
01427                                      newPrefix );
01428 }
01429 
01430 //-----------------------------------------------------------------------------
01431 QString KMMsgBase::forwardSubject() const {
01432   return cleanSubject( sForwardSubjPrefixes, sReplaceForwSubjPrefix, "Fwd:" );
01433 }
01434 
01435 //-----------------------------------------------------------------------------
01436 QString KMMsgBase::replySubject() const {
01437   return cleanSubject( sReplySubjPrefixes, sReplaceSubjPrefix, "Re:" );
01438 }
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 Jan 31 15:55:05 2007 by doxygen 1.4.2 written by Dimitri van Heesch, © 1997-2003