summaryrefslogtreecommitdiffstats
path: root/kshowmail/configelem.cpp
blob: 9ac5f0f66641e40bcbd8fbb4ec18b4c601d75d6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
/***************************************************************************
                          ConfigElem.cpp  -  description
                             -------------------
    begin                : Tue May 9 2000
    copyright            : (C) 2000-2001 by Eggert Ehmke
    email                : [email protected]
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "configelem.h"

int const ConfigElem::continueShowHeaders( 0 );
int const ConfigElem::cancelShowHeaders( 1 );


ConfigElem::ConfigElem( ) : TQObject()
{
  //initialize account
  init();

  //set default values
  m_url.setProtocol( "pop3" );
  m_url.setPort( 110 );
  m_bActive = false;
  appConfig = NULL;
  m_strAccount = "";
}

ConfigElem::ConfigElem( ConfigList* config ) : TQObject()
{
  //initialize account
  init();

  m_url.setProtocol( "pop3" );
  m_url.setPort (110);

  m_bActive = false;

  appConfig = config;

}

ConfigElem::ConfigElem( ConfigElem* pElem ) : TQObject()
{
  //initialize account
  init();

  //set active by default
  m_bActive = pElem->isActive();

  //copy some interesting stuff from the sample
  //the url object contains all necessary information about the server
  m_strAccount = pElem->getAccountName();
  m_url = pElem->getURL();
  appConfig = pElem->appConfig;

}

ConfigElem::ConfigElem( ConfigList* config, const TQString& account ) : TQObject()
{
  //initialize account
  init();

  //set account name
  m_strAccount = account;

  //deactivate it by default
  m_bActive = false;

  //set the pointer to the general app configuration
  appConfig = config;
}

void ConfigElem::init( )
{
  //initialize timeout timer
  pop3Timer = new TQTimer( this );
  connect( pop3Timer, TQ_SIGNAL( timeout() ), this, TQ_SLOT( slotTimeout() ) );

  //state is idle
  state = AccountIdle;

  //create new empty mail list
  m_pshowrecord = new ShowRecord();

  //the account has no appropriate account list view item yet
  m_pViewItem = NULL;

  //set default values
  PasswordStorage = DEFAULT_ACCOUNT_PASSWORD_STORAGE;
  filterApplied = false;
  deletionPerformedByFilters = false;
  refreshPerformedByFilters = false;
  downloadActionsInvoked = false;

  //initialize counters
  moveCounter = 0;
  nmbDeletedMailsLastRefresh = 0;
  nmbDeletedMailsLastStart = 0;
  nmbMovedMailsLastRefresh = 0;
  nmbMovedMailsLastStart = 0;
  nmbIgnoredMails = 0;
}


ConfigElem::~ConfigElem()
{
  // do not delete m_pshowrecord here
}

void ConfigElem::saveOptions( TQDomDocument& doc, TQDomElement& parent )
{
  //get application config
  TDEConfig* config = TDEApplication::kApplication()->config();

  //save the active state
  config->setGroup( getAccountName() );
  config->writeEntry( CONFIG_ENTRY_ACCOUNT_ACTIVE, m_bActive );
  config->sync();

  //save the stored mails inside this account
  parent.setAttribute( ATTRIBUTE_ACCOUNT_NAME, m_strAccount );
  m_pshowrecord->saveOptions( doc, parent );
}

void ConfigElem::readStoredMails( TQDomElement& parent )
{
  //get mails
  m_pshowrecord->readStoredMails( parent );
}


int ConfigElem::count()
{
  return m_pshowrecord->count();
}

bool ConfigElem::isActive( ) const
{
  return m_bActive;
}

void ConfigElem::setActive( bool active )
{
  m_bActive = active;
}

TQString ConfigElem::getAccountName( ) const
{
  return m_strAccount;
}

void ConfigElem::setAccountName( TQString name )
{
  if( name != NULL )
    m_strAccount = name;
}

TQString ConfigElem::getPassword( ) const
{
  return m_url.pass();
}

void ConfigElem::setPassword( const TQString& password )
{
    m_url.setPass( password );
}

KURL ConfigElem::getURL( ) const
{
  return m_url;
}

bool ConfigElem::hasPassword( ) const
{
  return m_url.hasPass();
}

void ConfigElem::setListViewItem( TQListViewItem* item )
{
  m_pViewItem = item;
}

TQListViewItem * ConfigElem::getListViewItem( )
{
  return m_pViewItem;
}

bool ConfigElem::isSelected( ) const
{
  if( m_pViewItem == NULL )

    return false;

  else

    return m_pViewItem->isSelected();
}

void ConfigElem::clearMailList( )
{
  if( m_pshowrecord == NULL )
    //there is no mail list yet, create a one
    m_pshowrecord = new ShowRecord;
  else
    //clear the existing mail list
    m_pshowrecord->clear();
}

void ConfigElem::setHost( const TQString& host )
{
  m_url.setHost( host );
}

void ConfigElem::setProtocol( const TQString& protocol )
{
  m_url.setProtocol( protocol );
}

void ConfigElem::setPort( unsigned short int port )
{
  m_url.setPort( port );
}

void ConfigElem::setUser( const TQString & user )
{
  m_url.setUser( user );
}

TQString ConfigElem::getUser( ) const
{
  return m_url.user();
}

TQString ConfigElem::getHost( ) const
{
  return m_url.host();
}

void ConfigElem::deleteSelectedMails( )
{
  //return if this account has no selected mails or
  //the account is not idle or the account is not active
  if( !m_pshowrecord->hasSelectedMails() || state != AccountIdle || !isActive() )
  {
    emit sigDeleteReady( m_strAccount );
    return;
  }

  //check whether we have a password for this account
  //if not, ask for it
  //return when no password is available
  if( !assertPassword() )
  {
    emit sigDeleteReady( m_strAccount );
    return;
  }

  //get the numbers of all selected mails
  MailsToDelete = m_pshowrecord->getSelectedMails();
  if( MailsToDelete.empty() )
  {
    kdError() << "ConfigElem::deleteSelectedMails (Account " << m_strAccount << "): The account has selected mails to delete but ShowRecord::getSelectedMails has returned an empty list." << endl;
    emit sigDeleteReady( m_strAccount );
    return;
  }

  //set account state
  state = AccountDeleting;

  //start the deleting of all mails in MailsToDelete
  deleteNextMail();
}

bool ConfigElem::assertPassword( bool force )
{
  //is a password stored?
  if ( !hasPassword() || force )
  {
    //no password found, we will ask the user!
    //set normal cursor
    while( TQApplication::overrideCursor() )
      TQApplication::restoreOverrideCursor();

    TQString password;      //for the password dialog to store the password
    int result = KPasswordDialog::getPassword( password, i18n( "Please type in the password for %1" ).arg( getAccountName() ) );

    //set waiting cursor
    TQApplication::setOverrideCursor( TQt::waitCursor );

    //let's look, what the user has done :o)
    if( result == KPasswordDialog::Accepted )
    {
      //the user has clicked OK in the password dialog
      //store the password
      setPassword( password );

      //save password in file or TDEWallet
      TDEConfig* config = TDEApplication::kApplication()->config();
      config->setGroup( getAccountName() );

      if( PasswordStorage == CONFIG_VALUE_ACCOUNT_PASSWORD_SAVE_FILE )
        config->writeEntry( CONFIG_ENTRY_ACCOUNT_PASSWORD, crypt( m_url ) );
      else
        config->writeEntry( CONFIG_ENTRY_ACCOUNT_PASSWORD, TQString::null );

      if( PasswordStorage == CONFIG_VALUE_ACCOUNT_PASSWORD_SAVE_TDEWALLET )
        TDEWalletAccess::savePassword( getAccountName(), m_url.pass() );

      config->sync();

      //emit configuration changed signal
      emit ( sigConfigChanged() );

      //tell we have a password
      return true;
    }
    else
      //the user has clicked Cancel in the password dialog; we don't have a password
      return false;
  }
  else
    //we have already a password for this account
    return true;

}

void ConfigElem::deleteNextMail( )
{
  //if the list of mails to delete is empty, finalize the deletion and return
  if( MailsToDelete.empty() )
  {
    if( deletionPerformedByFilters )
    {
      applyFiltersDeleted();
    }
    else
    {
      commitDeletion();
    }
    return;
  }

  //start job
  startKIOJob( TQString( "/remove/%1" ).arg( *MailsToDelete.begin() ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotMailDeleted( TDEIO::Job* ) ) );
}

void ConfigElem::slotMailDeleted( TDEIO::Job* job )
{
  //stop timeout timer
  pop3Timer->stop();

  //check for errors
  //if an error is occured, the deletion will be canceled
  //or will ask for a new password
  if( job->error() == TDEIO::ERR_COULD_NOT_LOGIN )
  {
    //login failed, ask for a new password
    job->showErrorDialog();
    bool res = assertPassword( true );
    if( res == false )
    {
      //we have not got a new password; cancel delete
      if( deletionPerformedByFilters )
      {
        applyFiltersDeleted();
      }
      else
      {
        slotFinalizeDeletion( NULL );
      }
      return;
    }
    //if we have got a new password, it jumps to the end of the if-statement
  }
  else if( job->error() != 0 )
  {
    //unknown error, show message and cancel delete
    job->showErrorDialog();
    if( deletionPerformedByFilters )
    {
      applyFiltersDeleted();
    }
    else
    {
      slotFinalizeDeletion( NULL );
    }
    return;
  }
  else
  {
    //operation was successful
    //remove the deleted mail from the internal mail list
    m_pshowrecord->removeMail( *MailsToDelete.begin() );

    //remove the first item of the list of mails to delete
    MailsToDelete.remove( MailsToDelete.begin() );

    //if the list of mails to delete is empty, finalize the deletion and return
    if( MailsToDelete.empty() )
    {
      if( deletionPerformedByFilters )
      {
        applyFiltersDeleted();
      }
      else
      {
        commitDeletion();
      }
      return;
    }
  }

  //delete next mail in list
  deleteNextMail();


}

void ConfigElem::slotFinalizeDeletion( TDEIO::Job* )
{
  //stop timeout time
  pop3Timer->stop();

  //set account state to idle
  state = AccountIdle;

  //emit signal to report the deletion is ready
  emit sigDeleteReady( m_strAccount );
}

void ConfigElem::startKIOJob( const TQString & path )
{
  TDEIO::MetaData options;           //options for the pop3 job

  //set options
  options.insert( "progress", "off" );
  options.insert( "pipelining", "off" );

  if( useTLS )
    options.insert( "tls", "on" );
  else
    options.insert( "tls", "off" );

  //Where is secure login?
  //I have decided against a configurable secure login because the used POP3 tdeioslave
  //always tries to login with APOP, if the server has sent a timestap (inside of the greeting string) for this authentification type.
  //It just follows the auth-metadata, if the server doesn't support APOP (no timestamp inside of the greeting string).
  //But I think, there is no server, which support a SASL authentification without also provide APOP.
  //Ulrich Weigelt

  //set the given command and parameters
  m_url.setPath( path );

  //print debug message
  kdDebug() << "ConfigElem::startKIOJob: start TDEIO job on URL " << m_url.url() << endl;

  //start the job and get handle to it
  pop3Job = TDEIO::get( m_url, false, false );

  //put options to the job
  pop3Job->addMetaData( options );

  //start timeout timer
  pop3Timer->start( getTimeoutTime() * 1000, true );
}

Types::AccountState_Type ConfigElem::getState( )
{
  return state;
}

void ConfigElem::commitDeletion( )
{
  //start job to commit
  startKIOJob( TQString( "/commit" ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotFinalizeDeletion( TDEIO::Job* ) ) );
}

unsigned int ConfigElem::getTimeoutTime( )
{
  //return default time, if the configuration is not accessable
  if( appConfig == NULL )
    return DEFAULT_TIMEOUT_TIME;

  //get time from configuration
  unsigned int time = appConfig->getTimeoutTime();

  //take minimum time, if get time is less
  if( time < MINIMUM_TIMEOUT_TIME )
    time = MINIMUM_TIMEOUT_TIME;

  return time;
}

void ConfigElem::slotTimeout( )
{
  //kill a running job
  if( pop3Job != NULL )
    pop3Job->kill( true );

  //show error message (during refresh if desired only)
  kdError() << "Timeout error!" << endl;

  if( state != AccountRefreshing || appConfig->showConnectionErrors() )
    KMessageBox::error( NULL, TQString( i18n( "Time out on %1. The operation could not be finished on time" ) ).arg( m_strAccount ), i18n( "Time Out" ) );

  //call the appropriate finalize methode
  switch( state )
  {
    case AccountIdle        : break;
    case AccountDeleting    : slotFinalizeDeletion( NULL ); break;
    case AccountDownloading : slotFinalizeShowMail( NULL ); break;
    case AccountRefreshing  : cancelRefresh(); break;

    default : break;
  }
}

TQStringList ConfigElem::getSelectedSubjects( ) const
{
  return m_pshowrecord->getSelectedSubjects();
}

bool ConfigElem::hasSelectedMails( )
{
  return m_pshowrecord->hasSelectedMails();
}

void ConfigElem::showSelectedMails( )
{
  //return if this account has no selected mails or
  //the account is not idle or the account is not active
  if( !m_pshowrecord->hasSelectedMails() || state != AccountIdle || !isActive() )
  {
    emit sigShowBodiesReady( m_strAccount );
    return;
  }

  //check whether we have a password for this account
  //if not, ask for it
  //return when no password is available
  if( !assertPassword() )
  {
    emit sigShowBodiesReady( m_strAccount );
    return;
  }

  //get the numbers of all selected mails
  MailsToShow = m_pshowrecord->getSelectedMails();
  if( MailsToShow.empty() )
  {
    kdError() << "ConfigElem::showSelectedMails (Account " << m_strAccount << "): The account has selected mails to show but ShowRecord::getSelectedMails has returned an empty list." << endl;
    emit sigShowBodiesReady( m_strAccount );
    return;
  }

  //set account state
  state = AccountDownloading;

  //start the deleting of all mails in MailsToDelete
  showNextMail();

}

void ConfigElem::showNextMail( )
{
  //if the list of mails to show is empty, finalize it and return
  if( MailsToShow.empty() )
  {
    slotFinalizeShowMail( NULL );
    return;
  }

  //clear the class variable mailbody, which contains the downloaded mail body
  mailbody.resize( 0 );

  //start job
  startKIOJob( TQString( "/download/%1" ).arg( *MailsToShow.begin() ) );
  connect( pop3Job, TQ_SIGNAL( data( TDEIO::Job*, const TQByteArray & ) ), TQ_SLOT( slotDataMailBody( TDEIO::Job*, const TQByteArray & ) ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotBodyDownloaded( TDEIO::Job* ) ) );

}

void ConfigElem::slotBodyDownloaded( TDEIO::Job * job )
{
  //stop timeout timer
  pop3Timer->stop();

  //check for errors
  //if an error has occured, the download will be canceled
  //or will ask for a new password
  if( job->error() == TDEIO::ERR_COULD_NOT_LOGIN )
  {
    //login failed, ask for a new password
    job->showErrorDialog();
    bool res = assertPassword( true );
    if( res == false )
    {
      //we have not got a new password; cancel delete
      slotFinalizeShowMail( NULL );
      return;
    }
    //if we have got a new password, jump to the end of the if-statement
  }
  else if( job->error() != 0 )
  {
    job->showErrorDialog();
    slotFinalizeShowMail( NULL );
    return;
  }
  else
  {
    //succesful download
    //show mail
    int currentMail = *MailsToShow.begin();
    TQString tsender = m_pshowrecord->getSenderOf( currentMail );
    TQString tdate = m_pshowrecord->getDateOf( currentMail );
    TQString tsize = m_pshowrecord->getSizeOf( currentMail );
    TQString tsubject = m_pshowrecord->getSubjectOf( currentMail );
    TQString tmailbody( m_pshowrecord->decodeMailBody( mailbody, currentMail, appConfig->allowHTML() ) );

    //emit signal to notify the opening of a window
    emit sigMessageWindowOpened();

    //create and open the window
    ShowMailDialog dlg( kapp->mainWidget(), m_strAccount, appConfig->allowHTML(), tsender, tdate, tsize, tsubject, tmailbody );
    int ret = dlg.exec();

    //emit signal to notify the closing of a window
    emit sigMessageWindowClosed();

    //cancel the download if desired
    if( ret == KDialogBase::Rejected )
    {
      MailsToShow.clear();
      commitDownloading();
      return;
    }

    //remove the first item of the list of mails to show
    MailsToShow.remove( MailsToShow.begin() );

    //if the list of mails is empty, finalize the showing and return
    if( MailsToShow.empty() )
    {
      commitDownloading();
      return;
    }
  }


  //show next mail in list
  showNextMail();
}

void ConfigElem::slotFinalizeShowMail( TDEIO::Job* )
{
  //stop timeout time
  pop3Timer->stop();

  //set account state to idle
  state = AccountIdle;

  //emit signal to report the download is ready
  emit sigShowBodiesReady( m_strAccount );
}

void ConfigElem::slotDataMailBody( TDEIO::Job *, const TQByteArray & datas )
{
  if( !datas.isEmpty() )
  {
    //we get the next part of the mail
    //append it
    uint lastSize = mailbody.size();
    mailbody.resize( lastSize + datas.size() );
    for( uint i = 0; i < datas.size(); i++ )
      mailbody[ lastSize + i ] = datas[ i ];
  }
}

void ConfigElem::commitDownloading( )
{
  //start job to commit
  startKIOJob( TQString( "/commit" ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotFinalizeShowMail( TDEIO::Job* ) ) );
}

void ConfigElem::refreshMailList( FilterLog* log )
{
  //store pointer to log
  if( log != NULL )
    FLog = log;

  //return, if account is not active
  if( !isActive() )
  {
    emit sigRefreshReady( m_strAccount );
    return;
  }

  //check whether we have a password for this account
  //if not, ask for it
  //return when no password is available
  if( !assertPassword() )
  {
    emit sigRefreshReady( m_strAccount );
    return;
  }

  //create a new ShowRecord instance
  //When the refresh has finished successfully, this will
  //replace the old mail list
  tempMailList = new ShowRecord();

  //set account state
  state = AccountRefreshing;

  //init counter
  if( !refreshPerformedByFilters )
  {
    nmbDeletedMailsLastRefresh = 0;
    nmbMovedMailsLastRefresh = 0;
    nmbIgnoredMails = 0;
  }

  //the first step is to get the UIDs
  getUIDs();
}

void ConfigElem::getUIDs( )
{
  //clears the TQString list, which contains all received UIDs
  receivedUIDs.clear();

  //start job
  startKIOJob( TQString( "/uidl" ) );
  connect( pop3Job, TQ_SIGNAL( data( TDEIO::Job*, const TQByteArray & ) ), TQ_SLOT( slotReceiveUID( TDEIO::Job*, const TQByteArray & ) ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotUIDsReceived( TDEIO::Job* ) ) );

}

void ConfigElem::slotReceiveUID( TDEIO::Job*, const TQByteArray& data )
{
  //return, when data is empty
  if( data.isEmpty() ) return;

 //cast the data to TQString
  TQString uid( data );

  //insert the uid at the end of the UID list
  receivedUIDs.append( uid );
}

void ConfigElem::slotUIDsReceived( TDEIO::Job * job )
{
  int number;                 //an extracted mail number
  TQString uid;                //an extracted uid
  bool corruptData = false;   //set to TRUE, if a data is corrupt
  bool isNew = false;         //state of the received mail

  //stop timeout timer
  pop3Timer->stop();

  //check for errors
  //if an error has occured, the refresh will be canceled
  //or will ask for a new password
  if( job->error() == TDEIO::ERR_COULD_NOT_LOGIN )
  {
    //login failed, ask for a new password
    job->showErrorDialog();
    bool res = assertPassword( true );
    if( res == true )
    {
      //we have got a new password, try again
      delete tempMailList;
      refreshMailList();
    }
    else
      //we have not got a new password; cancel refresh
      cancelRefresh();

    return;
  }
  else if( job->error() != 0 )
  {
    //show error message if desired
    if( appConfig->showConnectionErrors() )
      job->showErrorDialog();

    cancelRefresh();
    return;
  }

  //analyze UIDs
  if( !receivedUIDs.isEmpty() )
  {
    //iterate over all UIDs in the list
    for ( TQStringList::Iterator it = receivedUIDs.begin(); it != receivedUIDs.end(); ++it )
    {
      TQString line = *it;

      //every line has the format "number UID", e.g.: 1 bf10d38018de7c1d628d65288d722f6a
      //get the position of the separating space
      int positionOfSpace = line.find( " " );

      //if no space was found, the line is corrupt
      if( positionOfSpace == -1 )
      {
        kdError() << "ConfigElem::slotUIDsReceived: get a corrupt UID from " << dynamic_cast<TDEIO::SimpleJob*>(job)->url().host() << ". No space. : " << line << endl;
        corruptData = true;
      }
      else
      {
        //extract mail number and uid
        bool isNumber;
        number = line.left( positionOfSpace ).toInt( &isNumber );
        //check number
        if( !isNumber )
        {
          //the first part is not a number
          kdError() << "ConfigElem::slotUIDsReceived: get a corrupt UID from " << dynamic_cast<TDEIO::SimpleJob*>(job)->url().host() << ". No number found at begin. : " << line << endl;
          corruptData = true;
        }
        else
        {
          //number is ok; extract uid
          uid = line.mid( positionOfSpace + 1 );

          //determine about new mail or not
          if( !m_pshowrecord->hasMail( uid ) )
          {
            //the old list doesn't contain a mail with this uid
            //the mail is new
            isNew = true;
          }
          else if( ( appConfig->keepNew() || refreshPerformedByFilters ) && m_pshowrecord->isNew( uid ) )
          {
            //the mail is already in the old list
            //but we will leave the state of formerly new mails, because the user wants it or this refresh is performed by filters
            isNew = true;
          }
          else
            isNew = false;

          //append mail to the list
          tempMailList->appendNewMail( number, uid, isNew );

        }
      }
    }

    //if the data are ok, start the second step: get sizes
    //otherwise cancel the refresh
    if( !corruptData )
      getSizes();
    else
      cancelRefresh();
  }
  else
  {
    //we haven't received any UIDs. The account has no mails.
    //finalize the refresh
    swapMailLists();
  }

}

void ConfigElem::cancelRefresh()
{
  //print error message
  kdError() << m_strAccount << ": " << "Refresh canceled" << endl;

  //delete the new mail list
  delete tempMailList;

  //delete old mail list and create a new empty one
  delete m_pshowrecord;
  m_pshowrecord = new ShowRecord();

  //emit signal
  emit sigRefreshReady( m_strAccount );

  //set account state to idle
  state = AccountIdle;

  //we don't need an error message, because the TDEIO job has shown one
}

void ConfigElem::slotFinalizeRefresh( TDEIO::Job* )
{
  //stop timeout time
  pop3Timer->stop();

  //unset the flag
  refreshPerformedByFilters = false;

  //emit signal
  emit sigRefreshReady( m_strAccount );

  //set account state to idle
  state = AccountIdle;


}

void ConfigElem::commitRefresh( )
{
  //start job to commit
  startKIOJob( TQString( "/commit" ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotFinalizeRefresh( TDEIO::Job* ) ) );
}

void ConfigElem::getSizes( )
{
  //clears the TQString list, which contains all received UIDs
  receivedSizes.clear();

  //start job
  startKIOJob( TQString( "/index" ) );
  connect( pop3Job, TQ_SIGNAL( data( TDEIO::Job*, const TQByteArray & ) ), TQ_SLOT( slotReceiveSize( TDEIO::Job*, const TQByteArray & ) ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotSizesReceived( TDEIO::Job* ) ) );

}

void ConfigElem::slotSizesReceived( TDEIO::Job * job )
{
  int number;                 //an extracted mail number
  long size;                   //an extracted size
  bool corruptData = false;   //set to TRUE, if a data is corrupt

  //stop timeout timer
  pop3Timer->stop();

  //check for errors
  //if an error has occured, the refresh will be canceled
  if( job->error() != 0 )
  {
    //show error message if desired
    if( appConfig->showConnectionErrors() )
      job->showErrorDialog();
    cancelRefresh();
    return;
  }

  //analyze UIDs
  if( !receivedSizes.isEmpty() )
  {
    //iterate over all sizes in the list
    for ( TQStringList::Iterator it = receivedSizes.begin(); it != receivedSizes.end(); ++it )
    {
      TQString line = *it;

      //every line has the format "number size", e.g.: 1 1234
      //get the position of the separating space
      int positionOfSpace = line.find( " " );

      //if no space was found, the line is corrupt
      if( positionOfSpace == -1 )
      {
        kdError() << "ConfigElem::slotSizesReceived: get a corrupt size from " << dynamic_cast<TDEIO::SimpleJob*>(job)->url().host() << ". No space. : " << line << endl;
        corruptData = true;
      }
      else
      {
        //extract mail number and size
        bool isNumber;
        number = line.left( positionOfSpace ).toInt( &isNumber );
        //check number
        if( !isNumber )
        {
          //the first part is not a number
          kdError() << "ConfigElem::slotSizesReceived: get a corrupt size from " << dynamic_cast<TDEIO::SimpleJob*>(job)->url().host() << ". No number found at begin. : " << line << endl;
          corruptData = true;
        }
        else
        {
          //number is ok; extract size
          size = line.mid( positionOfSpace + 1 ).toLong( &isNumber );

          //check size
          if( !isNumber )
          {
            //the second part of the string is not a number
            kdError() << "ConfigElem::slotSizesReceived: get a corrupt size from " << dynamic_cast<TDEIO::SimpleJob*>(job)->url().host() << ". No size found at end. : " << line << endl;
            corruptData = true;
          }
          else
          {
            //size is ok
            //set it
            tempMailList->setSize( number, size );
          }
        }
      }
    }

    //if the data are ok, start the third step: get headers
    //otherwise cancel the refresh
    if( !corruptData )
      getHeaders();
    else
      cancelRefresh();
  }
}

void ConfigElem::slotReceiveSize( TDEIO::Job *, const TQByteArray & data )
{
  //return, when data is empty
  if( data.isEmpty() ) return;

 //cast the data to TQString
  TQString size( data );

  //insert the uid at the end of the sizes list
  receivedSizes.append( size );

}

void ConfigElem::getHeaders( )
{
  //get the numbers of all new mails
  newMails = tempMailList->getNewMails();
  if( newMails.empty() )
  {
    //no new mails available; copy the known headers from the old mail list
    copyHeaders();
    return;
  }

  //get the headers
  getNextHeader();
}

void ConfigElem::getNextHeader( )
{
  //if the list of mails empty, copy the known headers from the old mail list
  if( newMails.empty() )
  {
    copyHeaders();
    return;
  }

  //clear temporary header store
  receivedHeader.resize( 0 );

  //start job
  startKIOJob( TQString( "/headers/%1" ).arg( *newMails.begin() ) );
  connect( pop3Job, TQ_SIGNAL( data( TDEIO::Job*, const TQByteArray & ) ), this, TQ_SLOT( slotReceiveHeader( TDEIO::Job*, const TQByteArray & ) ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotHeaderDownloaded( TDEIO::Job* ) ) );

}

void ConfigElem::slotHeaderDownloaded( TDEIO::Job * job )
{
  //stop timeout timer
  pop3Timer->stop();

  //check for errors
  //if an error is occured, the download will be canceled
  if( job->error() != 0 )
  {
    //show error message if desired
    if( appConfig->showConnectionErrors() )
      job->showErrorDialog();

    cancelRefresh();
    return;
  }

  //store header
  tempMailList->setHeader( *newMails.begin(), TQString( receivedHeader ) );

  //remove the first item of the list of new mails
  newMails.remove( newMails.begin() );

  //if the list of new mails is empty, copy the headers of old mails to the new list
  if( newMails.empty() )
  {
    copyHeaders();
    return;
  }

  //get next header
  getNextHeader();
}

void ConfigElem::copyHeaders( )
{
  //get the UIDs of the old mails in the temporary mail list
  TQStringList UIDs = tempMailList->getUIDsOfOldMails();

  //iterate over all members of the list,
  //get the header from the old list and store it in the new one
  TQStringList::iterator it;
  for ( it = UIDs.begin(); it != UIDs.end(); ++it )
  {
    TQString header = m_pshowrecord->getHeaderOf( *it );
    tempMailList->setHeader( *it, header );
  }

  //now we have the a complete new mail list
  swapMailLists();
}

void ConfigElem::slotReceiveHeader( TDEIO::Job *, const TQByteArray & data )
{
  if( !data.isEmpty() )
  {
    //we get the next part of the mail
    //append it
    uint lastSize = receivedHeader.size();
    receivedHeader.resize( lastSize + data.size() );
    for( uint i = 0; i < data.size(); i++ )
      receivedHeader[ lastSize + i ] = data[ i ];
  }
}

int ConfigElem::getNumberNewMails( )
{
  return m_pshowrecord->getNumberNewMails();
}

int ConfigElem::getNumberMails( )
{
  return m_pshowrecord->getNumberMails();
}

long ConfigElem::getTotalSize( )
{
  return m_pshowrecord->getTotalSize();
}

void ConfigElem::fillMailListView( KshowmailView* view )
{
  m_pshowrecord->fillMailListView( view, m_strAccount );
}

void ConfigElem::refreshAccountListItem( )
{
  if( m_pViewItem != NULL )
  {
    if( isActive() )
    {
      m_pViewItem->setText( 4, TQString( "%1" ).arg( getNumberMails(), 3 ) );
      m_pViewItem->setText( 5, TQString( "%1" ).arg( getTotalSize(), 8 ) );
    }
    else
    {
      m_pViewItem->setText( 4, TQString( "???" ) );
      m_pViewItem->setText( 5, TQString( "???" ) );
    }
  }
}

void ConfigElem::killPOP3Job( )
{
  //just try to kill, if it is not idle
  if( state != AccountIdle )
  {
    //kill a running job
    if( pop3Job != NULL )
      pop3Job->kill( true );

    //stop timeout timer
    pop3Timer->stop();

    //call the appropriate finalize method
    switch( state )
    {
      case AccountDeleting    : slotFinalizeDeletion( NULL ); break;
      case AccountDownloading : slotFinalizeShowMail( NULL ); break;
      case AccountRefreshing  : cancelRefresh(); break;

      default : break;
    }
  }
}

int ConfigElem::showSelectedHeaders( )
{
  //return, if no mails are selected
  if( !hasSelectedMails() )
    return ConfigElem::continueShowHeaders;

  //order the mail list to show the headers of the selected mails
  int ret = m_pshowrecord->showSelectedHeaders( m_strAccount );

  return ret == ShowRecord::continueShowHeaders ? ConfigElem::continueShowHeaders : ConfigElem::cancelShowHeaders;
}

void ConfigElem::printSetup( ) const
{
  kdDebug() << "Setup of " << m_strAccount << ":" << endl;
  kdDebug() << "Host: " << m_url.host() << endl;
  kdDebug() << "Protocol: " << m_url.protocol() << endl;
  kdDebug() << "Port: " << m_url.port() << endl;
  kdDebug() << "User: " << m_url.user() << endl;
  kdDebug() << "Password: " << m_url.pass() << endl;

  switch( PasswordStorage )
  {
    case CONFIG_VALUE_ACCOUNT_PASSWORD_DONT_SAVE    : kdDebug() << "Password Storage: don't save" << endl; break;
    case CONFIG_VALUE_ACCOUNT_PASSWORD_SAVE_FILE    : kdDebug() << "Password Storage: save in file" << endl; break;
    case CONFIG_VALUE_ACCOUNT_PASSWORD_SAVE_TDEWALLET : kdDebug() << "Password Storage: use TDEWallet" << endl; break;
    default                                         : kdDebug() << "Password Storage: invalid value" << endl;

  }

  kdDebug() << "active: " << m_bActive << endl << endl;


}

void ConfigElem::setPasswordStorage( int storage )
{
  if( storage == CONFIG_VALUE_ACCOUNT_PASSWORD_DONT_SAVE ||
      storage == CONFIG_VALUE_ACCOUNT_PASSWORD_SAVE_FILE ||
      storage == CONFIG_VALUE_ACCOUNT_PASSWORD_SAVE_TDEWALLET )

    PasswordStorage = storage;

  else

    PasswordStorage =  DEFAULT_ACCOUNT_PASSWORD_STORAGE;
}

int ConfigElem::getPasswordStorage( ) const
{
  return PasswordStorage;
}

TQString ConfigElem::getProtocol( bool upperCase ) const
{
  if( upperCase )
    return m_url.protocol().upper();
  else
    return m_url.protocol();
}

unsigned short int ConfigElem::getPort( ) const
{
  return m_url.port();
}

void ConfigElem::setTLS( bool tls )
{
  useTLS = tls;
}

bool ConfigElem::getTLS( ) const
{
  return useTLS;
}

void ConfigElem::reloadFilterSettings( )
{
  headerFilter.load();
}

void ConfigElem::applyFilters( )
{
  //are we executed by the MOVE routines?
  if( !downloadActionsInvoked )
  {
    //this is the first call (at the current refresh cycle) of this methode
    //we get the lists of mails to delete an move and call the MOVE routines if necessary

    //OK, the filters were applied
    filterApplied = true;

    //order the mail list to apply the header filters
    //it returns lists of mail numbers which shall be deleted or moved
    //the marking will be done by the mail list itself
    //the mail list removes all mails which shall be ignored itself
    MailsToDelete.clear();
    m_pshowrecord->applyHeaderFilter( &headerFilter, getAccountName(), MailsToDelete, MailsToDownload, nmbIgnoredMails, FLog );
    nmbDeletedMailsLastRefresh += MailsToDelete.count();
    nmbDeletedMailsLastStart += MailsToDelete.count();

    //This part will be executed, if mails shall be downloaded
    if( !MailsToDownload.empty() )
    {
      downloadActionsInvoked = true;
      doDownloadActions();

      //we quit this methode at this point, because after the bodies are downloaded and written this methode will recalled.
      //At this time the else branch of this IF-statement will be executed and the methode continues
      return;
    }

  }
  else
  {
    //this is the second call (at the current refresh cycle) of this methode.
    //it is called by the Move routines.
    //the downloading of the mailbodies and writing it to the mailboxes has ended.
    //A second call was just exceuted, if there was mails to move
    downloadActionsInvoked = false;

    //after an move error there are maybe some mails leftover in MailsToMove
    MailsToDownload.clear();
  }



  //we have get the list of mails to delete and the all mails to move are written to its mailboxes
  //now we delete this mails (the moved mails too)

  if( !MailsToDelete.empty() )
  {
    //there are mails to delete
    //we delete they
    //after the delete cycle has done its job, it will call applyFiltersDeleted()
    deletionPerformedByFilters = true;  //this is set to indicate the deletion is performed by filters and not by user
                                        //the deletion methodes need it to decide on branch targets
    deleteNextMail();
  }
  else
  {
    //if we need not to start a second refresh cycle (no mails was deleted or moved)
    //we just commit the refresh and let the filter applied flag to false for the next regular refresh
    commitRefresh();
    filterApplied = false;
  }
}

void ConfigElem::swapMailLists( )
{
  //delete old mail list
  delete m_pshowrecord;

  //assign the new list
  if( tempMailList != NULL )
    m_pshowrecord = tempMailList;
  else
    m_pshowrecord = new ShowRecord();

  //if the filters were not applied yet, we do it now
  //applyFilters() will either start a second refresh cycle if it did some deletions
  //or call commitRefresh() to commit the refresh cycle.
  //if the filters were already applied we commit the refresh.
  if( filterApplied | !headerFilter.isActive() )
  {
    commitRefresh();
    filterApplied = false;
    return;
  }
  else
  {
    applyFilters();
    return;
  }
}

void ConfigElem::applyFiltersDeleted( )
{
  //unset the flag
  deletionPerformedByFilters = false;

  //start the second refresh cycle
  refreshPerformedByFilters = true;
  
  //this sends a commit and restart the refresh
  commitBeforeRefresh();
  return;
  //refreshMailList();
}


bool ConfigElem::writeToMailBox( const TQString & mail, const TQString & box )
{
  TQDir mailDir( box );

  //check whether the given path is a maildir
  if( !isMailDir( mailDir ) )
  {
    //show an error message
    KMessageBox::error( NULL, i18n( "%1 is not a mailbox." ).arg( box ) );
    return false;
  }

  //create unique file name according http://cr.yp.to/proto/maildir.html
  TQString partTime = TQString::number( time( NULL ) );   //left part, output of time()

  char hname[256];                                      //right part, the hostname
  TQString partHostname;
  if( gethostname( hname, 255 ) == 0 )
    partHostname = TQString( hname );
  else
  {
    //the hostname is not readable
    //show an error message and exit
    KMessageBox::error( NULL, i18n( "Can't read the hostname of your computer. But KShowmail need it to write a mail into the mailbox." ) );
    return false;
  }

  TQString partPID = TQString::number( getpid() );      //middle part, the PID

  TQString partCounter = TQString::number( moveCounter++ );

  TQString uniqueName( partTime + "." + partPID + partCounter + "." + partHostname );

  //build absolute path
  mailDir.cd( "tmp" );
  TQString absFile = mailDir.filePath( uniqueName );

  //and writing!
  TQFile file( absFile );
  if( file.open( IO_WriteOnly ) )
  {
    TQTextStream stream( &file );
    stream << mail << endl;
    file.close();
  }
  else
  {
    KMessageBox::detailedError( NULL, i18n( "Could not file a mail to %1." ).arg( box ), i18n( file.errorString().utf8() ) );
    return false;
  }

  //now we move it to the "new" subdirectory
  mailDir.cdUp();
  mailDir.cd( "new" );
  TQString absNewFile = mailDir.filePath( uniqueName );

  if( rename( absFile.ascii(), absNewFile.ascii() ) == -1 )
  {
    KMessageBox::error( NULL, i18n( "Could not move a mail from %1 to %2." ).arg( absFile ).arg( absNewFile ) );
    return false;
  }

  //the writing was successful
  return true;
}

void ConfigElem::doDownloadActions()
{
  //get first mail
  getNextMailForDownloadActions();
}

bool ConfigElem::isMailDir( const TQDir & path )
{
  //get a list of all subdirectories in this directory
  const TQStringList entries = path.entryList( TQDir::Dirs | TQDir::Readable | TQDir::Writable | TQDir::Hidden, TQDir::Name | TQDir::IgnoreCase | TQDir::LocaleAware );

  //a maildir folder must contains the folders "cur", "new" and "tmp"
  bool curFound = false;
  bool newFound = false;
  bool tmpFound = false;

  //iterate over all directories and look for the three necessary dirs
  TQStringList::const_iterator it = entries.begin();
  while( it != entries.end() && !( curFound && newFound && tmpFound ) )
  {
    if( *it == "tmp" )
      tmpFound = true;
    else if( *it == "cur" )
      curFound = true;
    else if( *it == "new" )
      newFound = true;

    ++it;
  }

  return curFound && newFound && tmpFound;
}

void ConfigElem::getNextMailForDownloadActions()
{
    //if the list of mails to move is empty return to applyFilters
  if( MailsToDownload.empty() )
  {
    applyFilters();
    return;
  }

  //clear the class variable mailbody, which contains the downloaded mail body
  mailbody.resize( 0 );

  //start job
  startKIOJob( TQString( "/download/%1" ).arg( MailsToDownload.begin().key() ) );
  connect( pop3Job, TQ_SIGNAL( data( TDEIO::Job*, const TQByteArray & ) ), TQ_SLOT( slotDataMailBody( TDEIO::Job*, const TQByteArray & ) ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotMailDownloadedForAction( TDEIO::Job* ) ) );

}

void ConfigElem::slotMailDownloadedForAction(TDEIO::Job * job)
{
  //stop timeout timer
  pop3Timer->stop();

  //check for errors
  //if an error has occured, the download will be canceled
  //or will ask for a new password
  if( job->error() == TDEIO::ERR_COULD_NOT_LOGIN )
  {
    //login failed, ask for a new password
    job->showErrorDialog();
    bool res = assertPassword( true );
    if( res == false )
    {
      //we have not got a new password; cancel delete
      applyFilters();
      return;
    }
    //if we have got a new password, jump to the end of the if-statement
  }
  else if( job->error() != 0 )
  {
    job->showErrorDialog();
    applyFilters();
    return;
  }
  else
  {
    //succesful download
    //do action
    MailToDownloadMap_Type::Iterator firstMail = MailsToDownload.begin();
    int currentMailNumber = firstMail.key();  //get mail number
    TQString currentMailBox( firstMail.data().mailbox ); //get mailbox
    TQString mail( mailbody );                 //convert mailtext
    FilterAction_Type action = firstMail.data().action; //get action

    bool resultMove = false;    //TRUE - mail is written into the mailbox
    bool resultSpam = false;  //TRUE - mail is Spam
    bool deleteIt = false;    //TRUE - mail shall be deleted
    bool resultAction = false;  //True - the action was succesful performed

    switch( action )
    {
      case FActMove       : resultMove = writeToMailBox( mail, currentMailBox );
                            //log entry is made by ShowRecordElem::applyHeaderFilter
                            if( resultMove == true )
                            {
                              nmbMovedMailsLastRefresh++;
                              nmbMovedMailsLastStart++;

                              resultAction = true;
                              deleteIt = true;
                            }
                            else
                            {
                              resultAction = false;
                              deleteIt = false;
                            }
                            break;

      case FActSpamcheck  : resultSpam = isSpam( mailbody );  //it is spam?
                            if( resultSpam == true )          //yes, it is spam! Arrgghh! Torture it!!!
                            {
                              switch( appConfig->getSpamAction() )
                              {
                                case FActMove   : resultMove = writeToMailBox( mail, appConfig->getSpamMailbox() );
                                                  if( resultMove == true )
                                                  {
                                                    nmbMovedMailsLastRefresh++;
                                                    nmbMovedMailsLastStart++;

                                                    if( FLog != NULL )
                                                      m_pshowrecord->writeToMoveLog( FLog, currentMailNumber, getAccountName(), appConfig->getSpamMailbox() );
                                                    resultAction = true;
                                                    deleteIt = true;
                                                  }
                                                  else
                                                  {
                                                    resultAction = false;
                                                    deleteIt = false;
                                                  }
                                                  break;

                                case FActMark   : m_pshowrecord->setMarkAtNextViewRefresh( currentMailNumber );
                                                  resultAction = true;
                                                  deleteIt = false;
                                                  break;

                                case FActDelete : if( FLog != NULL )
                                                    m_pshowrecord->writeToDeleteLog( FLog, currentMailNumber, getAccountName() );

                                                  nmbDeletedMailsLastRefresh++;
                                                  nmbDeletedMailsLastStart++;
                                                  resultAction = true;
                                                  deleteIt = true;
                                                  break;

                                default         : kdError() << "invalid action for spam mail" << endl;
                                                  resultAction = false;
                                                  deleteIt = false;
                                                  break;

                              }
                            }
                            else    //mail is not spam
                            {
                              resultAction = true;
                              deleteIt = false;
                            }
                            break;

      default             : deleteIt = false;
                            resultAction = false;

    }

    if( resultAction == true )
    {
      //Action was successful
      //remove this mail from the list
      MailsToDownload.remove( firstMail );

      //maybe add this mail to list of mails to delete
      if( deleteIt )
        MailsToDelete.append( currentMailNumber );
    }
    else
    {
      //Action was not successful
      //returns to applyFilters() to continue the filtering
      applyFilters();
      return;
    }


    //if the list of mails is empty, return to applyFilters() to continue the filtering
    if( MailsToDownload.empty() )
    {
      applyFilters();
      return;
    }
  }


  //show next mail in list
  getNextMailForDownloadActions();
}

bool ConfigElem::isSpam( TQByteArray mail ) const
{
  //check for a running spamassassin
  if( !isSpamAssassinRunning() )
  {
    KMessageBox::information( NULL, i18n( "You want to check your mails for spam, but SpamAssassin is not running.\nKShowmail skips the spam check." ), i18n( "SpamAssassin is not running" ), "ConfigElemNoSpamAssassinRunning" );
    return false;
  }

  //append an \0 at the end of the string
  int size = mail.size();
  if( mail[ size - 1 ] != '\0' )
  {
    mail.resize( size + 1 );
    mail[ size ] = '\0';
  }

  //calls spmac and get an file pointer to stdin of it
  FILE *write_fp;
  write_fp = popen( "spamc -E", "w" );

  //forward the mail to SpamAssassin
  if( write_fp != NULL )
  {
    fwrite( mail.data(), sizeof( char), mail.size(), write_fp );

    //check exit code of spamc and return result
    int excode = pclose( write_fp );
    if(  excode == 0 )
      return false;
    else
      return true;
  }
  else
  {
    kdError() << "Could not call the command spamc of SpamAssassin." << endl;
    return false;
  }

  return false;
}

bool ConfigElem::isSpamAssassinRunning( ) const
{
  FILE *read_fp;
  char buffer[ BUFSIZ + 1 ];
  int chars_read;
  bool found = false;

  memset( buffer, '\0', sizeof( buffer ) );
  read_fp = popen( "ps -eo comm", "r" );
  if( read_fp != NULL )
  {
    chars_read = fread( buffer, sizeof( char ), BUFSIZ, read_fp );
    while( chars_read > 0 )
    {
      buffer[ chars_read - 1 ] = '\0';
      TQString output( buffer );
      found = output.contains( NAME_SPAMASSASSIN_DAEMON ) > 0;
      chars_read = fread( buffer, sizeof( char ), BUFSIZ, read_fp );
    }
    pclose( read_fp );
  }

  return found;
}

int ConfigElem::numberDeletedMailsLastRefresh( )
{
  return nmbDeletedMailsLastRefresh;
}

int ConfigElem::numberDeletedMailsStart( )
{
  return nmbDeletedMailsLastStart;
}

int ConfigElem::numberMovedMailsLastRefresh( )
{
  return nmbMovedMailsLastRefresh;
}

int ConfigElem::numberMovedMailsStart( )
{
  return nmbMovedMailsLastStart;
}

int ConfigElem::numberIgnoredMails( )
{
  return nmbIgnoredMails;
}

TQStringList ConfigElem::getSelectedSenders( ) const
{
  return m_pshowrecord->getSelectedSenders();
}




void ConfigElem::commitBeforeRefresh()
{
  //start job to commit
  startKIOJob( TQString( "/commit" ) );
  connect( pop3Job, TQ_SIGNAL( result( TDEIO::Job* ) ), this, TQ_SLOT( slotCommitBeforeRefreshDone( TDEIO::Job* ) ) );

}

void ConfigElem::slotCommitBeforeRefreshDone(TDEIO::Job *)
{
  //after a commit was send, we start a new refresh cyle
  refreshMailList();
}

#include "configelem.moc"