Fossil

Changes On Branch webmail
Login

Changes On Branch webmail

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch webmail Excluding Merge-Ins

This is equivalent to a diff from 3f5ab717 to e2fd46dd

2018-07-17
15:32
Webmail changes compile on linux, mac, and windows now, so merge them to trunk. They are not ready for use, but they should not interfere with the stable parts of the code, and it is easier to test from trunk. ... (check-in: 0f6a5ee1 user: drh tags: trunk)
15:10
Fix a mimetype typo that prevents email notification from running. ... (check-in: adc23c10 user: drh tags: trunk)
15:10
Fix a mimetype typo that prevents email notification from running. ... (Closed-Leaf check-in: e2fd46dd user: drh tags: webmail)
15:07
Show the email notification status at the top of the /setup_notification page. ... (check-in: 308f4065 user: drh tags: webmail)
2018-07-16
13:33
Initialize variable to quell compiler warning about potentially unitialized variable. ... (check-in: 0cb83dec user: andybradford tags: trunk)
11:35
Merge enhancements from trunk. ... (check-in: 03a9b6f8 user: drh tags: webmail)
2018-07-15
19:56
Clarify the difference between fossil_fatal() and fossil_panic(). The fossil_panic() interface puts a message on the error log when generating webpages. Otherwise the two routines are identical. Convert some fossil_fatal() calls into fossil_panic() where appropriate. The goal here is to limit messages on the error log to things that require attention from the system administrator, or represent bugs. ... (check-in: 3f5ab717 user: drh tags: trunk)
18:31
Improvements to error logging. Only log fossil_panic() calls, not fossil_fatal() calls. ... (check-in: 06d4751a user: drh tags: trunk)

Changes to src/cgi.c.

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
  }
  fflush(g.httpOut);
  CGIDEBUG(("DONE\n"));

  /* After the webpage has been sent, do any useful background
  ** processing.
  */
  if( iReplyStatus==200 && fossil_strcmp(zContentType,"test/html")==0 ){
    email_auto_exec();
  }
}

/*
** Do a redirect request to the URL given in the argument.
**







|







341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
  }
  fflush(g.httpOut);
  CGIDEBUG(("DONE\n"));

  /* After the webpage has been sent, do any useful background
  ** processing.
  */
  if( iReplyStatus==200 && fossil_strcmp(zContentType,"text/html")==0 ){
    email_auto_exec();
  }
}

/*
** Do a redirect request to the URL given in the argument.
**

Changes to src/db.c.

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
}

/*
** Silently add the filename and line number as parameter to each
** db_begin_transaction call.
*/
#if INTERFACE
#define db_begin_transaction() db_begin_transaction_real(__FILE__,__LINE__)



#endif

/*
** Begin and end a nested transaction
*/
void db_begin_transaction_real(const char *zStartFile, int iStartLine){
  if( db.nBegin==0 ){
    db_multi_exec("BEGIN");
    sqlite3_commit_hook(g.db, db_verify_at_commit, 0);
    db.nPriorChanges = sqlite3_total_changes(g.db);
    db.doRollback = 0;
    db.zStartFile = zStartFile;
    db.iStartLine = iStartLine;
  }
  db.nBegin++;
}






















void db_end_transaction(int rollbackFlag){
  if( g.db==0 ) return;
  if( db.nBegin<=0 ){
    fossil_warning("Extra call to db_end_transaction");
    return;
  }
  if( rollbackFlag ){







|
>
>
>



|












>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
}

/*
** Silently add the filename and line number as parameter to each
** db_begin_transaction call.
*/
#if INTERFACE
#define db_begin_transaction()    db_begin_transaction_real(__FILE__,__LINE__)
#define db_begin_write()          db_begin_write_real(__FILE__,__LINE__)
#define db_commit_transaction()   db_end_transaction(0)
#define db_rollback_transaction() db_end_transaction(1)
#endif

/*
** Begin a nested transaction
*/
void db_begin_transaction_real(const char *zStartFile, int iStartLine){
  if( db.nBegin==0 ){
    db_multi_exec("BEGIN");
    sqlite3_commit_hook(g.db, db_verify_at_commit, 0);
    db.nPriorChanges = sqlite3_total_changes(g.db);
    db.doRollback = 0;
    db.zStartFile = zStartFile;
    db.iStartLine = iStartLine;
  }
  db.nBegin++;
}
/*
** Begin a new transaction for writing.
*/
void db_begin_write_real(const char *zStartFile, int iStartLine){
  if( db.nBegin==0 ){
    db_multi_exec("BEGIN IMMEDIATE");
    sqlite3_commit_hook(g.db, db_verify_at_commit, 0);
    db.nPriorChanges = sqlite3_total_changes(g.db);
    db.doRollback = 0;
    db.zStartFile = zStartFile;
    db.iStartLine = iStartLine;
  }else{
    fossil_warning("read txn at %s:%d might cause SQLITE_BUSY "
       "for the write txn at %s:%d",
       db.zStartFile, db.iStartLine, zStartFile, iStartLine);
  }
  db.nBegin++;
}

/* End a transaction previously started using db_begin_transaction()
** or db_begin_write().
*/
void db_end_transaction(int rollbackFlag){
  if( g.db==0 ) return;
  if( db.nBegin<=0 ){
    fossil_warning("Extra call to db_end_transaction");
    return;
  }
  if( rollbackFlag ){

Changes to src/email.c.

202
203
204
205
206
207
208










209
210
211
212
213
214
215
    return;
  }
  db_begin_transaction();

  email_submenu_common();
  style_submenu_element("Send Announcement","%R/announce");
  style_header("Email Notification Setup");










  @ <form action="%R/setup_notification" method="post"><div>
  @ <input type="submit"  name="submit" value="Apply Changes" /><hr>
  login_insert_csrf_secret();

  entry_attribute("Canonical Server URL", 40, "email-url",
                   "eurl", "", 0);
  @ <p><b>Required.</b>







>
>
>
>
>
>
>
>
>
>







202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    return;
  }
  db_begin_transaction();

  email_submenu_common();
  style_submenu_element("Send Announcement","%R/announce");
  style_header("Email Notification Setup");
  @ <h1>Status</h1>
  @ <table class="label-value">
  if( email_enabled() ){
    stats_for_email();
  }else{
    @ <th>Disabled</th>
  }
  @ </table>
  @ <hr>
  @ <h1> Configuration </h1>
  @ <form action="%R/setup_notification" method="post"><div>
  @ <input type="submit"  name="submit" value="Apply Changes" /><hr>
  login_insert_csrf_secret();

  entry_attribute("Canonical Server URL", 40, "email-url",
                   "eurl", "", 0);
  @ <p><b>Required.</b>
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099

2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
  int iJulianDay;
  if( g.db==0 ) return;
  if( db_transaction_nesting_depth()!=0 ){
    fossil_warning("Called email_auto_exec() from within transaction "
                   "started at %z", db_transaction_start_point());
    return;
  }
  db_begin_transaction();
  if( !email_tables_exist() ) goto autoexec_done;
  if( !db_get_boolean("email-autoexec",0) ) goto autoexec_done;

  email_send_alerts(0);
  iJulianDay = db_int(0, "SELECT julianday('now')");
  if( iJulianDay>db_get_int("email-last-digest",0) ){
    if( db_transaction_nesting_depth()!=1 ){
      fossil_warning("Transaction nesting error prior to digest processing");
    }else{
      db_set_int("email-last-digest",iJulianDay,0);
      email_send_alerts(SENDALERT_DIGEST);
    }
  }

autoexec_done:
  db_end_transaction(0);
}

/*
** WEBPAGE: contact_admin
**
** A web-form to send an email message to the repository administrator,
** or (with appropriate permissions) to anybody.







<
|
|
>










<
<
|







2100
2101
2102
2103
2104
2105
2106

2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119


2120
2121
2122
2123
2124
2125
2126
2127
  int iJulianDay;
  if( g.db==0 ) return;
  if( db_transaction_nesting_depth()!=0 ){
    fossil_warning("Called email_auto_exec() from within transaction "
                   "started at %z", db_transaction_start_point());
    return;
  }

  if( !email_tables_exist() ) return;
  if( !db_get_boolean("email-autoexec",0) ) return;
  db_begin_write();
  email_send_alerts(0);
  iJulianDay = db_int(0, "SELECT julianday('now')");
  if( iJulianDay>db_get_int("email-last-digest",0) ){
    if( db_transaction_nesting_depth()!=1 ){
      fossil_warning("Transaction nesting error prior to digest processing");
    }else{
      db_set_int("email-last-digest",iJulianDay,0);
      email_send_alerts(SENDALERT_DIGEST);
    }
  }


  db_commit_transaction();
}

/*
** WEBPAGE: contact_admin
**
** A web-form to send an email message to the repository administrator,
** or (with appropriate permissions) to anybody.

Changes to src/smtp.c.

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
** Schema used by the email processing system.
*/
static const char zEmailSchema[] = 
@ -- bulk storage is in a separate table.  This table can store either
@ -- the body of email messages or transcripts of smtp sessions.
@ CREATE TABLE IF NOT EXISTS repository.emailblob(
@   emailid INTEGER PRIMARY KEY,  -- numeric idea for the entry

@   ets INT,                      -- Corresponding transcript, or NULL
@   etime INT,                    -- insertion time, secs since 1970
@   etxt TEXT                     -- content of this entry
@ );
@
@ -- One row for each mailbox entry.  All users emails are stored in
@ -- this same table.
@ CREATE TABLE IF NOT EXISTS repository.emailbox(

@   euser TEXT,          -- User who received this email
@   edate INT,           -- Date received.  Seconds since 1970
@   efrom TEXT,          -- Who is the email from
@   emsgid INT,          -- Raw email text
@   ets INT,             -- Transcript of the receiving SMTP session
@   estate INT,          -- Unread, read, starred, etc.
@   esubject TEXT,       -- Subject line for display
@   etags TEXT           -- zero or more tags
@ );
@
@ -- Information on how to deliver incoming email.
@ CREATE TABLE IF NOT EXISTS repository.emailroute(
@   eaddr TEXT PRIMARY KEY,  -- Email address







>








>




<
|







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
** Schema used by the email processing system.
*/
static const char zEmailSchema[] = 
@ -- bulk storage is in a separate table.  This table can store either
@ -- the body of email messages or transcripts of smtp sessions.
@ CREATE TABLE IF NOT EXISTS repository.emailblob(
@   emailid INTEGER PRIMARY KEY,  -- numeric idea for the entry
@   enref INT,                    -- Number of references to this blob
@   ets INT,                      -- Corresponding transcript, or NULL
@   etime INT,                    -- insertion time, secs since 1970
@   etxt TEXT                     -- content of this entry
@ );
@
@ -- One row for each mailbox entry.  All users emails are stored in
@ -- this same table.
@ CREATE TABLE IF NOT EXISTS repository.emailbox(
@   ebid INTEGER PRIMARY KEY,  -- Unique id for each mailbox entry
@   euser TEXT,          -- User who received this email
@   edate INT,           -- Date received.  Seconds since 1970
@   efrom TEXT,          -- Who is the email from
@   emsgid INT,          -- Raw email text

@   estate INT,          -- 0: Unread, 1: read, 2: trash 3: sent
@   esubject TEXT,       -- Subject line for display
@   etags TEXT           -- zero or more tags
@ );
@
@ -- Information on how to deliver incoming email.
@ CREATE TABLE IF NOT EXISTS repository.emailroute(
@   eaddr TEXT PRIMARY KEY,  -- Email address
671
672
673
674
675
676
677



















678
679
680
681
682
683
684
@   eto TEXT,                -- Receipient email address
@   emsgid INT,              -- Message body in the emailblob table
@   ectime INT,              -- Time enqueued.  Seconds since 1970
@   emtime INT,              -- Time of last send attempt.  Sec since 1970
@   ensend INT,              -- Number of send attempts
@   ets INT                  -- Transcript of last failed attempt
@ );



















;

/*
** Code used to delete the email tables.
*/
static const char zEmailDrop[] =
@ DROP TABLE IF EXISTS emailblob;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
@   eto TEXT,                -- Receipient email address
@   emsgid INT,              -- Message body in the emailblob table
@   ectime INT,              -- Time enqueued.  Seconds since 1970
@   emtime INT,              -- Time of last send attempt.  Sec since 1970
@   ensend INT,              -- Number of send attempts
@   ets INT                  -- Transcript of last failed attempt
@ );
@
@ -- Triggers to automatically keep the emailblob.enref field up to date
@ -- as entries in the emailblob, emailbox, and emailoutq tables are
@ -- deleted.
@ CREATE TRIGGER IF NOT EXISTS repository.emailblob_d1
@ AFTER DELETE ON emailblob BEGIN
@   DELETE FROM emailblob WHERE enref<=1 AND emailid=old.ets;
@   UPDATE emailblob SET enref=enref-1 WHERE emailid=old.ets;
@ END;
@ CREATE TRIGGER IF NOT EXISTS repository.emailbox_d1
@ AFTER DELETE ON emailbox BEGIN
@   DELETE FROM emailblob WHERE enref<=1 AND emailid=old.emsgid;
@   UPDATE emailblob SET enref=enref-1 WHERE emailid=old.emsgid;
@ END;
@ CREATE TRIGGER IF NOT EXISTS repository.emailoutq_d1
@ AFTER DELETE ON emailoutq BEGIN
@   DELETE FROM emailblob WHERE enref<=1 AND emailid IN (old.ets,old.emsgid);
@   UPDATE emailblob SET enref=enref-1 WHERE emailid IN (old.ets,old.emsgid);
@ END;
;

/*
** Code used to delete the email tables.
*/
static const char zEmailDrop[] =
@ DROP TABLE IF EXISTS emailblob;
826
827
828
829
830
831
832


833
834
835
836
837
838
839
  char *zFrom;                /* MAIL FROM: argument */
  int nTo;                    /* Number of RCPT TO: lines seen */
  struct SmtpTo {
    char *z;                    /* Address in each RCPT TO line */
    int okRemote;               /* zTo can be in another domain */
  } *aTo;
  u32 srvrFlags;              /* Control flags */


  Blob msg;                   /* Content following DATA */
  Blob transcript;            /* Session transcript */
};

#define SMTPSRV_CLEAR_MSG    1   /* smtp_server_clear() last message only */
#define SMTPSRV_CLEAR_ALL    2   /* smtp_server_clear() everything */
#define SMTPSRV_LOG       0x001  /* Record a transcript of the interaction */







>
>







846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
  char *zFrom;                /* MAIL FROM: argument */
  int nTo;                    /* Number of RCPT TO: lines seen */
  struct SmtpTo {
    char *z;                    /* Address in each RCPT TO line */
    int okRemote;               /* zTo can be in another domain */
  } *aTo;
  u32 srvrFlags;              /* Control flags */
  int nEts;                   /* Number of references to the transcript */
  int nRef;                   /* Number of references to idMsg */
  Blob msg;                   /* Content following DATA */
  Blob transcript;            /* Session transcript */
};

#define SMTPSRV_CLEAR_MSG    1   /* smtp_server_clear() last message only */
#define SMTPSRV_CLEAR_ALL    2   /* smtp_server_clear() everything */
#define SMTPSRV_LOG       0x001  /* Record a transcript of the interaction */
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
      if( zAddr[i]=='@' && zAddr[i+1]!=0 ){
        db_multi_exec(
          "INSERT INTO emailoutq(edomain,efrom,eto,emsgid,ectime,"
                                "emtime,ensend)"
          "VALUES(%Q,%Q,%Q,%lld,now(),0,0)",
          zAddr+i+1, p->zFrom, zAddr, p->idMsg
        );

      }
    }
    return;
  }
  blob_init(&policy, zPolicy, -1);
  while( blob_line(&policy, &line) ){
    blob_trim(&line);
    blob_token(&line, &token);
    blob_tail(&line, &tail);
    if( blob_size(&tail)==0 ) continue;
    if( blob_eq_str(&token, "mbox", 4) ){
      Blob subj;
      email_header_value(&p->msg, "subject", &subj);
      db_multi_exec(
        "INSERT INTO emailbox(euser,edate,efrom,emsgid,ets,estate,esubject)"
        " VALUES(%Q,now(),%Q,%lld,%lld,0,%Q)",
          blob_str(&tail), p->zFrom, p->idMsg, p->idTranscript,
          blob_str(&subj)
      );
      blob_reset(&subj);

    }
    if( blob_eq_str(&token, "forward", 7) ){
      smtp_append_to(p, fossil_strdup(blob_str(&tail)), 1);
    }
    blob_reset(&tail);
  }
}

/*
** The SmtpServer object contains a complete incoming email.
** Add this email to the database.
*/
static void smtp_server_route_incoming(SmtpServer *p, int bFinish){
  Stmt s;
  int i;
  if( p->zFrom
   && p->nTo
   && blob_size(&p->msg)
   && (p->srvrFlags & SMTPSRV_DRYRUN)==0
  ){
    db_begin_transaction();
    if( p->idTranscript==0 ) smtp_server_schema(0);

    db_prepare(&s,
      "INSERT INTO emailblob(ets,etime,etxt)"
      " VALUES(:ets,now(),compress(:etxt))"
    );

    if( !bFinish && p->idTranscript==0 ){
      db_bind_null(&s, ":ets");
      db_bind_null(&s, ":etxt");

      db_step(&s);
      db_reset(&s);
      p->idTranscript = db_last_insert_rowid();
    }else if( bFinish ){
      if( p->idTranscript ){
        db_multi_exec(
           "UPDATE emailblob SET etxt=compress(%Q)"
           " WHERE emailid=%lld",
           blob_str(&p->transcript), p->idTranscript);
      }else{
        db_bind_null(&s, ":ets");
        db_bind_str(&s, ":etxt", &p->transcript);

        db_step(&s);
        db_reset(&s);
        p->idTranscript = db_last_insert_rowid();
      }
    }
    db_bind_int64(&s, ":ets", p->idTranscript);
    db_bind_str(&s, ":etxt", &p->msg);

    db_step(&s);
    db_finalize(&s);
    p->idMsg = db_last_insert_rowid();

    /* make entries in emailbox and emailoutq */
    for(i=0; i<p->nTo; i++){
      int okRemote = p->aTo[i].okRemote;
      p->aTo[i].okRemote = 1;
      smtp_server_send_one_user(p, p->aTo[i].z, okRemote);
    }













    /* Finish the transaction after all changes are implemented */
    db_end_transaction(0);
  }
  smtp_server_clear(p, SMTPSRV_CLEAR_MSG);
}

































































/*
** COMMAND: smtpd
**
** Usage: %fossil smtpd [OPTIONS] REPOSITORY
**
** Begin a SMTP conversation with a client using stdin/stdout.  The







>














|
|
|



>




















|

>

|
|

>



>






|

|



>







>











>
>
>
>
>
>
>
>
>
>
>
>

|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
      if( zAddr[i]=='@' && zAddr[i+1]!=0 ){
        db_multi_exec(
          "INSERT INTO emailoutq(edomain,efrom,eto,emsgid,ectime,"
                                "emtime,ensend)"
          "VALUES(%Q,%Q,%Q,%lld,now(),0,0)",
          zAddr+i+1, p->zFrom, zAddr, p->idMsg
        );
        p->nRef++;
      }
    }
    return;
  }
  blob_init(&policy, zPolicy, -1);
  while( blob_line(&policy, &line) ){
    blob_trim(&line);
    blob_token(&line, &token);
    blob_tail(&line, &tail);
    if( blob_size(&tail)==0 ) continue;
    if( blob_eq_str(&token, "mbox", 4) ){
      Blob subj;
      email_header_value(&p->msg, "subject", &subj);
      db_multi_exec(
        "INSERT INTO emailbox(euser,edate,efrom,emsgid,estate,esubject)"
        " VALUES(%Q,now(),%Q,%lld,0,%Q)",
          blob_str(&tail), p->zFrom, p->idMsg,
          blob_str(&subj)
      );
      blob_reset(&subj);
      p->nRef++;
    }
    if( blob_eq_str(&token, "forward", 7) ){
      smtp_append_to(p, fossil_strdup(blob_str(&tail)), 1);
    }
    blob_reset(&tail);
  }
}

/*
** The SmtpServer object contains a complete incoming email.
** Add this email to the database.
*/
static void smtp_server_route_incoming(SmtpServer *p, int bFinish){
  Stmt s;
  int i;
  if( p->zFrom
   && p->nTo
   && blob_size(&p->msg)
   && (p->srvrFlags & SMTPSRV_DRYRUN)==0
  ){
    db_begin_write();
    if( p->idTranscript==0 ) smtp_server_schema(0);
    p->nRef = 0;
    db_prepare(&s,
      "INSERT INTO emailblob(ets,etime,etxt,enref)"
      " VALUES(:ets,now(),compress(:etxt),:enref)"
    );
    p->nEts++;
    if( !bFinish && p->idTranscript==0 ){
      db_bind_null(&s, ":ets");
      db_bind_null(&s, ":etxt");
      db_bind_int(&s, ":enref", 0);
      db_step(&s);
      db_reset(&s);
      p->idTranscript = db_last_insert_rowid();
    }else if( bFinish ){
      if( p->idTranscript ){
        db_multi_exec(
           "UPDATE emailblob SET etxt=compress(%Q), enref=%d"
           " WHERE emailid=%lld",
           blob_str(&p->transcript), p->nEts, p->idTranscript);
      }else{
        db_bind_null(&s, ":ets");
        db_bind_str(&s, ":etxt", &p->transcript);
        db_bind_int(&s, ":enref", p->nEts);
        db_step(&s);
        db_reset(&s);
        p->idTranscript = db_last_insert_rowid();
      }
    }
    db_bind_int64(&s, ":ets", p->idTranscript);
    db_bind_str(&s, ":etxt", &p->msg);
    db_bind_int(&s, ":enref", 0);
    db_step(&s);
    db_finalize(&s);
    p->idMsg = db_last_insert_rowid();

    /* make entries in emailbox and emailoutq */
    for(i=0; i<p->nTo; i++){
      int okRemote = p->aTo[i].okRemote;
      p->aTo[i].okRemote = 1;
      smtp_server_send_one_user(p, p->aTo[i].z, okRemote);
    }

    /* Fix up the emailblob.enref field of the email message body */
    if( p->nRef ){
      db_multi_exec(
        "UPDATE emailblob SET enref=%d WHERE emailid=%lld", 
        p->nRef, p->idMsg
      );
    }else{
      db_multi_exec(
        "DELETE FROM emailblob WHERE emailid=%lld", p->idMsg
      );
    }

    /* Finish the transaction after all changes are implemented */
    db_commit_transaction();
  }
  smtp_server_clear(p, SMTPSRV_CLEAR_MSG);
}

/*
** COMMAND: test-emailblob-refcheck
**
** Usage: %fossil test-emailblob-refcheck [--repair] [--full]
**
** Verify that the emailblob.enref field is correct.  Report any errors.
** Use the --repair command to fix up the enref field.  The --full option
** gives a full report showing the enref value on all entries in the
** emailblob table.
*/
void test_refcheck_emailblob(void){
  int doRepair;
  int fullReport;
  Blob sql;
  Stmt q;
  int nErr = 0;
  db_find_and_open_repository(0, 0);
  fullReport = find_option("full",0,0)!=0;
  doRepair = find_option("repair",0,0)!=0;
  verify_all_options();
  if( !db_table_exists("repository","emailblob") ){
    fossil_print("emailblob table is not configured - nothing to check\n");
    return;
  }
  db_multi_exec(
    "CREATE TEMP TABLE refcnt(id INTEGER PRIMARY KEY, n);"
    "INSERT INTO refcnt SELECT ets, count(*) FROM ("
    "  SELECT ets FROM emailblob"
    "  UNION ALL"
    "  SELECT emsgid FROM emailbox"
    "  UNION ALL"
    "  SELECT emsgid FROM emailoutq"
    ") WHERE ets IS NOT NULL GROUP BY 1;"
    "INSERT OR IGNORE INTO refcnt(id,n) SELECT emailid, 0 FROM emailblob;"
  );
  if( doRepair ){
    db_multi_exec(
      "UPDATE emailblob SET enref=(SELECT n FROM refcnt WHERE id=emailid)"
    );
  }
  blob_init(&sql, 0, 0);
  blob_append_sql(&sql, 
    "SELECT a.emailid, a.enref, b.n"
    "  FROM emailblob AS a JOIN refcnt AS b ON a.emailid=b.id"
  );
  if( !fullReport ){
    blob_append_sql(&sql, " WHERE a.enref!=b.n");
  }
  db_prepare_blob(&q, &sql);
  blob_reset(&sql);
  while( db_step(&q)==SQLITE_ROW ){
    sqlite3_int64 id = db_column_int64(&q,0);
    int n1 = db_column_int(&q, 1);
    int n2 = db_column_int(&q, 2);
    if( n1!=n2 ) nErr++;
    fossil_print("%12lld %4d %4d%s\n", id, n1, n2, n1!=n2 ? " ERROR" : "");
  }
  db_finalize(&q);
  if( nErr ){
    fossil_print("Number of incorrect emailblob.enref values: %d\n",nErr);
  }
}


/*
** COMMAND: smtpd
**
** Usage: %fossil smtpd [OPTIONS] REPOSITORY
**
** Begin a SMTP conversation with a client using stdin/stdout.  The

Changes to src/stat.c.

49
50
51
52
53
54
55




























































56
57
58
59
60
61
62
    sqlite3_snprintf(nOut, zOut, "%.1fKB", (double)v/1000.0);
  }else if( v<1000000000 ){
    sqlite3_snprintf(nOut, zOut, "%.1fMB", (double)v/1000000.0);
  }else{
    sqlite3_snprintf(nOut, zOut, "%.1fGB", (double)v/1000000000.0);
  }
}





























































/*
** WEBPAGE: stat
**
** Show statistics and global information about the repository.
*/
void stat_page(void){







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
    sqlite3_snprintf(nOut, zOut, "%.1fKB", (double)v/1000.0);
  }else if( v<1000000000 ){
    sqlite3_snprintf(nOut, zOut, "%.1fMB", (double)v/1000000.0);
  }else{
    sqlite3_snprintf(nOut, zOut, "%.1fGB", (double)v/1000000000.0);
  }
}

/*
** Generate stats for the email notification subsystem.
*/
void stats_for_email(void){
  const char *zDest = db_get("email-send-method",0);
  int nSub, nASub, nPend, nDPend;
  const char *zDir, *zDb, *zCmd, *zRelay;
  @ <tr><th>Outgoing&nbsp;Email:</th><td>
  if( fossil_strcmp(zDest,"pipe")==0
   && (zCmd = db_get("email-send-command",0))!=0
  ){
    @ Piped to command "%h(zCmd)"
  }else
  if( fossil_strcmp(zDest,"db")==0
   && (zDb = db_get("email-send-db",0))!=0
  ){
    sqlite3 *db;
    sqlite3_stmt *pStmt;
    int rc;
    @ Queued to database "%h(zDb)"
    rc = sqlite3_open(zDb, &db);
    if( rc==SQLITE_OK ){
      rc = sqlite3_prepare_v2(db, "SELECT count(*) FROM email",-1,&pStmt,0);
      if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
        @ (%,d(sqlite3_column_int(pStmt,0)) messages,
        @ %,d(file_size(zDb,ExtFILE)) bytes)
      }
      sqlite3_finalize(pStmt);
    }
    sqlite3_close(db);
  }else
  if( fossil_strcmp(zDest,"dir")==0
   && (zDir = db_get("email-send-dir",0))!=0
  ){
    @ Written to files in "%h(zDir)"
    @ (%,d(file_directory_size(zDir,0,1)) messages)
  }else
  if( fossil_strcmp(zDest,"relay")==0
   && (zRelay = db_get("email-send-relayhost",0))!=0
  ){
    @ Relay to %h(zRelay) using SMTP
  }
  else{
    @ Off
  }
  @ </td></tr>
  nPend = db_int(0,"SELECT count(*) FROM pending_alert WHERE NOT sentSep");
  nDPend = db_int(0,"SELECT count(*) FROM pending_alert"
                    " WHERE NOT sentDigest");
  @ <tr><th>Pending&nbsp;Alerts:</th><td>
  @ %,d(nPend) normal, %,d(nDPend) digest
  @ </td></tr>
  @ <tr><th>Subscribers:</th><td>
  nSub = db_int(0, "SELECT count(*) FROM subscriber");
  nASub = db_int(0, "SELECT count(*) FROM subscriber WHERE sverified"
                   " AND NOT sdonotcall AND length(ssub)>1");
  @ %,d(nASub) active, %,d(nSub) total
  @ </td></tr>
}

/*
** WEBPAGE: stat
**
** Show statistics and global information about the repository.
*/
void stat_page(void){
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
    if( szFile>=0 ){
      @ <tr><th>Error Log:</th>
      @ <td><a href='%R/errorlog'>%h(g.zErrlog)</a> (%,lld(szFile) bytes)
    }
    @ </td></tr>
  }
  if( g.perm.Admin && email_enabled() ){
    const char *zDest = db_get("email-send-method",0);
    int nSub, nASub, nPend, nDPend;
    const char *zDir, *zDb, *zCmd;
    @ <tr><th>Outgoing&nbsp;Email:</th><td>
    if( fossil_strcmp(zDest,"pipe")==0
     && (zCmd = db_get("email-send-command",0))!=0
    ){
      @ Piped to command "%h(zCmd)"
    }else
    if( fossil_strcmp(zDest,"db")==0
     && (zDb = db_get("email-send-db",0))!=0
    ){
      sqlite3 *db;
      sqlite3_stmt *pStmt;
      int rc;
      @ Queued to database "%h(zDb)"
      rc = sqlite3_open(zDb, &db);
      if( rc==SQLITE_OK ){
        rc = sqlite3_prepare_v2(db, "SELECT count(*) FROM email",-1,&pStmt,0);
        if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
          @ (%,d(sqlite3_column_int(pStmt,0)) messages,
          @ %,d(file_size(zDb,ExtFILE)) bytes)
        }
        sqlite3_finalize(pStmt);
      }
      sqlite3_close(db);
    }else
    if( fossil_strcmp(zDest,"dir")==0
     && (zDir = db_get("email-send-dir",0))!=0
    ){
      @ Written to files in "%h(zDir)"
      @ (%,d(file_directory_size(zDir,0,1)) messages)
    }else{
      @ Off
    }
    @ </td></tr>
    nPend = db_int(0,"SELECT count(*) FROM pending_alert WHERE NOT sentSep");
    nDPend = db_int(0,"SELECT count(*) FROM pending_alert"
                      " WHERE NOT sentDigest");
    @ <tr><th>Pending&nbsp;Alerts:</th><td>
    @ %,d(nPend) normal, %,d(nDPend) digest
    @ </td></tr>
    @ <tr><th>Subscribers:</th><td>
    nSub = db_int(0, "SELECT count(*) FROM subscriber");
    nASub = db_int(0, "SELECT count(*) FROM subscriber WHERE sverified"
                     " AND NOT sdonotcall AND length(ssub)>1");
    @ %,d(nASub) active, %,d(nSub) total
    @ </td></tr>
  }

  @ </table>
  style_footer();
}

/*







<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







265
266
267
268
269
270
271










272





































273
274
275
276
277
278
279
    if( szFile>=0 ){
      @ <tr><th>Error Log:</th>
      @ <td><a href='%R/errorlog'>%h(g.zErrlog)</a> (%,lld(szFile) bytes)
    }
    @ </td></tr>
  }
  if( g.perm.Admin && email_enabled() ){










    stats_for_email();





































  }

  @ </table>
  style_footer();
}

/*

Changes to src/webmail.c.

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
        break;
      }
    }
  }
  emailtoc_free(p);
  blob_reset(&email);
}






































































































































































































/*
** WEBPAGE:  webmail
**
** This page can be used to read content from the EMAILBOX table
** that contains email received by the "fossil smtpd" command.













*/
void webmail_page(void){
  int emailid;
  Stmt q;
  Blob sql;
  int showAll = 0;
  const char *zUser = 0;






  HQuery url;
  login_check_credentials();
  if( g.zLogin==0 ){
    login_needed(0);
    return;
  }
  if( !db_table_exists("repository","emailbox") ){
    style_header("Webmail Not Available");
    @ <p>This repository is not configured to provide webmail</p>
    style_footer();







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






>
>
>
>
>
>
>
>
>
>
>
>
>







>
>
>
>
>
>


|







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
        break;
      }
    }
  }
  emailtoc_free(p);
  blob_reset(&email);
}

/*
** Add the select/option box to the timeline submenu that shows
** the various email message formats.
*/
static void webmail_f_submenu(void){
  static const char *az[] = {
     "0", "Normal",
     "1", "Decoded",
     "2", "Raw",
  };
  style_submenu_multichoice("f", sizeof(az)/(2*sizeof(az[0])), az, 0);
}

/*
** If the first N characters of z[] are the name of a header field
** that should be shown in "Normal" mode, then return 1.
*/
static int webmail_normal_header(const char *z, int N){
  static const char *az[] = {
    "To",  "Cc",  "Bcc",  "Date", "From",  "Subject",
  };
  int i;
  for(i=0; i<sizeof(az)/sizeof(az[0]); i++){
    if( sqlite3_strnicmp(z, az[i], N)==0 ) return 1;
  }
  return 0;
}

/*
** Paint a page showing a single email message
*/
static void webmail_show_one_message(
  HQuery *pUrl,          /* Calling context */
  int emailid,           /* emailbox.ebid to display */
  const char *zUser      /* User who owns it, or NULL if does not matter */
){
  Blob sql;
  Stmt q;
  int eState = -1;
  char zENum[30];
  style_submenu_element("Index", "%s", url_render(pUrl,"id",0,0,0));
  webmail_f_submenu();
  blob_init(&sql, 0, 0);
  db_begin_transaction();
  blob_append_sql(&sql,
    "SELECT decompress(etxt), estate"
    " FROM emailblob, emailbox"
    " WHERE emailid=emsgid AND ebid=%d",
     emailid
  );
  if( zUser ) blob_append_sql(&sql, " AND euser=%Q", zUser);
  db_prepare_blob(&q, &sql);
  blob_reset(&sql);
  style_header("Message %d",emailid);
  if( db_step(&q)==SQLITE_ROW ){
    Blob msg = db_column_text_as_blob(&q, 0);
    int eFormat = atoi(PD("f","0"));
    eState = db_column_int(&q, 1);
    if( eFormat==2 ){
      @ <pre>%h(db_column_text(&q, 0))</pre>
    }else{      
      EmailToc *p = emailtoc_from_email(&msg);
      int i, j;
      @ <p>
      for(i=0; i<p->nHdr; i++){
        char *z = p->azHdr[i];
        email_hdr_unfold(z);
        for(j=0; z[j] && z[j]!=':'; j++){}
        if( eFormat==0 && !webmail_normal_header(z, j) ) continue;
        if( z[j]!=':' ){
          @ %h(z)<br>
        }else{
          z[j] = 0;
          @ <b>%h(z):</b> %h(z+j+1)<br>
        }
      }
      for(i=0; i<p->nBody; i++){
        @ <hr><b>Messsage Body #%d(i): %h(p->aBody[i].zMimetype) \
        if( p->aBody[i].zFilename ){
          @ "%h(p->aBody[i].zFilename)"
        }
        @ </b>
        if( eFormat==0 ){
          if( strncmp(p->aBody[i].zMimetype, "text/plain", 10)!=0 ) continue;
          if( p->aBody[i].zFilename ) continue;
        }else{
          if( strncmp(p->aBody[i].zMimetype, "text/", 5)!=0 ) continue;
        }
        switch( p->aBody[i].encoding ){
          case EMAILENC_B64: {
            int n = 0;
            decodeBase64(p->aBody[i].zContent, &n, p->aBody[i].zContent);
            break;
          }
          case EMAILENC_QUOTED: {
            int n = 0;
            decodeQuotedPrintable(p->aBody[i].zContent, &n);
            break;
          }
        }
        @ <pre>%h(p->aBody[i].zContent)</pre>
      }
    }
  }
  db_finalize(&q);

  if( eState==0 ){
    /* If is message is currently Unread, change it to Read */
    blob_append_sql(&sql,
      "UPDATE emailbox SET estate=1 "
      " WHERE estate=0 AND ebid=%d",
       emailid
    );
    if( zUser ) blob_append_sql(&sql, " AND euser=%Q", zUser);
    db_multi_exec("%s", blob_sql_text(&sql));
    blob_reset(&sql);
    eState = 1;
  }

  url_add_parameter(pUrl, "id", 0);
  sqlite3_snprintf(sizeof(zENum), zENum, "e%d", emailid);
  if( eState==2 ){
    style_submenu_element("Undelete","%s",
      url_render(pUrl,"read","1",zENum,"1"));
  }
  if( eState==1 ){
    style_submenu_element("Delete", "%s",
      url_render(pUrl,"trash","1",zENum,"1"));
    style_submenu_element("Mark As Unread", "%s",
      url_render(pUrl,"unread","1",zENum,"1"));
  }
  if( eState==3 ){
    style_submenu_element("Delete", "%s",
      url_render(pUrl,"trash","1",zENum,"1"));
  }

  db_end_transaction(0);
  style_footer();
  return;
}

/*
** Scan the query parameters looking for parameters with name of the
** form "eN" where N is an integer.  For all such integers, change
** the state of every emailbox entry with ebid==N to eStateNew provided
** that either zUser is NULL or matches.
**
** Or if eNewState==99, then delete the entries.
*/
static void webmail_change_state(int eNewState, const char *zUser){
  Blob sql;
  int sep = '(';
  int i;
  const char *zName;
  int n;
  if( !cgi_csrf_safe(0) ) return;
  blob_init(&sql, 0, 0);
  if( eNewState==99 ){
    blob_append_sql(&sql, "DELETE FROM emailbox WHERE estate==2 AND ebid IN ");
  }else{
    blob_append_sql(&sql, "UPDATE emailbox SET estate=%d WHERE ebid IN ",
                    eNewState);
  }
  for(i=0; (zName = cgi_parameter_name(i))!=0; i++){
    if( zName[0]!='e' ) continue;
    if( !fossil_isdigit(zName[1]) ) continue;
    n = atoi(zName+1);
    blob_append_sql(&sql, "%c%d", sep, n);
    sep = ',';
  }
  if( zUser ){
    blob_append_sql(&sql, ") AND euser=%Q", zUser);
  }else{
    blob_append_sql(&sql, ")");
  }
  if( sep==',' ){
    db_multi_exec("%s", blob_sql_text(&sql));
  }
  blob_reset(&sql);
}


/*
** Add the select/option box to the timeline submenu that shows
** which messages to include in the index.
*/
static void webmail_d_submenu(void){
  static const char *az[] = {
     "0", "InBox",
     "1", "Unread",
     "2", "Trash",
     "3", "Sent",
     "4", "Everything",
  };
  style_submenu_multichoice("d", sizeof(az)/(2*sizeof(az[0])), az, 0);
}

/*
** WEBPAGE:  webmail
**
** This page can be used to read content from the EMAILBOX table
** that contains email received by the "fossil smtpd" command.
**
** Query parameters:
**
**     id=N                 Show a single email entry emailbox.ebid==N
**     f=N                  Display format.  0: decoded 1: raw
**     user=USER            Show mailbox for USER (admin only).
**     user=*               Show mailbox for all users (admin only).
**     d=N                  0: inbox+unread 1: unread-only 2: trash 3: all
**     eN                   Select email entry emailbox.ebid==N
**     trash                Move selected entries to trash (estate=2)
**     read                 Mark selected entries as read (estate=1)
**     unread               Mark selected entries as unread (estate=0)
**  
*/
void webmail_page(void){
  int emailid;
  Stmt q;
  Blob sql;
  int showAll = 0;
  const char *zUser = 0;
  int d = 0;               /* Display mode.  0..3.  d= query parameter */
  int pg = 0;              /* Page number */
  int N = 50;              /* Results per page */
  int got;                 /* Number of results on this page */
  char zPPg[30];           /* Previous page */
  char zNPg[30];           /* Next page */
  HQuery url;
  login_check_credentials();
  if( !login_is_individual() ){
    login_needed(0);
    return;
  }
  if( !db_table_exists("repository","emailbox") ){
    style_header("Webmail Not Available");
    @ <p>This repository is not configured to provide webmail</p>
    style_footer();
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
    if( zUser ){
      url_add_parameter(&url, "user", zUser);
      if( fossil_strcmp(zUser,"*")==0 ){
        showAll = 1;
        zUser = 0;
      }
    }
  }
  if( emailid>0 ){
    style_submenu_element("Index", "%s", url_render(&url,"id",0,0,0));
    blob_init(&sql, 0, 0);
    blob_append_sql(&sql, "SELECT decompress(etxt)"
                          " FROM emailblob WHERE emailid=%d",
                          emailid);
    if( !g.perm.Admin ){
      blob_append_sql(&sql, " AND EXISTS(SELECT 1 FROM emailbox WHERE"
                            " euser=%Q AND emsgid=emailid)", g.zLogin);
    }
    db_prepare_blob(&q, &sql);
    blob_reset(&sql);
    if( db_step(&q)==SQLITE_ROW ){
      Blob msg = db_column_text_as_blob(&q, 0);
      url_add_parameter(&url, "id", P("id"));
      style_header("Message %d",emailid);
      if( PB("raw") ){
        @ <pre>%h(db_column_text(&q, 0))</pre>
        style_submenu_element("Decoded", "%s", url_render(&url,"raw",0,0,0));
      }else{      
        EmailToc *p = emailtoc_from_email(&msg);
        int i, j;
        style_submenu_element("Raw", "%s", url_render(&url,"raw","1",0,0));
        @ <p>
        for(i=0; i<p->nHdr; i++){
          char *z = p->azHdr[i];
          email_hdr_unfold(z);
          for(j=0; z[j] && z[j]!=':'; j++){}
          if( z[j]!=':' ){
            @ %h(z)<br>
          }else{
            z[j] = 0;
            @ <b>%h(z):</b> %h(z+j+1)<br>
          }
        }
        for(i=0; i<p->nBody; i++){
          @ <hr><b>Messsage Body #%d(i): %h(p->aBody[i].zMimetype) \
          if( p->aBody[i].zFilename ){
            @ "%h(p->aBody[i].zFilename)"
          }
          @ </b>
          if( strncmp(p->aBody[i].zMimetype, "text/", 5)!=0 ) continue;
          switch( p->aBody[i].encoding ){
            case EMAILENC_B64: {
              int n = 0;
              decodeBase64(p->aBody[i].zContent, &n, p->aBody[i].zContent);
              break;
            }
            case EMAILENC_QUOTED: {
              int n = 0;
              decodeQuotedPrintable(p->aBody[i].zContent, &n);
              break;
            }
          }
          @ <pre>%h(p->aBody[i].zContent)</pre>
        }
      }      
      style_footer();
      db_finalize(&q);
      return;
    }
    db_finalize(&q);
  }
  style_header("Webmail");






  blob_init(&sql, 0, 0);
  blob_append_sql(&sql,
        /*    0       1                           2        3        4      5 */


    "SELECT efrom, datetime(edate,'unixepoch'), estate, esubject, emsgid, euser"



    " FROM emailbox"
  );























  if( showAll ){
    style_submenu_element("My Emails", "%s", url_render(&url,"user",0,0,0));
  }else if( zUser!=0 ){
    style_submenu_element("All Users", "%s", url_render(&url,"user","*",0,0));
    if( fossil_strcmp(zUser, g.zLogin)!=0 ){
      style_submenu_element("My Emails", "%s", url_render(&url,"user",0,0,0));
    }
    if( zUser ){
      blob_append_sql(&sql, " WHERE euser=%Q", zUser);
    }else{
      blob_append_sql(&sql, " WHERE euser=%Q", g.zLogin);
    }
  }else{
    if( g.perm.Admin ){
      style_submenu_element("All Users", "%s", url_render(&url,"user","*",0,0));
    }
    blob_append_sql(&sql, " WHERE euser=%Q", g.zLogin);
  }

  blob_append_sql(&sql, " ORDER BY edate DESC limit 50");


  db_prepare_blob(&q, &sql);
  blob_reset(&sql);
























  @ <ol>
  while( db_step(&q)==SQLITE_ROW ){
    const char *zId = db_column_text(&q,4);
    const char *zFrom = db_column_text(&q, 0);
    const char *zDate = db_column_text(&q, 1);
    const char *zSubject = db_column_text(&q, 3);
    @ <li>




    if( showAll ){
      const char *zTo = db_column_text(&q,5);
      @ <a href="%s(url_render(&url,"user",zTo,0,0))">%h(zTo)</a>:
    }
    @ <a href="%s(url_render(&url,"id",zId,0,0))">\
    @ %h(zFrom) &rarr; %h(zSubject)</a>
    @ %h(zDate)
  }
  db_finalize(&q);
























































  @ </ol>





























  style_footer(); 
}







|
<
<
<
<
<
<
<
<
|
|
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<

>
>
>
>
>
>


|
>
>
|
>
>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|

|





|

>
|
>
>
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

|
|
|
|
|
>
>
>
>


|

<
<
|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

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
    if( zUser ){
      url_add_parameter(&url, "user", zUser);
      if( fossil_strcmp(zUser,"*")==0 ){
        showAll = 1;
        zUser = 0;
      }
    }
  }else{








    zUser = g.zLogin;
  }




  if( P("d") ) url_add_parameter(&url, "d", P("d"));
  if( emailid>0 ){










    webmail_show_one_message(&url, emailid, zUser);
































    return;
  }


  style_header("Webmail");
  webmail_d_submenu();
  db_begin_transaction();
  if( P("trash")!=0 ) webmail_change_state(2,zUser);
  if( P("unread")!=0 ) webmail_change_state(0,zUser);
  if( P("read")!=0 ) webmail_change_state(1,zUser);
  if( P("purge")!=0 ) webmail_change_state(99,zUser);
  blob_init(&sql, 0, 0);
  blob_append_sql(&sql,
    "CREATE TEMP TABLE tmbox AS "
    "SELECT ebid,"                   /* 0 */
    " efrom,"                        /* 1 */
    " datetime(edate,'unixepoch'),"  /* 2 */
    " estate,"                       /* 3 */
    " esubject,"                     /* 4 */
    " euser"                         /* 5 */
    " FROM emailbox"
  );
  d = atoi(PD("d","0"));
  switch( d ){
    case 0: {   /* Show unread and read */
      blob_append_sql(&sql, " WHERE estate<=1");
      break;
    }
    case 1: {   /* Unread messages only */
      blob_append_sql(&sql, " WHERE estate=0");
      break;
    }
    case 2: {   /* Trashcan only */
      blob_append_sql(&sql, " WHERE estate=2");
      break;
    }
    case 3: {   /* Outgoing email only */
      blob_append_sql(&sql, " WHERE estate=3");
      break;
    }
    case 4: {   /* Everything */
      blob_append_sql(&sql, " WHERE 1");
      break;
    }
  }
  if( showAll ){
    style_submenu_element("My Emails", "%s", url_render(&url,"user",0,0,0));
  }else if( zUser!=0 ){
    style_submenu_element("All Users", "%s", url_render(&url,"user","*",0,0));
    if( fossil_strcmp(zUser, g.zLogin)!=0 ){
      style_submenu_element("My Emails", "%s", url_render(&url,"user",0,0,0));
    }
    if( zUser ){
      blob_append_sql(&sql, " AND euser=%Q", zUser);
    }else{
      blob_append_sql(&sql, " AND euser=%Q", g.zLogin);
    }
  }else{
    if( g.perm.Admin ){
      style_submenu_element("All Users", "%s", url_render(&url,"user","*",0,0));
    }
    blob_append_sql(&sql, " AND euser=%Q", g.zLogin);
  }
  pg = atoi(PD("pg","0"));
  blob_append_sql(&sql, " ORDER BY edate DESC limit %d offset %d", N+1, pg*N);
  db_multi_exec("%s", blob_sql_text(&sql));
  got = db_int(0, "SELECT count(*) FROM tmbox");
  db_prepare(&q, "SELECT * FROM tmbox LIMIT %d", N);
  blob_reset(&sql);
  @ <form action="%R/webmail" method="POST">
  @ <table border="0" width="100%%">
  @ <tr><td align="left">
  if( d==2 ){
    @ <input type="submit" name="read" value="Undelete">
    @ <input type="submit" name="purge" value="Delete Permanently">
  }else{
    @ <input type="submit" name="trash", value="Delete">
    if( d!=1 ){
      @ <input type="submit" name="unread" value="Mark as unread">
    }
    @ <input type="submit" name="read" value="Mark as read">
  }
  @ <a href="%s(url_render(&url,0,0,0,0))">refresh</a>
  @ </td><td align="right">
  if( pg>0 ){
    sqlite3_snprintf(sizeof(zPPg), zPPg, "%d", pg-1);
    @ <a href="%s(url_render(&url,"pg",zPPg,0,0))">&lt; Newer</a>&nbsp;&nbsp;
  }
  if( got>50 ){
    sqlite3_snprintf(sizeof(zNPg),zNPg,"%d",pg+1);
    @ <a href="%s(url_render(&url,"pg",zNPg,0,0))">Older &gt;</a></td>
  }
  @ </table>
  @ <table>
  while( db_step(&q)==SQLITE_ROW ){
    const char *zId = db_column_text(&q,0);
    const char *zFrom = db_column_text(&q, 1);
    const char *zDate = db_column_text(&q, 2);
    const char *zSubject = db_column_text(&q, 4);
    @ <tr>
    @ <td><input type="checkbox" name="e%s(zId)"></td>
    @ <td>%h(zFrom)</td>
    @ <td><a href="%s(url_render(&url,"id",zId,0,0))">%h(zSubject)</a> \
    @ %s(zDate)</td>
    if( showAll ){
      const char *zTo = db_column_text(&q,5);
      @ <td><a href="%s(url_render(&url,"user",zTo,0,0))">%h(zTo)</a></td>
    }


    @ </tr>
  }
  db_finalize(&q);
  @ </table>
  @ </form>
  style_footer();
  db_end_transaction(0);
}

/*
** WEBPAGE:  test-emailblob
**
** This page, accessible only to administrators, allows easy viewing of
** the emailblob table - the table that contains the text of email messages
** both inbound and outbound, and transcripts of SMTP sessions.
**
**    id=N          Show the text of emailblob with emailid==N
**    
*/
void webmail_emailblob_page(void){
  int id = atoi(PD("id","0"));
  Stmt q;
  login_check_credentials();
  if( !g.perm.Setup ){
    login_needed(0);
    return;
  }
  add_content_sql_commands(g.db);
  style_header("emailblob table");
  if( id>0 ){
    style_submenu_element("Index", "%R/test-emailblob");
    @ <ul>
    db_prepare(&q, "SELECT emailid FROM emailblob WHERE ets=%d", id);
    while( db_step(&q)==SQLITE_ROW ){
      int id = db_column_int(&q, 0);
      @ <li> <a href="%R/test-emailblob?id=%d(id)">emailblob entry %d(id)</a>
    }
    db_finalize(&q);
    db_prepare(&q, "SELECT euser, estate FROM emailbox WHERE emsgid=%d", id);
    while( db_step(&q)==SQLITE_ROW ){
      const char *zUser = db_column_text(&q, 0);
      int e = db_column_int(&q, 1);
      @ <li> emailbox for %h(zUser) state %d(e)
    }
    db_finalize(&q);
    db_prepare(&q, "SELECT efrom, eto FROM emailoutq WHERE emsgid=%d", id);
    while( db_step(&q)==SQLITE_ROW ){
      const char *zFrom = db_column_text(&q, 0);
      const char *zTo = db_column_text(&q, 1);
      @ <li> emailoutq message body from %h(zFrom) to %h(zTo)
    }
    db_finalize(&q);
    db_prepare(&q, "SELECT efrom, eto FROM emailoutq WHERE ets=%d", id);
    while( db_step(&q)==SQLITE_ROW ){
      const char *zFrom = db_column_text(&q, 0);
      const char *zTo = db_column_text(&q, 1);
      @ <li> emailoutq transcript from %h(zFrom) to %h(zTo)
    }
    db_finalize(&q);
    @ </ul>
    @ <hr>
    db_prepare(&q, "SELECT decompress(etxt) FROM emailblob WHERE emailid=%d",
               id);
    while( db_step(&q)==SQLITE_ROW ){
      const char *zContent = db_column_text(&q, 0);
      @ <pre>%h(zContent)</pre>
    }
    db_finalize(&q);
  }else{
    db_prepare(&q,
       "SELECT emailid, enref, ets, datetime(etime,'unixepoch')"
       " FROM emailblob ORDER BY etime DESC, emailid DESC");
    @ <table border="1" cellpadding="5" cellspacing="0">
    @ <tr><th> emailid <th> enref <th> ets <th> etime</tr>
    while( db_step(&q)==SQLITE_ROW ){
      int id = db_column_int(&q, 0);
      int nref = db_column_int(&q, 1);
      int ets = db_column_int(&q, 2);
      const char *zDate = db_column_text(&q, 3);
      @ <tr>
      @  <td><a href="%R/test-emailblob?id=%d(id)">%d(id)</a>
      @  <td>%d(nref)</td>
      @  <td>%d(ets)</td>
      @  <td>%h(zDate)</td>
      @ </tr>
    }
    @ </table>
    db_finalize(&q);
  }
  style_footer();
}