kmail

kmmsgbase.cpp

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