Fossil

Check-in Differences
Login

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

Difference From release To trunk

2020-09-28
04:03
If I am reading this correctly, the JPEG and PNG bars are the ones increasing with each commit, not so much the TIFF bar due to using uncompressed TIFF (Leaf check-in: 309af345 user: andygoth tags: trunk)
02:29
Move change to intended location (shouldn't have been on branch) (check-in: fb6b093d user: andygoth tags: trunk)
2020-08-20
13:27
Version 2.12.1 (Leaf check-in: b98ce23d user: drh tags: release, branch-2.12, version-2.12.1)
13:01
2.12.1 release candidate with security fixes. (check-in: 40feec32 user: drh tags: branch-2.12)

Changes to VERSION.

1
2.12.1
|
1
2.13

Changes to auto.def.

174
175
176
177
178
179
180


181
182

183
184
185
186
187
188
189
       configlog "Compiled OK: [join $cmdline]"
       configlog "============"
    }
    if {!$ok} {
      user-error "unable to compile SQLite compatibility test program"
    }
    set err [catch {exec-with-stderr ./conftest__} result errinfo]


    if {$err} {
      user-error $result

    }
    file delete ./conftest__
  }
  test_system_sqlite

}








>
>
|
|
>







174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
       configlog "Compiled OK: [join $cmdline]"
       configlog "============"
    }
    if {!$ok} {
      user-error "unable to compile SQLite compatibility test program"
    }
    set err [catch {exec-with-stderr ./conftest__} result errinfo]
    if {[get-define build] eq [get-define host]} {
      set err [catch {exec-with-stderr ./conftest__} result errinfo]
      if {$err} {
        user-error $result
      }
    }
    file delete ./conftest__
  }
  test_system_sqlite

}

Changes to skins/ardoise/css.txt.

7
8
9
10
11
12
13

14
15
16
17
18
19
20
...
570
571
572
573
574
575
576



577
578
579
580
581
582
583
...
947
948
949
950
951
952
953
954


955
956
957
958
959
960
961
img,
legend,
table.login_out,
table.login_out td,
tr.timelineCurrent,
tr.timelineCurrent td.timelineTableCell,
tr.timelineSelected {

  border: 0
}
ol,
p,
ul {
  margin-top: 0
}
................................................................................
  margin: 0 .2rem;
  font-size: 90%;
  white-space: nowrap;
  background: #000;
  border: 2px solid #bbb;
  border-radius: 5px
}



pre > code {
  padding: 1rem 1.5rem;
  white-space: pre
}
td,
th {
  padding: 1px 5px;
................................................................................
span.timelineSelected {
  border-radius: 5px;
  border: solid #ff8000;
  vertical-align: top;
  text-align: left;
  background: #442800
}
.timelineSelected {}


.timelineSecondary {}
.timelineSecondary > .timelineColumnarCell,
.timelineSecondary > .timelineCompactCell,
.timelineSecondary > .timelineDetailCell,
.timelineSecondary > .timelineModernCell,
.timelineSecondary > .timelineVerboseCell {
  padding: .75em;







>







 







>
>
>







 







|
>
>







7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
...
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
img,
legend,
table.login_out,
table.login_out td,
tr.timelineCurrent,
tr.timelineCurrent td.timelineTableCell,
tr.timelineSelected {
  background-color: initial;
  border: 0
}
ol,
p,
ul {
  margin-top: 0
}
................................................................................
  margin: 0 .2rem;
  font-size: 90%;
  white-space: nowrap;
  background: #000;
  border: 2px solid #bbb;
  border-radius: 5px
}
table.numbered-lines td.file-content > pre {
  margin-top: -2px/*offset CODE tag border*/;
}
pre > code {
  padding: 1rem 1.5rem;
  white-space: pre
}
td,
th {
  padding: 1px 5px;
................................................................................
span.timelineSelected {
  border-radius: 5px;
  border: solid #ff8000;
  vertical-align: top;
  text-align: left;
  background: #442800
}
.timelineSelected {
  box-shadow: none;
}
.timelineSecondary {}
.timelineSecondary > .timelineColumnarCell,
.timelineSecondary > .timelineCompactCell,
.timelineSecondary > .timelineDetailCell,
.timelineSecondary > .timelineModernCell,
.timelineSecondary > .timelineVerboseCell {
  padding: .75em;

Changes to skins/default/css.txt.

222
223
224
225
226
227
228


229
230
231
232
233
234
235
236
}
span.submenuctrl {
  white-space: nowrap;
}
div.submenu label {
  white-space: nowrap;
}



@media screen and (max-width: 600px) {
  /* Spacing for mobile */
  body {
    padding-left: 4px;
    padding-right: 4px;
  }
  .title {







>
>
|







222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
}
span.submenuctrl {
  white-space: nowrap;
}
div.submenu label {
  white-space: nowrap;
}
.fossil-tooltip.help-buttonlet-content {
  background-color: lightyellow;
}
@media screen and (max-width: 600px) {
  /* Spacing for mobile */
  body {
    padding-left: 4px;
    padding-right: 4px;
  }
  .title {

Changes to skins/eagle/css.txt.

397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
  font-family: "courier new";
}

div.filetreeline:hover {
  background-color: #7EA2D9;
}

div.selectedText {
  background-color: #7EA2D9;
}

.statistics-report-graph-line {
  background-color: #7EA2D9;
}








|







397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
  font-family: "courier new";
}

div.filetreeline:hover {
  background-color: #7EA2D9;
}

table.numbered-lines td.line-numbers span.selected-line {
  background-color: #7EA2D9;
}

.statistics-report-graph-line {
  background-color: #7EA2D9;
}

Changes to skins/xekri/css.txt.

998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
....
1116
1117
1118
1119
1120
1121
1122







/**************************************
 * Did not encounter these
 */

/* selected lines of text within a linenumbered artifact display */
div.selectedText {
  font-weight: bold;
  color: #00f;
  background-color: #d5d5ff;
  border: 1px #00f solid;
}

/* format for missing privileges note on user setup page */
p.missingPriv {
  color: #00f;
}

................................................................................
tr.row0 {
  /* use default */
}
/* odd table row color */
tr.row1 {
  /* Use default */
}












|



|







 







>
>
>
>
>
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
....
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127


/**************************************
 * Did not encounter these
 */

/* selected lines of text within a linenumbered artifact display */
table.numbered-lines td.line-numbers span.selected-line {
  font-weight: bold;
  color: #00f;
  background-color: #d5d5ff;
  border-color: #00f;
}

/* format for missing privileges note on user setup page */
p.missingPriv {
  color: #00f;
}

................................................................................
tr.row0 {
  /* use default */
}
/* odd table row color */
tr.row1 {
  /* Use default */
}

.fossil-tooltip.help-buttonlet-content {
  background-color: #111;
  border: 1px solid rgba(255,255,255,0.5);
}

Changes to src/add.c.

167
168
169
170
171
172
173

174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
...
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
...
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
...
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
...
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
...
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
                " WHERE pathname=%Q %s", zPath, filename_collation()) ){
    db_multi_exec("UPDATE vfile SET deleted=0"
                  " WHERE pathname=%Q %s AND deleted",
                  zPath, filename_collation());
  }else{
    char *zFullname = mprintf("%s%s", g.zLocalRoot, zPath);
    int isExe = file_isexe(zFullname, RepoFILE);

    if( file_nondir_objects_on_path(g.zLocalRoot, zFullname) ){
      /* Do not add unsafe files to the vfile */
      doSkip = 1;
    }else{
      db_multi_exec(
        "INSERT INTO vfile(vid,deleted,rid,mrid,pathname,isexe,islink,mhash)"
        "VALUES(%d,0,0,0,%Q,%d,%d,NULL)",
        vid, zPath, isExe, file_islink(0));
    }
    fossil_free(zFullname);
  }
  if( db_changes() && !doSkip ){
    fossil_print("ADDED  %s\n", zPath);
    return 1;
  }else{
................................................................................
  }
}

/*
** Add all files in the sfile temp table.
**
** Automatically exclude the repository file and any other files
** with reserved names. Also exclude files that are beneath an 
** existing symlink.
*/
static int add_files_in_sfile(int vid){
  const char *zRepo;        /* Name of the repository database file */
  int nAdd = 0;             /* Number of files added */
  int i;                    /* Loop counter */
  const char *zReserved;    /* Name of a reserved file */
................................................................................
    zRepo = blob_str(&repoName);
  }
  if( filenames_are_case_sensitive() ){
    xCmp = fossil_strcmp;
  }else{
    xCmp = fossil_stricmp;
  }
  db_prepare(&loop, 
     "SELECT pathname FROM sfile"
     " WHERE pathname NOT IN ("
       "SELECT sfile.pathname FROM vfile, sfile"
       " WHERE vfile.islink"
       "   AND NOT vfile.deleted"
       "   AND sfile.pathname>(vfile.pathname||'/')"
       "   AND sfile.pathname<(vfile.pathname||'0'))"
................................................................................
**          setting is non-zero, files WILL BE removed from disk as well.
**          This does NOT apply to the 'forget' command.
**
** Options:
**   --soft                  Skip removing files from the checkout.
**                           This supersedes the --hard option.
**   --hard                  Remove files from the checkout.
**   --case-sensitive <BOOL> Override the case-sensitive setting.
**   -n|--dry-run            If given, display instead of run actions.
**   --reset                 Reset the DELETED state of a checkout, such
**                           that all newly-rm'd (but not yet committed)
**                           files are no longer removed. No flags other
**                           than --verbose or --dry-run may be used with
**                           --reset.
**   --verbose|-v            Outputs information about each --reset file.
................................................................................
**
** The case-sensitive setting determines the default value.  If
** the case-sensitive setting is undefined, then case sensitivity
** defaults off for Cygwin, Mac and Windows and on for all other unix.
** If case-sensitivity is enabled in the windows kernel, the Cygwin port
** of fossil.exe can detect that, and modifies the default to 'on'.
**
** The --case-sensitive <BOOL> command-line option overrides any
** setting.
*/
int filenames_are_case_sensitive(void){
  static int caseSensitive;
  static int once = 1;

  if( once ){
................................................................................
**          setting is non-zero, files WILL BE renamed or moved on disk
**          as well.  This does NOT apply to the 'rename' command.
**
** Options:
**   --soft                    Skip moving files within the checkout.
**                             This supersedes the --hard option.
**   --hard                    Move files within the checkout.
**   --case-sensitive <BOOL>   Override the case-sensitive setting.
**   -n|--dry-run              If given, display instead of run actions.
**
** See also: [[changes]], [[status]]
*/
void mv_cmd(void){
  int i;
  int vid;







>







|







 







|







 







|







 







|







 







|







 







|







167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
...
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
...
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
...
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
...
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
...
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
                " WHERE pathname=%Q %s", zPath, filename_collation()) ){
    db_multi_exec("UPDATE vfile SET deleted=0"
                  " WHERE pathname=%Q %s AND deleted",
                  zPath, filename_collation());
  }else{
    char *zFullname = mprintf("%s%s", g.zLocalRoot, zPath);
    int isExe = file_isexe(zFullname, RepoFILE);
    int isLink = file_islink(0);
    if( file_nondir_objects_on_path(g.zLocalRoot, zFullname) ){
      /* Do not add unsafe files to the vfile */
      doSkip = 1;
    }else{
      db_multi_exec(
        "INSERT INTO vfile(vid,deleted,rid,mrid,pathname,isexe,islink,mhash)"
        "VALUES(%d,0,0,0,%Q,%d,%d,NULL)",
        vid, zPath, isExe, isLink);
    }
    fossil_free(zFullname);
  }
  if( db_changes() && !doSkip ){
    fossil_print("ADDED  %s\n", zPath);
    return 1;
  }else{
................................................................................
  }
}

/*
** Add all files in the sfile temp table.
**
** Automatically exclude the repository file and any other files
** with reserved names. Also exclude files that are beneath an
** existing symlink.
*/
static int add_files_in_sfile(int vid){
  const char *zRepo;        /* Name of the repository database file */
  int nAdd = 0;             /* Number of files added */
  int i;                    /* Loop counter */
  const char *zReserved;    /* Name of a reserved file */
................................................................................
    zRepo = blob_str(&repoName);
  }
  if( filenames_are_case_sensitive() ){
    xCmp = fossil_strcmp;
  }else{
    xCmp = fossil_stricmp;
  }
  db_prepare(&loop,
     "SELECT pathname FROM sfile"
     " WHERE pathname NOT IN ("
       "SELECT sfile.pathname FROM vfile, sfile"
       " WHERE vfile.islink"
       "   AND NOT vfile.deleted"
       "   AND sfile.pathname>(vfile.pathname||'/')"
       "   AND sfile.pathname<(vfile.pathname||'0'))"
................................................................................
**          setting is non-zero, files WILL BE removed from disk as well.
**          This does NOT apply to the 'forget' command.
**
** Options:
**   --soft                  Skip removing files from the checkout.
**                           This supersedes the --hard option.
**   --hard                  Remove files from the checkout.
**   --case-sensitive BOOL   Override the case-sensitive setting.
**   -n|--dry-run            If given, display instead of run actions.
**   --reset                 Reset the DELETED state of a checkout, such
**                           that all newly-rm'd (but not yet committed)
**                           files are no longer removed. No flags other
**                           than --verbose or --dry-run may be used with
**                           --reset.
**   --verbose|-v            Outputs information about each --reset file.
................................................................................
**
** The case-sensitive setting determines the default value.  If
** the case-sensitive setting is undefined, then case sensitivity
** defaults off for Cygwin, Mac and Windows and on for all other unix.
** If case-sensitivity is enabled in the windows kernel, the Cygwin port
** of fossil.exe can detect that, and modifies the default to 'on'.
**
** The "--case-sensitive BOOL" command-line option overrides any
** setting.
*/
int filenames_are_case_sensitive(void){
  static int caseSensitive;
  static int once = 1;

  if( once ){
................................................................................
**          setting is non-zero, files WILL BE renamed or moved on disk
**          as well.  This does NOT apply to the 'rename' command.
**
** Options:
**   --soft                    Skip moving files within the checkout.
**                             This supersedes the --hard option.
**   --hard                    Move files within the checkout.
**   --case-sensitive BOOL     Override the case-sensitive setting.
**   -n|--dry-run              If given, display instead of run actions.
**
** See also: [[changes]], [[status]]
*/
void mv_cmd(void){
  int i;
  int vid;

Changes to src/ajax.c.

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
...
128
129
130
131
132
133
134
135

136
137
138
139
140
141
142
** Emits JS code which initializes the
** fossil.page.previewModes object to a map of AJAX_RENDER_xxx values
** and symbolic names for use by client-side scripts.
**
** If addScriptTag is true then the output is wrapped in a SCRIPT tag
** with the current nonce, else no SCRIPT tag is emitted.
**
** Requires that style_emit_script_fossil_bootstrap() has already been
** called in order to initialize the window.fossil.page object.
*/
void ajax_emit_js_preview_modes(int addScriptTag){
  if(addScriptTag){
    style_emit_script_tag(0,0);
    CX("\n");
  }
  CX("fossil.page.previewModes={"
     "guess: %d, %d: 'guess', wiki: %d, %d: 'wiki',"
     "htmlIframe: %d, %d: 'htmlIframe', "
     "htmlInline: %d, %d: 'htmlInline', "
     "text: %d, %d: 'text'"
     "};\n",
     AJAX_RENDER_GUESS, AJAX_RENDER_GUESS,
     AJAX_RENDER_WIKI, AJAX_RENDER_WIKI,
     AJAX_RENDER_HTML_IFRAME, AJAX_RENDER_HTML_IFRAME,
     AJAX_RENDER_HTML_INLINE, AJAX_RENDER_HTML_INLINE,
     AJAX_RENDER_PLAIN_TEXT, AJAX_RENDER_PLAIN_TEXT);
  if(addScriptTag){
    style_emit_script_tag(1,0);
  }
}

/*
** Returns a value from the ajax_render_modes enum, based on the
** given mime type string (which may be NULL), defaulting to
** AJAX_RENDER_PLAIN_TEXT.
................................................................................
    case AJAX_RENDER_WIKI:
      safe_html_context(DOCSRC_FILE);
      wiki_render_by_mimetype(pContent, zMime);
      break;
    default:{
      const char *zContent = blob_str(pContent);
      if(AJAX_PREVIEW_LINE_NUMBERS & flags){
        output_text_with_line_numbers(zContent, "on");

      }else{
        const char *zExt = strrchr(zName,'.');
        if(zExt && zExt[1]){
          CX("<pre><code class='language-%s'>%h</code></pre>",
             zExt+1, zContent);
        }else{
          CX("<pre>%h</pre>", zContent);







|




|
<













|







 







|
>







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
...
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
** Emits JS code which initializes the
** fossil.page.previewModes object to a map of AJAX_RENDER_xxx values
** and symbolic names for use by client-side scripts.
**
** If addScriptTag is true then the output is wrapped in a SCRIPT tag
** with the current nonce, else no SCRIPT tag is emitted.
**
** Requires that builtin_emit_script_fossil_bootstrap() has already been
** called in order to initialize the window.fossil.page object.
*/
void ajax_emit_js_preview_modes(int addScriptTag){
  if(addScriptTag){
    style_script_begin(__FILE__,__LINE__);

  }
  CX("fossil.page.previewModes={"
     "guess: %d, %d: 'guess', wiki: %d, %d: 'wiki',"
     "htmlIframe: %d, %d: 'htmlIframe', "
     "htmlInline: %d, %d: 'htmlInline', "
     "text: %d, %d: 'text'"
     "};\n",
     AJAX_RENDER_GUESS, AJAX_RENDER_GUESS,
     AJAX_RENDER_WIKI, AJAX_RENDER_WIKI,
     AJAX_RENDER_HTML_IFRAME, AJAX_RENDER_HTML_IFRAME,
     AJAX_RENDER_HTML_INLINE, AJAX_RENDER_HTML_INLINE,
     AJAX_RENDER_PLAIN_TEXT, AJAX_RENDER_PLAIN_TEXT);
  if(addScriptTag){
    style_script_end();
  }
}

/*
** Returns a value from the ajax_render_modes enum, based on the
** given mime type string (which may be NULL), defaulting to
** AJAX_RENDER_PLAIN_TEXT.
................................................................................
    case AJAX_RENDER_WIKI:
      safe_html_context(DOCSRC_FILE);
      wiki_render_by_mimetype(pContent, zMime);
      break;
    default:{
      const char *zContent = blob_str(pContent);
      if(AJAX_PREVIEW_LINE_NUMBERS & flags){
        output_text_with_line_numbers(zContent, blob_size(pContent),
                                      zName, "on", 0);
      }else{
        const char *zExt = strrchr(zName,'.');
        if(zExt && zExt[1]){
          CX("<pre><code class='language-%s'>%h</code></pre>",
             zExt+1, zContent);
        }else{
          CX("<pre>%h</pre>", zContent);

Changes to src/alerts.c.

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
....
1767
1768
1769
1770
1771
1772
1773

1774
1775
1776
1777
1778
1779
1780
1781

1782
1783
1784
1785
1786
1787
1788
/*
** SETTING: email-subname             width=16
** This is a short name used to identifies the repository in the Subject:
** line of email alerts. Traditionally this name is included in square
** brackets. Examples: "[fossil-src]", "[sqlite-src]".
*/
/*
** SETTING: email-send-method         width=5 default=off
** Determine the method used to send email.  Allowed values are
** "off", "relay", "pipe", "dir", "db", and "stdout".  The "off" value
** means no email is ever sent.  The "relay" value means emails are sent
** to an Mail Sending Agent using SMTP located at email-send-relayhost.
** The "pipe" value means email messages are piped into a command 
** determined by the email-send-command setting. The "dir" value means
** emails are written to individual files in a directory determined
** by the email-send-dir setting.  The "db" value means that emails
** are added to an SQLite database named by the* email-send-db setting.
** The "stdout" value writes email text to standard output, for debugging.
*/
/*
** SETTING: email-send-command       width=40
** This is a command to which outbound email content is piped when the
** email-send-method is set to "pipe".  The command must extract
** recipient, sender, subject, and all other relevant information
** from the email header.
*/
/*
** SETTING: email-send-dir           width=40
** This is a directory into which outbound emails are written as individual
** files if the email-send-method is set to "dir".
*/
/*
** SETTING: email-send-db            width=40
** This is an SQLite database file into which outbound emails are written
** if the email-send-method is set to "db".
*/
/*
** SETTING: email-self               width=40
** This is the email address for the repository.  Outbound emails add
** this email address as the "From:" field.
*/
/*
** SETTING: email-send-relayhost      width=40
** This is the hostname and TCP port to which output email messages
** are sent when email-send-method is "relay".  There should be an
** SMTP server configured as a Mail Submission Agent listening on the
** designated host and port and all times.
*/


................................................................................
    if( nName==64 ){
      db_multi_exec(
        "UPDATE subscriber SET sverified=1"
        " WHERE subscriberCode=hextoblob(%Q)",
        zName);
      if( db_get_boolean("selfreg-verify",0) ){
        char *zNewCap = db_get("default-perms","u");

        db_multi_exec(
           "UPDATE user"
           "   SET cap=%Q"
           " WHERE cap='7' AND login=("
           "   SELECT suname FROM subscriber"
           "    WHERE subscriberCode=hextoblob(%Q))",
           zNewCap, zName
        );

        login_set_capabilities(zNewCap, 0);
      }
      @ <h1>Your email alert subscription has been verified!</h1>
      @ <p>Use the form below to update your subscription information.</p>
      @ <p>Hint:  Bookmark this page so that you can more easily update
      @ your subscription information in the future</p>
    }else{







|












|






|




|









|







 







>








>







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
....
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
/*
** SETTING: email-subname             width=16
** This is a short name used to identifies the repository in the Subject:
** line of email alerts. Traditionally this name is included in square
** brackets. Examples: "[fossil-src]", "[sqlite-src]".
*/
/*
** SETTING: email-send-method         width=5 default=off sensitive
** Determine the method used to send email.  Allowed values are
** "off", "relay", "pipe", "dir", "db", and "stdout".  The "off" value
** means no email is ever sent.  The "relay" value means emails are sent
** to an Mail Sending Agent using SMTP located at email-send-relayhost.
** The "pipe" value means email messages are piped into a command 
** determined by the email-send-command setting. The "dir" value means
** emails are written to individual files in a directory determined
** by the email-send-dir setting.  The "db" value means that emails
** are added to an SQLite database named by the* email-send-db setting.
** The "stdout" value writes email text to standard output, for debugging.
*/
/*
** SETTING: email-send-command       width=40 sensitive
** This is a command to which outbound email content is piped when the
** email-send-method is set to "pipe".  The command must extract
** recipient, sender, subject, and all other relevant information
** from the email header.
*/
/*
** SETTING: email-send-dir           width=40 sensitive
** This is a directory into which outbound emails are written as individual
** files if the email-send-method is set to "dir".
*/
/*
** SETTING: email-send-db            width=40 sensitive
** This is an SQLite database file into which outbound emails are written
** if the email-send-method is set to "db".
*/
/*
** SETTING: email-self               width=40
** This is the email address for the repository.  Outbound emails add
** this email address as the "From:" field.
*/
/*
** SETTING: email-send-relayhost      width=40 sensitive
** This is the hostname and TCP port to which output email messages
** are sent when email-send-method is "relay".  There should be an
** SMTP server configured as a Mail Submission Agent listening on the
** designated host and port and all times.
*/


................................................................................
    if( nName==64 ){
      db_multi_exec(
        "UPDATE subscriber SET sverified=1"
        " WHERE subscriberCode=hextoblob(%Q)",
        zName);
      if( db_get_boolean("selfreg-verify",0) ){
        char *zNewCap = db_get("default-perms","u");
        db_unprotect(PROTECT_USER);
        db_multi_exec(
           "UPDATE user"
           "   SET cap=%Q"
           " WHERE cap='7' AND login=("
           "   SELECT suname FROM subscriber"
           "    WHERE subscriberCode=hextoblob(%Q))",
           zNewCap, zName
        );
        db_protect_pop();
        login_set_capabilities(zNewCap, 0);
      }
      @ <h1>Your email alert subscription has been verified!</h1>
      @ <p>Use the form below to update your subscription information.</p>
      @ <p>Hint:  Bookmark this page so that you can more easily update
      @ your subscription information in the future</p>
    }else{

Changes to src/allrepo.c.

297
298
299
300
301
302
303

304

305
306
307
308
309
310
311
...
332
333
334
335
336
337
338

339

340
341
342
343
344
345
346
...
426
427
428
429
430
431
432

433

434
435
436
      blob_append_sql(&sql,
         "DELETE FROM global_config WHERE name GLOB '%s:%q'",
         useCheckouts?"ckout":"repo", blob_str(&fn)
      );
      if( dryRunFlag ){
        fossil_print("%s\n", blob_sql_text(&sql));
      }else{

        db_multi_exec("%s", blob_sql_text(&sql));

      }
    }
    db_end_transaction(0);
    blob_reset(&sql);
    blob_reset(&fn);
    blob_reset(&extra);
    return;
................................................................................
      blob_append_sql(&sql,
         "INSERT OR IGNORE INTO global_config(name,value)"
         "VALUES('repo:%q',1)", z
      );
      if( dryRunFlag ){
        fossil_print("%s\n", blob_sql_text(&sql));
      }else{

        db_multi_exec("%s", blob_sql_text(&sql));

      }
    }
    db_end_transaction(0);
    blob_reset(&sql);
    blob_reset(&fn);
    blob_reset(&extra);
    return;
................................................................................
  ** be found, remove those names from the ~/.fossil file.
  */
  if( nToDel>0 ){
    const char *zSql = "DELETE FROM global_config WHERE name IN toDel";
    if( dryRunFlag ){
      fossil_print("%s\n", zSql);
    }else{

      db_multi_exec("%s", zSql /*safe-for-%s*/ );

    }
  }
}







>

>







 







>

>







 







>

>



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
...
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
...
430
431
432
433
434
435
436
437
438
439
440
441
442
      blob_append_sql(&sql,
         "DELETE FROM global_config WHERE name GLOB '%s:%q'",
         useCheckouts?"ckout":"repo", blob_str(&fn)
      );
      if( dryRunFlag ){
        fossil_print("%s\n", blob_sql_text(&sql));
      }else{
        db_unprotect(PROTECT_CONFIG);
        db_multi_exec("%s", blob_sql_text(&sql));
        db_protect_pop();
      }
    }
    db_end_transaction(0);
    blob_reset(&sql);
    blob_reset(&fn);
    blob_reset(&extra);
    return;
................................................................................
      blob_append_sql(&sql,
         "INSERT OR IGNORE INTO global_config(name,value)"
         "VALUES('repo:%q',1)", z
      );
      if( dryRunFlag ){
        fossil_print("%s\n", blob_sql_text(&sql));
      }else{
        db_unprotect(PROTECT_CONFIG);
        db_multi_exec("%s", blob_sql_text(&sql));
        db_protect_pop();
      }
    }
    db_end_transaction(0);
    blob_reset(&sql);
    blob_reset(&fn);
    blob_reset(&extra);
    return;
................................................................................
  ** be found, remove those names from the ~/.fossil file.
  */
  if( nToDel>0 ){
    const char *zSql = "DELETE FROM global_config WHERE name IN toDel";
    if( dryRunFlag ){
      fossil_print("%s\n", zSql);
    }else{
      db_unprotect(PROTECT_CONFIG);
      db_multi_exec("%s", zSql /*safe-for-%s*/ );
      db_protect_pop();
    }
  }
}

Changes to src/attach.c.

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
  blob_zero(&attach);
  if( fShowContent ){
    const char *z;
    content_get(ridSrc, &attach);
    blob_to_utf8_no_bom(&attach, 0);
    z = blob_str(&attach);
    if( zLn ){
      output_text_with_line_numbers(z, zLn);
    }else{
      @ <pre>
      @ %h(z)
      @ </pre>
    }
  }else if( strncmp(zMime, "image/", 6)==0 ){
    int sz = db_int(0, "SELECT size FROM blob WHERE rid=%d", ridSrc);







|







615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
  blob_zero(&attach);
  if( fShowContent ){
    const char *z;
    content_get(ridSrc, &attach);
    blob_to_utf8_no_bom(&attach, 0);
    z = blob_str(&attach);
    if( zLn ){
      output_text_with_line_numbers(z, blob_size(&attach), zName, zLn, 1);
    }else{
      @ <pre>
      @ %h(z)
      @ </pre>
    }
  }else if( strncmp(zMime, "image/", 6)==0 ){
    int sz = db_int(0, "SELECT size FROM blob WHERE rid=%d", ridSrc);

Changes to src/backlink.c.

167
168
169
170
171
172
173
174

175
176
177
178
179
180
181
  Manifest *pWiki;
  if( tagid==0 ) return;
  rid = db_int(0, "SELECT rid FROM tagxref WHERE tagid=%d"
                  " ORDER BY mtime DESC LIMIT 1", tagid);
  if( rid==0 ) return;
  pWiki = manifest_get(rid, CFTYPE_WIKI, 0);
  if( pWiki ){
    backlink_extract(pWiki->zWiki, pWiki->zMimetype, tagid, 2, pWiki->rDate,1);

    manifest_destroy(pWiki);
  }
}

/*
** Structure used to pass down state information through the
** markup formatters into the BACKLINK generator.







|
>







167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
  Manifest *pWiki;
  if( tagid==0 ) return;
  rid = db_int(0, "SELECT rid FROM tagxref WHERE tagid=%d"
                  " ORDER BY mtime DESC LIMIT 1", tagid);
  if( rid==0 ) return;
  pWiki = manifest_get(rid, CFTYPE_WIKI, 0);
  if( pWiki ){
    backlink_extract(pWiki->zWiki, pWiki->zMimetype, tagid, BKLNK_WIKI,
                     pWiki->rDate, 1);
    manifest_destroy(pWiki);
  }
}

/*
** Structure used to pass down state information through the
** markup formatters into the BACKLINK generator.

Changes to src/backoffice.c.

239
240
241
242
243
244
245

246
247
248
249
250
251
252
253
254
255

256
257
258
259
260
261
262
...
275
276
277
278
279
280
281

282
283
284
285
286

287
288
289
290
291
292
293
**
** No other process should start active backoffice processing until
** process (1) no longer exists and the current time exceeds (2).
*/
static void backofficeReadLease(Lease *pLease){
  Stmt q;
  memset(pLease, 0, sizeof(*pLease));

  db_prepare(&q, "SELECT value FROM repository.config"
                 " WHERE name='backoffice'");
  if( db_step(&q)==SQLITE_ROW ){
    const char *z = db_column_text(&q,0);
    z = backofficeParseInt(z, &pLease->idCurrent);
    z = backofficeParseInt(z, &pLease->tmCurrent);
    z = backofficeParseInt(z, &pLease->idNext);
    backofficeParseInt(z, &pLease->tmNext);
  }
  db_finalize(&q);

}

/*
** Return a string that describes how long it has been since the
** last backoffice run.  The string is obtained from fossil_malloc().
*/
char *backoffice_last_run(void){
................................................................................
  return mprintf("%z ago", human_readable_age(rAge));
}

/*
** Write a lease to the backoffice property
*/
static void backofficeWriteLease(Lease *pLease){

  db_multi_exec(
    "REPLACE INTO repository.config(name,value,mtime)"
    " VALUES('backoffice','%lld %lld %lld %lld',now())",
    pLease->idCurrent, pLease->tmCurrent,
    pLease->idNext, pLease->tmNext);

}

/*
** Check to see if the specified Win32 process is still alive.  It
** should be noted that even if this function returns non-zero, the
** process may die before another operation on it can be completed.
*/







>










>







 







>





>







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
...
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
**
** No other process should start active backoffice processing until
** process (1) no longer exists and the current time exceeds (2).
*/
static void backofficeReadLease(Lease *pLease){
  Stmt q;
  memset(pLease, 0, sizeof(*pLease));
  db_unprotect(PROTECT_CONFIG);
  db_prepare(&q, "SELECT value FROM repository.config"
                 " WHERE name='backoffice'");
  if( db_step(&q)==SQLITE_ROW ){
    const char *z = db_column_text(&q,0);
    z = backofficeParseInt(z, &pLease->idCurrent);
    z = backofficeParseInt(z, &pLease->tmCurrent);
    z = backofficeParseInt(z, &pLease->idNext);
    backofficeParseInt(z, &pLease->tmNext);
  }
  db_finalize(&q);
  db_protect_pop();
}

/*
** Return a string that describes how long it has been since the
** last backoffice run.  The string is obtained from fossil_malloc().
*/
char *backoffice_last_run(void){
................................................................................
  return mprintf("%z ago", human_readable_age(rAge));
}

/*
** Write a lease to the backoffice property
*/
static void backofficeWriteLease(Lease *pLease){
  db_unprotect(PROTECT_CONFIG);
  db_multi_exec(
    "REPLACE INTO repository.config(name,value,mtime)"
    " VALUES('backoffice','%lld %lld %lld %lld',now())",
    pLease->idCurrent, pLease->tmCurrent,
    pLease->idNext, pLease->tmNext);
  db_protect_pop();
}

/*
** Check to see if the specified Win32 process is still alive.  It
** should be noted that even if this function returns non-zero, the
** process may die before another operation on it can be completed.
*/

Changes to src/bisect.c.

73
74
75
76
77
78
79
80

81
82
83
84
85
86
87
...
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
...
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
...
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
...
608
609
610
611
612
613
614
615

616
617
*/
static const struct {
  const char *zName;
  const char *zDefault;
  const char *zDesc;
} aBisectOption[] = {
  { "auto-next",    "on",    "Automatically run \"bisect next\" after each "
                             "\"bisect good\" or \"bisect bad\"" },

  { "direct-only",  "on",    "Follow only primary parent-child links, not "
                             "merges\n" },
  { "display",    "chart",   "Command to run after \"next\".  \"chart\", "
                             "\"log\", \"status\", or \"none\"" },
};

/*
................................................................................
      char c;
      int rid;
      if( blob_size(&log) ) blob_append(&log, " ", 1);
      if( zDesc[0]=='n' ) blob_append(&log, "-", 1);
      if( zDesc[0]=='s' ) blob_append(&log, "s", 1);
      for(i=1; ((c = zDesc[i])>='0' && c<='9') || (c>='a' && c<='f'); i++){}
      if( i==1 ) break;
      rid = db_int(0, 
        "SELECT rid FROM blob"
        " WHERE uuid LIKE '%.*q%%'"
        "   AND EXISTS(SELECT 1 FROM plink WHERE cid=rid)",
        i-1, zDesc+1
      );
      if( rid==0 ) break;
      blob_appendf(&log, "%d", rid);
................................................................................
*/
void bisect_cmd(void){
  int n;
  const char *zCmd;
  int foundCmd = 0;
  db_must_be_within_tree();
  if( g.argc<3 ){
    usage("bad|good|log|next|options|reset|skip|status|undo");
  }
  zCmd = g.argv[2];
  n = strlen(zCmd);
  if( n==0 ) zCmd = "-";
  if( strncmp(zCmd, "bad", n)==0 ){
    int ridBad;
    foundCmd = 1;
................................................................................
    if( g.argc==3 ){
      ridSkip = db_lget_int("checkout",0);
    }else{
      ridSkip = name_to_typed_rid(g.argv[3], "ci");
    }
    if( ridSkip>0 ){
      bisect_append_skip(ridSkip);
      if( bisect_option("auto-next") 
       && db_lget_int("bisect-bad",0)>0
       && db_lget_int("bisect-good",0)>0
      ){
        zCmd = "next";
        n = 4;
      }
    }
................................................................................
  }else if( strncmp(zCmd, "vlist", n)==0
         || strncmp(zCmd, "ls", n)==0
         || strncmp(zCmd, "status", n)==0
  ){
    int fAll = find_option("all", "a", 0)!=0;
    bisect_list(!fAll);
  }else if( !foundCmd ){
    usage("bad|good|log|next|options|reset|status|ui|undo");

  }
}







|
>







 







|







 







|







 







|







 







|
>


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
...
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
...
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
...
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
...
609
610
611
612
613
614
615
616
617
618
619
*/
static const struct {
  const char *zName;
  const char *zDefault;
  const char *zDesc;
} aBisectOption[] = {
  { "auto-next",    "on",    "Automatically run \"bisect next\" after each "
                             "\"bisect good\", \"bisect bad\", or \"bisect "
                             "skip\"" },
  { "direct-only",  "on",    "Follow only primary parent-child links, not "
                             "merges\n" },
  { "display",    "chart",   "Command to run after \"next\".  \"chart\", "
                             "\"log\", \"status\", or \"none\"" },
};

/*
................................................................................
      char c;
      int rid;
      if( blob_size(&log) ) blob_append(&log, " ", 1);
      if( zDesc[0]=='n' ) blob_append(&log, "-", 1);
      if( zDesc[0]=='s' ) blob_append(&log, "s", 1);
      for(i=1; ((c = zDesc[i])>='0' && c<='9') || (c>='a' && c<='f'); i++){}
      if( i==1 ) break;
      rid = db_int(0,
        "SELECT rid FROM blob"
        " WHERE uuid LIKE '%.*q%%'"
        "   AND EXISTS(SELECT 1 FROM plink WHERE cid=rid)",
        i-1, zDesc+1
      );
      if( rid==0 ) break;
      blob_appendf(&log, "%d", rid);
................................................................................
*/
void bisect_cmd(void){
  int n;
  const char *zCmd;
  int foundCmd = 0;
  db_must_be_within_tree();
  if( g.argc<3 ){
    goto usage;
  }
  zCmd = g.argv[2];
  n = strlen(zCmd);
  if( n==0 ) zCmd = "-";
  if( strncmp(zCmd, "bad", n)==0 ){
    int ridBad;
    foundCmd = 1;
................................................................................
    if( g.argc==3 ){
      ridSkip = db_lget_int("checkout",0);
    }else{
      ridSkip = name_to_typed_rid(g.argv[3], "ci");
    }
    if( ridSkip>0 ){
      bisect_append_skip(ridSkip);
      if( bisect_option("auto-next")
       && db_lget_int("bisect-bad",0)>0
       && db_lget_int("bisect-good",0)>0
      ){
        zCmd = "next";
        n = 4;
      }
    }
................................................................................
  }else if( strncmp(zCmd, "vlist", n)==0
         || strncmp(zCmd, "ls", n)==0
         || strncmp(zCmd, "status", n)==0
  ){
    int fAll = find_option("all", "a", 0)!=0;
    bisect_list(!fAll);
  }else if( !foundCmd ){
usage:
    usage("bad|good|log|chart|next|options|reset|skip|status|ui|undo");
  }
}

Changes to src/browse.c.

390
391
392
393
394
395
396

397
398
399
400
401
402
403
        @ </iframe>
      }else{
        Blob content;
        const char *zMime = mimetype_from_name(zName);
        content_get(rid, &content);
        safe_html_context(DOCSRC_FILE);
        wiki_render_by_mimetype(&content, zMime);

      }
    }
  }
  db_finalize(&q);
  style_footer();
}








>







390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
        @ </iframe>
      }else{
        Blob content;
        const char *zMime = mimetype_from_name(zName);
        content_get(rid, &content);
        safe_html_context(DOCSRC_FILE);
        wiki_render_by_mimetype(&content, zMime);
        document_emit_js();
      }
    }
  }
  db_finalize(&q);
  style_footer();
}

Changes to src/builtin.c.

256
257
258
259
260
261
262








263
264
265
266
267
268
269
...
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
...
557
558
559
560
561
562
563
















































































































































































































































































































  if( strcmp(zMode, "bundled")==0 ){
    builtin.eDelivery = JS_BUNDLED;
  }else if( !bSilent ){
    fossil_fatal("unknown javascript delivery mode \"%s\" - should be"
                 " one of: inline separate bundled", zMode);
  }
}









/*
** The caller wants the Javascript file named by zFilename to be
** included in the generated page.  Add the file to the queue of
** requested javascript resources, if it is not there already.
**
** The current implementation queues the file to be included in the
................................................................................
void builtin_fulfill_js_requests(void){
  if( builtin.nSent>=builtin.nReq ) return;  /* nothing to do */
  switch( builtin.eDelivery ){
    case JS_INLINE: {
      CX("<script nonce='%h'>\n",style_nonce());
      do{
        int i = builtin.aReq[builtin.nSent++];
        CX("/* %s */\n", aBuiltinFiles[i].zName);
        cgi_append_content((const char*)aBuiltinFiles[i].pData,
                           aBuiltinFiles[i].nByte);
      }while( builtin.nSent<builtin.nReq );
      CX("</script>\n");
      break;
    }
    case JS_BUNDLED: {
................................................................................
*/
int builtin_vtab_register(sqlite3 *db){
  int rc = sqlite3_create_module(db, "builtin", &builtinVtabModule, 0);
  return rc;
}
/* End of the builtin virtual table
******************************************************************************/























































































































































































































































































































>
>
>
>
>
>
>
>







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
...
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
...
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
  if( strcmp(zMode, "bundled")==0 ){
    builtin.eDelivery = JS_BUNDLED;
  }else if( !bSilent ){
    fossil_fatal("unknown javascript delivery mode \"%s\" - should be"
                 " one of: inline separate bundled", zMode);
  }
}

/*
** Returns the current JS delivery mode: one of JS_INLINE,
** JS_SEPARATE, JS_BUNDLED.
*/
int builtin_get_js_delivery_mode(void){
  return builtin.eDelivery;
}

/*
** The caller wants the Javascript file named by zFilename to be
** included in the generated page.  Add the file to the queue of
** requested javascript resources, if it is not there already.
**
** The current implementation queues the file to be included in the
................................................................................
void builtin_fulfill_js_requests(void){
  if( builtin.nSent>=builtin.nReq ) return;  /* nothing to do */
  switch( builtin.eDelivery ){
    case JS_INLINE: {
      CX("<script nonce='%h'>\n",style_nonce());
      do{
        int i = builtin.aReq[builtin.nSent++];
        CX("/* %s %.60c*/\n", aBuiltinFiles[i].zName, '*');
        cgi_append_content((const char*)aBuiltinFiles[i].pData,
                           aBuiltinFiles[i].nByte);
      }while( builtin.nSent<builtin.nReq );
      CX("</script>\n");
      break;
    }
    case JS_BUNDLED: {
................................................................................
*/
int builtin_vtab_register(sqlite3 *db){
  int rc = sqlite3_create_module(db, "builtin", &builtinVtabModule, 0);
  return rc;
}
/* End of the builtin virtual table
******************************************************************************/


/*
** The first time this is called, it emits code to install and
** bootstrap the window.fossil object, using the built-in file
** fossil.bootstrap.js (not to be confused with bootstrap.js).
**
** Subsequent calls are no-ops.
**
** It emits 2 parts:
**
** 1) window.fossil core object, some of which depends on C-level
** runtime data. That part of the script is always emitted inline. If
** addScriptTag is true then it is wrapped in its own SCRIPT tag, else
** it is assumed that the caller already opened a tag.
**
** 2) Emits the static fossil.bootstrap.js using builtin_request_js().
*/
void builtin_emit_script_fossil_bootstrap(int addScriptTag){
  static int once = 0;
  if(0==once++){
    char * zName;
    /* Set up the generic/app-agnostic parts of window.fossil
    ** which require C-level state... */
    if(addScriptTag!=0){
      style_script_begin(__FILE__,__LINE__);
    }
    CX("(function(){\n");
    CX(/*MSIE NodeList.forEach polyfill, courtesy of Mozilla:
    https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#Polyfill
       */
       "if(window.NodeList && !NodeList.prototype.forEach){"
       "NodeList.prototype.forEach = Array.prototype.forEach;"
       "}\n");
    CX("if(!window.fossil) window.fossil={};\n"
       "window.fossil.version = %!j;\n"
    /* fossil.rootPath is the top-most CGI/server path,
    ** including a trailing slash. */
       "window.fossil.rootPath = %!j+'/';\n",
       get_version(), g.zTop);
    /* fossil.config = {...various config-level options...} */
    CX("window.fossil.config = {");
    zName = db_get("project-name", "");
    CX("projectName: %!j,\n", zName);
    fossil_free(zName);
    zName = db_get("short-project-name", "");
    CX("shortProjectName: %!j,\n", zName);
    fossil_free(zName);
    zName = db_get("project-code", "");
    CX("projectCode: %!j,\n", zName);
    fossil_free(zName);
    CX("/* Length of UUID hashes for display purposes. */");
    CX("hashDigits: %d, hashDigitsUrl: %d,\n",
       hash_digits(0), hash_digits(1));
    CX("editStateMarkers: {"
       "/*Symbolic markers to denote certain edit states.*/"
       "isNew:'[+]', isModified:'[*]', isDeleted:'[-]'},\n");
    CX("confirmerButtonTicks: 3 "
       "/*default fossil.confirmer tick count.*/,\n");
    /* Inject certain info about the current skin... */
    CX("skin:{");
    /* can leak a local filesystem path:
       CX("name: %!j,", skin_in_use());*/
    CX("isDark: %s"
       "/*true if the current skin has the 'white-foreground' detail*/",
       skin_detail_boolean("white-foreground") ? "true" : "false");
    CX("}\n"/*fossil.config.skin*/);
    CX("};\n"/* fossil.config */);
    CX("if(fossil.config.skin.isDark) "
       "document.body.classList.add('fossil-dark-style');\n");
#if 0
    /* Is it safe to emit the CSRF token here? Some pages add it
    ** as a hidden form field. */
    if(g.zCsrfToken[0]!=0){
      CX("window.fossil.csrfToken = %!j;\n",
         g.zCsrfToken);
    }
#endif
    /*
    ** fossil.page holds info about the current page. This is also
    ** where the current page "should" store any of its own
    ** page-specific state, and it is reserved for that purpose.
    */
    CX("window.fossil.page = {"
       "name:\"%T\""
       "};\n", g.zPath);
    CX("})();\n");
    if(addScriptTag!=0){
      style_script_end();
    }
    /* The remaining window.fossil bootstrap code is not dependent on
    ** C-runtime state... */
    builtin_request_js("fossil.bootstrap.js");
  }
}

/*
** Given the NAME part of fossil.NAME.js, this function checks whether
** that module has been emitted by this function before.  If it has,
** it returns -1 with no side effects. If it has not, it queues up
** (via builtin_request_js()) an emit of the module via and all of its
** known (by this function) fossil.XYZ.js dependencies (in their
** dependency order) and returns 1. If it does not find the given
** module name it returns 0.
**
** As a special case, if passed 0 then it queues up all known modules
** and returns -1.
**
** The very first time this is called, it unconditionally calls
** builtin_emit_script_fossil_bootstrap().
**
** Any given module is only queued once, whether it is explicitly
** passed to the function or resolved as a dependency. Any attempts to
** re-queue them later are harmless no-ops.
*/
static int builtin_emit_fossil_js_once(const char * zName){
  static int once = 0;
  int i;
  static struct FossilJs {
    const char * zName; /* NAME part of fossil.NAME.js */
    int emitted;        /* True if already emitted. */
    const char * zDeps; /* \0-delimited list of other FossilJs
                        ** entries: all known deps of this one. Each
                        ** REQUIRES an EXPLICIT trailing \0, including
                        ** the final one! */
  } fjs[] = {
  /* This list ordering isn't strictly important. */
  {"confirmer",      0, 0},
  {"copybutton",     0, "dom\0"},
  {"dom",            0, 0},
  {"fetch",          0, 0},
  {"numbered-lines", 0, "popupwidget\0copybutton\0"},
  {"pikchr",         0, "dom\0"},
  {"popupwidget",    0, "dom\0"},
  {"storage",        0, 0},
  {"tabs",           0, "dom\0"}
  };
  const int nFjs = sizeof(fjs) / sizeof(fjs[0]);
  if(0==once){
    ++once;
    builtin_emit_script_fossil_bootstrap(1);
  }
  if(0==zName){
    for( i = 0; i < nFjs; ++i ){
      builtin_emit_fossil_js_once(fjs[i].zName);
    }
    return -1;
  }
  for( i = 0; i < nFjs; ++i ){
    if(0==strcmp(zName, fjs[i].zName)){
      if(fjs[i].emitted){
        return -1;
      }else{
        char nameBuffer[50];
        if(fjs[i].zDeps){
          const char * zDep = fjs[i].zDeps;
          while(*zDep!=0){
            builtin_emit_fossil_js_once(zDep);
            zDep += strlen(zDep)+1/*NUL delimiter*/;
          }
        }
        sqlite3_snprintf(sizeof(nameBuffer)-1, nameBuffer,
                         "fossil.%s.js", fjs[i].zName);
        builtin_request_js(nameBuffer);
        fjs[i].emitted = 1;
        return 1;
      }
    }
  }
  return 0;
}

/*
** COMMAND: test-js-once
**
** Tester for builtin_emit_fossil_js_once().
**
** Usage: %fossil test-js-once filename
*/
void test_js_once(void){
  int i;
  if(g.argc<2){
    usage("?FILENAME...?");
  }
  if(2==g.argc){
    builtin_emit_fossil_js_once(0);
    assert(builtin.nReq>8);
  }else{
    for(i = 2; i < g.argc; ++i){
      builtin_emit_fossil_js_once(g.argv[i]);
    }
    assert(builtin.nReq>1 && "don't forget implicit fossil.bootstrap.js");
  }
  for(i = 0; i < builtin.nReq; ++i){
    fossil_print("ndx#%d = %d = %s\n", i, builtin.aReq[i],
                 aBuiltinFiles[builtin.aReq[i]].zName);
  }
}

/*
** Convenience wrapper which calls builtin_request_js() for a series
** of builtin scripts named fossil.NAME.js. The first time it is
** called, it also calls builtin_emit_script_fossil_bootstrap() to
** initialize the window.fossil JS API. The first argument is the NAME
** part of the first API to emit. All subsequent arguments must be
** strings of the NAME part of additional fossil.NAME.js files,
** followed by a NULL argument to terminate the list.
**
** e.g. pass it ("fetch", "dom", "tabs", 0) to load those 3 APIs (or
** pass it ("fetch","tabs",0), as "dom" is a dependency of "tabs", so
** it will be automatically loaded). Do not forget the trailing 0!
**
** If it is JS_BUNDLED then this routine queues up an emit of ALL of
** the JS fossil.XYZ.js APIs which are not strictly specific to a
** single page, and then calls builtin_fulfill_js_requests(). The idea
** is that we can get better bundle caching and reduced HTTP requests
** by including all JS, rather than creating separate bundles on a
** per-page basis. In this case, all arguments are ignored!
**
** This function has an internal mapping of the dependencies for each
** of the known fossil.XYZ.js modules and ensures that the
** dependencies also get queued (recursively) and that each module is
** queued only once.
**
** If passed a name which is not a base fossil module name then it 
** will fail fatally!
**
** DO NOT use this for loading fossil.page.*.js: use
** builtin_request_js() for those.
**
** If the current JS delivery mode is *not* JS_BUNDLED then this
** function queues up a request for each given module and its known
** dependencies, but does not immediately fulfill the request, thus it
** can be called multiple times.
**
** If a given module is ever passed to this more than once, either in
** a single invocation or multiples, it is only queued for emit a
** single time (i.e. the 2nd and subsequent ones become
** no-ops). Likewise, if a module is requested but was already
** automatically queued to fulfill a dependency, the explicit request
** becomes a no-op.
**
** Bundled mode is the only mode in which this API greatly improves
** aggregate over-the-wire and HTTP request costs. For other modes,
** reducing the inclusion of fossil.XYZ APIs to their bare minimum
** provides the lowest aggregate costs. For debate and details, see
** the discussion at:
**
** https://fossil-scm.org/forum/forumpost/3fa2633f3e
**
** In practice it is normally necessary (or preferred) to call
** builtin_fulfill_js_requests() after calling this, before proceeding
** to call builtin_request_js() for page-specific JS, in order to
** improve cachability.
**
** Minor caveat: the purpose of emitting all of the fossil.XYZ JS APIs
** at once is to reduce over-the-wire transfers by enabling cross-page
** caching, but if there are other JS scripts pending via
** builtin_request_js() when this is called then they will be included
** in the JS request emitted by this routine, resulting in a different
** script URL than if they were not included. Thus, if a given page
** has its own scripts to install via builtin_request_js(), they
** should, if possible, be delayed until after this is called OR the
** page should call builtin_fulfill_js_requests() to flush the request
** queue before calling this routine.
**
** Achtung: the fossil.page.XYZ.js files are page-specific, containing
** the app-level logic for that specific page, and loading more than
** one of them in a single page will break that page. Each of those
** expects to "own" the page it is loaded in, and it should be loaded
** as late in the JS-loading process as feasible, ideally bundled (via
** builtin_request_js()) with any other app-/page-specific JS it may
** need.
**
** Example usage:
**
** builtin_fossil_js_bundle_or("dom", "fetch", 0);
**
** In bundled mode, that will (the first time it is called) emit all
** builtin fossil JS APIs and "fulfill" the queue immediately. In
** non-bundled mode it will queue up the "dom" and "fetch" APIs to be
** emitted the next time builtin_fulfill_js_requests() is called.
*/
void builtin_fossil_js_bundle_or( const char * zApi, ... ) {
  static int bundled = 0;
  const char *zArg;
  va_list vargs;

  if(JS_BUNDLED == builtin_get_js_delivery_mode()){
    if(!bundled){
      bundled = 1;
      builtin_emit_fossil_js_once(0);
      builtin_fulfill_js_requests();
    }
    return;
  }
  va_start(vargs,zApi);
  for( zArg = zApi; zArg!=0; (zArg = va_arg (vargs, const char *))){
    if(0==builtin_emit_fossil_js_once(zArg)){
      fossil_fatal("Unknown fossil JS module: %s\n", zArg);
    }
  }
  va_end(vargs);
}

Changes to src/captcha.c.

456
457
458
459
460
461
462

463
464
465
466

467
468
469
470
471
472
473
...
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
  const char *zSecret;
  const char *z;
  Blob b;
  static char zRes[20];

  zSecret = db_get("captcha-secret", 0);
  if( zSecret==0 ){

    db_multi_exec(
      "REPLACE INTO config(name,value)"
      " VALUES('captcha-secret', lower(hex(randomblob(20))));"
    );

    zSecret = db_get("captcha-secret", 0);
    assert( zSecret!=0 );
  }
  blob_init(&b, 0, 0);
  blob_appendf(&b, "%s-%x", zSecret, seed);
  sha1sum_blob(&b, &b);
  z = blob_buffer(&b);
................................................................................
/*
** Add a "Speak the captcha" button.
*/
void captcha_speakit_button(unsigned int uSeed, const char *zMsg){
  if( zMsg==0 ) zMsg = "Speak the text";
  @ <input aria-label="%h(zMsg)" type="button" value="%h(zMsg)" \
  @ id="speakthetext">
  @ <script nonce="%h(style_nonce())">
  @ document.getElementById("speakthetext").onclick = function(){
  @   var audio = window.fossilAudioCaptcha \
  @ || new Audio("%R/captcha-audio/%u(uSeed)");
  @   window.fossilAudioCaptcha = audio;
  @   audio.currentTime = 0;
  @   audio.play();
  @ }







>




>







 







|







456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
...
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
  const char *zSecret;
  const char *z;
  Blob b;
  static char zRes[20];

  zSecret = db_get("captcha-secret", 0);
  if( zSecret==0 ){
    db_unprotect(PROTECT_CONFIG);
    db_multi_exec(
      "REPLACE INTO config(name,value)"
      " VALUES('captcha-secret', lower(hex(randomblob(20))));"
    );
    db_protect_pop();
    zSecret = db_get("captcha-secret", 0);
    assert( zSecret!=0 );
  }
  blob_init(&b, 0, 0);
  blob_appendf(&b, "%s-%x", zSecret, seed);
  sha1sum_blob(&b, &b);
  z = blob_buffer(&b);
................................................................................
/*
** Add a "Speak the captcha" button.
*/
void captcha_speakit_button(unsigned int uSeed, const char *zMsg){
  if( zMsg==0 ) zMsg = "Speak the text";
  @ <input aria-label="%h(zMsg)" type="button" value="%h(zMsg)" \
  @ id="speakthetext">
  @ <script nonce="%h(style_nonce())">/* captcha_speakit_button() */
  @ document.getElementById("speakthetext").onclick = function(){
  @   var audio = window.fossilAudioCaptcha \
  @ || new Audio("%R/captcha-audio/%u(uSeed)");
  @   window.fossilAudioCaptcha = audio;
  @   audio.currentTime = 0;
  @   audio.play();
  @ }

Changes to src/cgi.c.

1051
1052
1053
1054
1055
1056
1057











1058
1059
1060
1061
1062
1063
1064
....
1069
1070
1071
1072
1073
1074
1075






1076










1077
1078
1079
1080
1081
1082
1083
....
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
** but REQUEST_URI is not, then compute REQUEST_URI from PATH_INFO and
** SCRIPT_NAME.  If neither REQUEST_URI nor PATH_INFO are provided, then
** assume that PATH_INFO is an empty string and set REQUEST_URI equal
** to PATH_INFO.
**
** SCGI typically omits PATH_INFO.  CGI sometimes omits REQUEST_URI and
** PATH_INFO when it is empty.











*/
void cgi_init(void){
  char *z;
  const char *zType;
  char *zSemi;
  int len;
  const char *zRequestUri = cgi_parameter("REQUEST_URI",0);
................................................................................
#endif

#ifdef FOSSIL_ENABLE_JSON
  const int noJson = P("no_json")!=0;
#endif
  g.isHTTP = 1;
  cgi_destination(CGI_BODY);






  if( zScriptName==0 ) malformed_request("missing SCRIPT_NAME");










#ifdef _WIN32
  /* The Microsoft IIS web server does not define REQUEST_URI, instead it uses
  ** PATH_INFO for virtually the same purpose.  Define REQUEST_URI the same as
  ** PATH_INFO and redefine PATH_INFO with SCRIPT_NAME removed from the 
  ** beginning. */
  if( zServerSoftware && strstr(zServerSoftware, "Microsoft-IIS") ){
    int i, j;
................................................................................
    }else{
      lo = mid+1;
    }
  }

  /* If no match is found and the name begins with an upper-case
  ** letter, then check to see if there is an environment variable
  ** with the given name. Handle environment variables with empty values
  ** the same as non-existent environment variables.
  */
  if( fossil_isupper(zName[0]) ){
    const char *zValue = fossil_getenv(zName);
    if( zValue && zValue[0] ){
      cgi_set_parameter_nocopy(zName, zValue, 0);
      CGIDEBUG(("env-match [%s] = [%s]\n", zName, zValue));
      return zValue;
    }
  }
  CGIDEBUG(("no-match [%s]\n", zName));
  return zDefault;







>
>
>
>
>
>
>
>
>
>
>







 







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







 







|
<



|







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
....
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
....
1282
1283
1284
1285
1286
1287
1288
1289

1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
** but REQUEST_URI is not, then compute REQUEST_URI from PATH_INFO and
** SCRIPT_NAME.  If neither REQUEST_URI nor PATH_INFO are provided, then
** assume that PATH_INFO is an empty string and set REQUEST_URI equal
** to PATH_INFO.
**
** SCGI typically omits PATH_INFO.  CGI sometimes omits REQUEST_URI and
** PATH_INFO when it is empty.
**
** CGI Parameter quick reference:
**
**                                      REQUEST_URI
**                               _____________|____________
**                              /                          \
**    https://www.fossil-scm.org/forum/info/12736b30c072551a?t=c
**            \________________/\____/\____________________/ \_/
**                    |            |             |            |
**               HTTP_HOST         |        PATH_INFO     QUERY_STRING
**                            SCRIPT_NAME
*/
void cgi_init(void){
  char *z;
  const char *zType;
  char *zSemi;
  int len;
  const char *zRequestUri = cgi_parameter("REQUEST_URI",0);
................................................................................
#endif

#ifdef FOSSIL_ENABLE_JSON
  const int noJson = P("no_json")!=0;
#endif
  g.isHTTP = 1;
  cgi_destination(CGI_BODY);

  /* We must have SCRIPT_NAME. If the web server did not supply it, try
  ** to compute it from REQUEST_URI and PATH_INFO. */
  if( zScriptName==0 ){
    size_t nRU, nPI;
    if( zRequestUri==0 || zPathInfo==0 ){
      malformed_request("missing SCRIPT_NAME");  /* Does not return */
    }
    nRU = strlen(zRequestUri);
    nPI = strlen(zPathInfo);
    if( nRU<nPI ){
      malformed_request("PATH_INFO is longer than REQUEST_URI");
    }
    zScriptName = mprintf("%.*s", (int)(nRU-nPI), zRequestUri);
    cgi_set_parameter("SCRIPT_NAME", zScriptName);
  }

#ifdef _WIN32
  /* The Microsoft IIS web server does not define REQUEST_URI, instead it uses
  ** PATH_INFO for virtually the same purpose.  Define REQUEST_URI the same as
  ** PATH_INFO and redefine PATH_INFO with SCRIPT_NAME removed from the 
  ** beginning. */
  if( zServerSoftware && strstr(zServerSoftware, "Microsoft-IIS") ){
    int i, j;
................................................................................
    }else{
      lo = mid+1;
    }
  }

  /* If no match is found and the name begins with an upper-case
  ** letter, then check to see if there is an environment variable
  ** with the given name.

  */
  if( fossil_isupper(zName[0]) ){
    const char *zValue = fossil_getenv(zName);
    if( zValue ){
      cgi_set_parameter_nocopy(zName, zValue, 0);
      CGIDEBUG(("env-match [%s] = [%s]\n", zName, zValue));
      return zValue;
    }
  }
  CGIDEBUG(("no-match [%s]\n", zName));
  return zDefault;

Changes to src/checkin.c.

60
61
62
63
64
65
66



67
68
69
70
71
72
73
..
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
...
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
...
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
....
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
....
1336
1337
1338
1339
1340
1341
1342
1343


1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
....
1373
1374
1375
1376
1377
1378
1379










1380
1381
1382
1383

1384
1385
1386
1387
1388
1389
1390
....
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
....
2481
2482
2483
2484
2485
2486
2487















2488
2489
2490
2491
2492
2493
2494
....
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
....
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750

/*
** Create a TEMP table named SFILE and add all unmanaged files named on
** the command-line to that table.  If directories are named, then add
** all unmanaged files contained underneath those directories.  If there
** are no files or directories named on the command-line, then add all
** unmanaged files anywhere in the checkout.



*/
static void locate_unmanaged_files(
  int argc,           /* Number of command-line arguments to examine */
  char **argv,        /* values of command-line arguments */
  unsigned scanFlags, /* Zero or more SCAN_xxx flags */
  Glob *pIgnore       /* Do not add files that match this GLOB */
){
................................................................................
  int nRoot;   /* length of g.zLocalRoot */

  db_multi_exec("CREATE TEMP TABLE sfile(pathname TEXT PRIMARY KEY %s,"
                " mtime INTEGER, size INTEGER)", filename_collation());
  nRoot = (int)strlen(g.zLocalRoot);
  if( argc==0 ){
    blob_init(&name, g.zLocalRoot, nRoot - 1);
    vfile_scan(&name, blob_size(&name), scanFlags, pIgnore, 0, RepoFILE);
    blob_reset(&name);
  }else{
    for(i=0; i<argc; i++){
      file_canonical_name(argv[i], &name, 0);
      zName = blob_str(&name);
      isDir = file_isdir(zName, RepoFILE);
      if( isDir==1 ){
        vfile_scan(&name, nRoot-1, scanFlags, pIgnore, 0, RepoFILE);
      }else if( isDir==0 ){
        fossil_warning("not found: %s", &zName[nRoot]);
      }else if( file_access(zName, R_OK) ){
        fossil_fatal("cannot open %s", &zName[nRoot]);
      }else{
        db_multi_exec(
           "INSERT OR IGNORE INTO sfile(pathname) VALUES(%Q)",
................................................................................
**
** General options:
**    --abs-paths       Display absolute pathnames.
**    --rel-paths       Display pathnames relative to the current working
**                      directory.
**    --hash            Verify file status using hashing rather than
**                      relying on file mtimes.
**    --case-sensitive <BOOL>  Override case-sensitive setting.
**    --dotfiles        Include unmanaged files beginning with a dot.
**    --ignore <CSG>    Ignore unmanaged files matching CSG glob patterns.
**
** Options specific to the changes command:
**    --header          Identify the repository if report is non-empty.
**    -v|--verbose      Say "(none)" if the change report is empty.
**    --classify        Start each line with the file's change type.
................................................................................
  /* We should be done with options.. */
  verify_all_options();

  if( zIgnoreFlag==0 ){
    zIgnoreFlag = db_get("ignore-glob", 0);
  }
  pIgnore = glob_create(zIgnoreFlag);
#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
  /* Always consider symlinks. */
  g.allowSymlinks = db_allow_symlinks_by_default();
#endif
  locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore);
  glob_free(pIgnore);

  blob_zero(&report);
  status_report(&report, flags);
  if( blob_size(&report) ){
    if( showHdr ){
................................................................................
  }
  if( db_get_boolean("dotfiles", 0) ) scanFlags |= SCAN_ALL;
  verify_all_options();
  pIgnore = glob_create(zIgnoreFlag);
  pKeep = glob_create(zKeepFlag);
  pClean = glob_create(zCleanFlag);
  nRoot = (int)strlen(g.zLocalRoot);
#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
  /* Always consider symlinks. */
  g.allowSymlinks = db_allow_symlinks_by_default();
#endif
  if( !dirsOnlyFlag ){
    Stmt q;
    Blob repo;
    if( !dryRunFlag && !disableUndo ) undo_begin();
    locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore);
    db_prepare(&q,
        "SELECT %Q || pathname FROM sfile"
................................................................................
**
** Space to hold the returned filename is obtained from fossil_malloc()
** and should be freed by the caller.  The caller should also unlink
** the file when it is done.
*/
static char *prepare_commit_description_file(
  CheckinInfo *p,     /* Information about this commit */
  int parent_rid      /* parent check-in */


){
  Blob *pDesc;
  char *zTags;
  char *zFilename;
  Blob desc;
  unsigned int r[2];
  blob_init(&desc, 0, 0);
  pDesc = &desc;
  blob_appendf(pDesc, "checkout %s\n", g.zLocalRoot);
  blob_appendf(pDesc, "repository %s\n", g.zRepositoryName);
  blob_appendf(pDesc, "user %s\n",
               p->zUserOvrd ? p->zUserOvrd : login_name());
  blob_appendf(pDesc, "branch %s\n",
................................................................................
  status_report(pDesc, C_DEFAULT | C_FATAL);
  if( g.markPrivate ){
    blob_append(pDesc, "private-branch\n", -1);
  }
  if( p->integrateFlag ){
    blob_append(pDesc, "integrate\n", -1);
  }










  sqlite3_randomness(sizeof(r), r);
  zFilename = mprintf("%scommit-description-%08x%08x.txt",
                      g.zLocalRoot, r[0], r[1]);
  blob_write_to_file(pDesc, zFilename);

  blob_reset(pDesc);
  return zFilename;
}


/*
** Populate the Global.aCommitFile[] based on the command line arguments
................................................................................
    ){
      fossil_fatal("cannot commit against a closed leaf");
    }

    /* Always exit the loop on the second pass */
    if( bRecheck ) break;

    /* Run before-commit hooks */
    if( !noVerify ){
      char *zAuxFile = prepare_commit_description_file(&sCiInfo,vid);
      int rc = hook_run("before-commit",zAuxFile,bTrace);
      file_delete(zAuxFile);
      fossil_free(zAuxFile);
      if( rc ){
        fossil_fatal("Before-commit hook failed\n");
      }
    }
  
    /* Get the check-in comment.  This might involve prompting the
    ** user for the check-in comment, in which case we should resync
    ** to renew the check-in lock and repeat the checks for conflicts.
    */
    if( zComment ){
      blob_zero(&comment);
................................................................................
        cReply = 'N';
      }
      if( cReply!='y' && cReply!='Y' ){
        fossil_exit(1);
      }
    }
  }
















  /*
  ** Step 1: Compute an aggregate MD5 checksum over the disk image
  ** of every file in vid.  The file names are part of the checksum.
  ** The resulting checksum is the same as is expected on the R-card
  ** of a manifest.
  */
................................................................................

  /* Step 2: Insert records for all modified files into the blob
  ** table. If there were arguments passed to this command, only
  ** the identified files are inserted (if they have been modified).
  */
  db_prepare(&q,
    "SELECT id, %Q || pathname, mrid, %s, %s, %s FROM vfile "
    "WHERE chnged==1 AND NOT deleted AND is_selected(id)",
    g.zLocalRoot,
    glob_expr("pathname", db_get("crlf-glob",db_get("crnl-glob",""))),
    glob_expr("pathname", db_get("binary-glob","")),
    glob_expr("pathname", db_get("encoding-glob",""))
  );
  while( db_step(&q)==SQLITE_ROW ){
    int id, rid;
................................................................................
  undo_reset();

  /* Commit */
  db_multi_exec("DELETE FROM vvar WHERE name='ci-comment'");
  db_multi_exec("PRAGMA repository.application_id=252006673;");
  db_multi_exec("PRAGMA localdb.application_id=252006674;");
  if( dryRunFlag ){
    leaf_ambiguity_warning(nvid,nvid);
    db_end_transaction(1);
    exit(1);
  }
  db_end_transaction(0);

  if( outputManifest & MFESTFLG_TAGS ){
    Blob tagslist;







>
>
>







 







|





|

|







 







|







 







<
<
<
<







 







<
<
<
<







 







|
>
>





<







 







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







 







<
<
<
<
<
<
<
<
<
<







 







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







 







|







 







<







60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
..
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
...
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
...
857
858
859
860
861
862
863




864
865
866
867
868
869
870
....
1014
1015
1016
1017
1018
1019
1020




1021
1022
1023
1024
1025
1026
1027
....
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345

1346
1347
1348
1349
1350
1351
1352
....
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
....
2421
2422
2423
2424
2425
2426
2427










2428
2429
2430
2431
2432
2433
2434
....
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
....
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
....
2748
2749
2750
2751
2752
2753
2754

2755
2756
2757
2758
2759
2760
2761

/*
** Create a TEMP table named SFILE and add all unmanaged files named on
** the command-line to that table.  If directories are named, then add
** all unmanaged files contained underneath those directories.  If there
** are no files or directories named on the command-line, then add all
** unmanaged files anywhere in the checkout.
**
** This routine never follows symlinks.  It always treats symlinks as
** object unto themselves.
*/
static void locate_unmanaged_files(
  int argc,           /* Number of command-line arguments to examine */
  char **argv,        /* values of command-line arguments */
  unsigned scanFlags, /* Zero or more SCAN_xxx flags */
  Glob *pIgnore       /* Do not add files that match this GLOB */
){
................................................................................
  int nRoot;   /* length of g.zLocalRoot */

  db_multi_exec("CREATE TEMP TABLE sfile(pathname TEXT PRIMARY KEY %s,"
                " mtime INTEGER, size INTEGER)", filename_collation());
  nRoot = (int)strlen(g.zLocalRoot);
  if( argc==0 ){
    blob_init(&name, g.zLocalRoot, nRoot - 1);
    vfile_scan(&name, blob_size(&name), scanFlags, pIgnore, 0, SymFILE);
    blob_reset(&name);
  }else{
    for(i=0; i<argc; i++){
      file_canonical_name(argv[i], &name, 0);
      zName = blob_str(&name);
      isDir = file_isdir(zName, SymFILE);
      if( isDir==1 ){
        vfile_scan(&name, nRoot-1, scanFlags, pIgnore, 0, SymFILE);
      }else if( isDir==0 ){
        fossil_warning("not found: %s", &zName[nRoot]);
      }else if( file_access(zName, R_OK) ){
        fossil_fatal("cannot open %s", &zName[nRoot]);
      }else{
        db_multi_exec(
           "INSERT OR IGNORE INTO sfile(pathname) VALUES(%Q)",
................................................................................
**
** General options:
**    --abs-paths       Display absolute pathnames.
**    --rel-paths       Display pathnames relative to the current working
**                      directory.
**    --hash            Verify file status using hashing rather than
**                      relying on file mtimes.
**    --case-sensitive BOOL  Override case-sensitive setting.
**    --dotfiles        Include unmanaged files beginning with a dot.
**    --ignore <CSG>    Ignore unmanaged files matching CSG glob patterns.
**
** Options specific to the changes command:
**    --header          Identify the repository if report is non-empty.
**    -v|--verbose      Say "(none)" if the change report is empty.
**    --classify        Start each line with the file's change type.
................................................................................
  /* We should be done with options.. */
  verify_all_options();

  if( zIgnoreFlag==0 ){
    zIgnoreFlag = db_get("ignore-glob", 0);
  }
  pIgnore = glob_create(zIgnoreFlag);




  locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore);
  glob_free(pIgnore);

  blob_zero(&report);
  status_report(&report, flags);
  if( blob_size(&report) ){
    if( showHdr ){
................................................................................
  }
  if( db_get_boolean("dotfiles", 0) ) scanFlags |= SCAN_ALL;
  verify_all_options();
  pIgnore = glob_create(zIgnoreFlag);
  pKeep = glob_create(zKeepFlag);
  pClean = glob_create(zCleanFlag);
  nRoot = (int)strlen(g.zLocalRoot);




  if( !dirsOnlyFlag ){
    Stmt q;
    Blob repo;
    if( !dryRunFlag && !disableUndo ) undo_begin();
    locate_unmanaged_files(g.argc-2, g.argv+2, scanFlags, pIgnore);
    db_prepare(&q,
        "SELECT %Q || pathname FROM sfile"
................................................................................
**
** Space to hold the returned filename is obtained from fossil_malloc()
** and should be freed by the caller.  The caller should also unlink
** the file when it is done.
*/
static char *prepare_commit_description_file(
  CheckinInfo *p,     /* Information about this commit */
  int parent_rid,     /* parent check-in */
  Blob *pComment,     /* Check-in comment */
  int dryRunFlag      /* True for a dry-run only */
){
  Blob *pDesc;
  char *zTags;
  char *zFilename;
  Blob desc;

  blob_init(&desc, 0, 0);
  pDesc = &desc;
  blob_appendf(pDesc, "checkout %s\n", g.zLocalRoot);
  blob_appendf(pDesc, "repository %s\n", g.zRepositoryName);
  blob_appendf(pDesc, "user %s\n",
               p->zUserOvrd ? p->zUserOvrd : login_name());
  blob_appendf(pDesc, "branch %s\n",
................................................................................
  status_report(pDesc, C_DEFAULT | C_FATAL);
  if( g.markPrivate ){
    blob_append(pDesc, "private-branch\n", -1);
  }
  if( p->integrateFlag ){
    blob_append(pDesc, "integrate\n", -1);
  }
  if( pComment && blob_size(pComment)>0 ){
    blob_appendf(pDesc, "checkin-comment\n%s\n", blob_str(pComment));
  }
  if( dryRunFlag ){
    zFilename = 0;
    fossil_print("******* Commit Description *******\n%s"
                 "***** End Commit Description *****\n",
                 blob_str(pDesc));
  }else{
    unsigned int r[2];
    sqlite3_randomness(sizeof(r), r);
    zFilename = mprintf("%scommit-description-%08x%08x.txt",
                        g.zLocalRoot, r[0], r[1]);
    blob_write_to_file(pDesc, zFilename);
  }
  blob_reset(pDesc);
  return zFilename;
}


/*
** Populate the Global.aCommitFile[] based on the command line arguments
................................................................................
    ){
      fossil_fatal("cannot commit against a closed leaf");
    }

    /* Always exit the loop on the second pass */
    if( bRecheck ) break;











  
    /* Get the check-in comment.  This might involve prompting the
    ** user for the check-in comment, in which case we should resync
    ** to renew the check-in lock and repeat the checks for conflicts.
    */
    if( zComment ){
      blob_zero(&comment);
................................................................................
        cReply = 'N';
      }
      if( cReply!='y' && cReply!='Y' ){
        fossil_exit(1);
      }
    }
  }

  if( !noVerify && hook_exists("before-commit") ){
    /* Run before-commit hooks */
    char *zAuxFile;
    zAuxFile = prepare_commit_description_file(
                     &sCiInfo, vid, &comment, dryRunFlag);
    if( zAuxFile ){
      int rc = hook_run("before-commit",zAuxFile,bTrace);
      file_delete(zAuxFile);
      fossil_free(zAuxFile);
      if( rc ){
        fossil_fatal("Before-commit hook failed\n");
      }
    }
  }

  /*
  ** Step 1: Compute an aggregate MD5 checksum over the disk image
  ** of every file in vid.  The file names are part of the checksum.
  ** The resulting checksum is the same as is expected on the R-card
  ** of a manifest.
  */
................................................................................

  /* Step 2: Insert records for all modified files into the blob
  ** table. If there were arguments passed to this command, only
  ** the identified files are inserted (if they have been modified).
  */
  db_prepare(&q,
    "SELECT id, %Q || pathname, mrid, %s, %s, %s FROM vfile "
    "WHERE chnged IN (1, 7, 9) AND NOT deleted AND is_selected(id)",
    g.zLocalRoot,
    glob_expr("pathname", db_get("crlf-glob",db_get("crnl-glob",""))),
    glob_expr("pathname", db_get("binary-glob","")),
    glob_expr("pathname", db_get("encoding-glob",""))
  );
  while( db_step(&q)==SQLITE_ROW ){
    int id, rid;
................................................................................
  undo_reset();

  /* Commit */
  db_multi_exec("DELETE FROM vvar WHERE name='ci-comment'");
  db_multi_exec("PRAGMA repository.application_id=252006673;");
  db_multi_exec("PRAGMA localdb.application_id=252006674;");
  if( dryRunFlag ){

    db_end_transaction(1);
    exit(1);
  }
  db_end_transaction(0);

  if( outputManifest & MFESTFLG_TAGS ){
    Blob tagslist;

Changes to src/checkout.c.

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
  int flg;

  flg = db_get_manifest_setting();

  if( flg & MFESTFLG_RAW ){
    blob_zero(&manifest);
    content_get(vid, &manifest);
    sterilize_manifest(&manifest);
    zManFile = mprintf("%smanifest", g.zLocalRoot);
    blob_write_to_file(&manifest, zManFile);
    free(zManFile);
  }else{
    if( !db_exists("SELECT 1 FROM vfile WHERE pathname='manifest'") ){
      zManFile = mprintf("%smanifest", g.zLocalRoot);
      file_delete(zManFile);







|







178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
  int flg;

  flg = db_get_manifest_setting();

  if( flg & MFESTFLG_RAW ){
    blob_zero(&manifest);
    content_get(vid, &manifest);
    sterilize_manifest(&manifest, CFTYPE_MANIFEST);
    zManFile = mprintf("%smanifest", g.zLocalRoot);
    blob_write_to_file(&manifest, zManFile);
    free(zManFile);
  }else{
    if( !db_exists("SELECT 1 FROM vfile WHERE pathname='manifest'") ){
      zManFile = mprintf("%smanifest", g.zLocalRoot);
      file_delete(zManFile);

Changes to src/clone.c.

165
166
167
168
169
170
171

172
173
174
175
176
177
178
...
196
197
198
199
200
201
202

203

204
205

206
207
208
209
210

211
212
213
214
215
216
217
...
233
234
235
236
237
238
239

240

241
242
243
244
245
246
247

  url_parse(g.argv[2], urlFlags);
  if( zDefaultUser==0 && g.url.user!=0 ) zDefaultUser = g.url.user;
  if( g.url.isFile ){
    file_copy(g.url.name, g.argv[3]);
    db_close(1);
    db_open_repository(g.argv[3]);

    db_record_repository_filename(g.argv[3]);
    url_remember();
    if( !(syncFlags & SYNC_PRIVATE) ) delete_private_content();
    shun_artifacts();
    db_create_default_users(1, zDefaultUser);
    if( zDefaultUser ){
      g.zLogin = zDefaultUser;
................................................................................
    remember_or_get_http_auth(zHttpAuth, urlFlags & URL_REMEMBER, g.argv[2]);
    url_remember();
    if( g.zSSLIdentity!=0 ){
      /* If the --ssl-identity option was specified, store it as a setting */
      Blob fn;
      blob_zero(&fn);
      file_canonical_name(g.zSSLIdentity, &fn, 0);

      db_set("ssl-identity", blob_str(&fn), 0);

      blob_reset(&fn);
    }

    db_multi_exec(
      "REPLACE INTO config(name,value,mtime)"
      " VALUES('server-code', lower(hex(randomblob(20))), now());"
      "DELETE FROM config WHERE name='project-code';"
    );

    url_enable_proxy(0);
    clone_ssh_db_set_options();
    url_get_password_if_needed();
    g.xlinkClusterOnly = 1;
    nErr = client_sync(syncFlags,CONFIGSET_ALL,0,0);
    g.xlinkClusterOnly = 0;
    verify_cancel();
................................................................................
  }
  db_end_transaction(0);
  fossil_print("Vacuuming the database... "); fflush(stdout);
  if( db_int(0, "PRAGMA page_count")>1000
   && db_int(0, "PRAGMA page_size")<8192 ){
     db_multi_exec("PRAGMA page_size=8192;");
  }

  db_multi_exec("VACUUM");

  fossil_print("\nproject-id: %s\n", db_get("project-code", 0));
  fossil_print("server-id:  %s\n", db_get("server-code", 0));
  zPassword = db_text(0, "SELECT pw FROM user WHERE login=%Q", g.zLogin);
  fossil_print("admin-user: %s (password is \"%s\")\n", g.zLogin, zPassword);
}

/*







>







 







>

>


>





>







 







>

>







165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
...
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
...
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254

  url_parse(g.argv[2], urlFlags);
  if( zDefaultUser==0 && g.url.user!=0 ) zDefaultUser = g.url.user;
  if( g.url.isFile ){
    file_copy(g.url.name, g.argv[3]);
    db_close(1);
    db_open_repository(g.argv[3]);
    db_open_config(1,0);
    db_record_repository_filename(g.argv[3]);
    url_remember();
    if( !(syncFlags & SYNC_PRIVATE) ) delete_private_content();
    shun_artifacts();
    db_create_default_users(1, zDefaultUser);
    if( zDefaultUser ){
      g.zLogin = zDefaultUser;
................................................................................
    remember_or_get_http_auth(zHttpAuth, urlFlags & URL_REMEMBER, g.argv[2]);
    url_remember();
    if( g.zSSLIdentity!=0 ){
      /* If the --ssl-identity option was specified, store it as a setting */
      Blob fn;
      blob_zero(&fn);
      file_canonical_name(g.zSSLIdentity, &fn, 0);
      db_unprotect(PROTECT_ALL);
      db_set("ssl-identity", blob_str(&fn), 0);
      db_protect_pop();
      blob_reset(&fn);
    }
    db_unprotect(PROTECT_CONFIG);
    db_multi_exec(
      "REPLACE INTO config(name,value,mtime)"
      " VALUES('server-code', lower(hex(randomblob(20))), now());"
      "DELETE FROM config WHERE name='project-code';"
    );
    db_protect_pop();
    url_enable_proxy(0);
    clone_ssh_db_set_options();
    url_get_password_if_needed();
    g.xlinkClusterOnly = 1;
    nErr = client_sync(syncFlags,CONFIGSET_ALL,0,0);
    g.xlinkClusterOnly = 0;
    verify_cancel();
................................................................................
  }
  db_end_transaction(0);
  fossil_print("Vacuuming the database... "); fflush(stdout);
  if( db_int(0, "PRAGMA page_count")>1000
   && db_int(0, "PRAGMA page_size")<8192 ){
     db_multi_exec("PRAGMA page_size=8192;");
  }
  db_unprotect(PROTECT_ALL);
  db_multi_exec("VACUUM");
  db_protect_pop();
  fossil_print("\nproject-id: %s\n", db_get("project-code", 0));
  fossil_print("server-id:  %s\n", db_get("server-code", 0));
  zPassword = db_text(0, "SELECT pw FROM user WHERE login=%Q", g.zLogin);
  fossil_print("admin-user: %s (password is \"%s\")\n", g.zLogin, zPassword);
}

/*

Changes to src/comformat.c.

549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
**   --trimcrlf       Enable trimming of leading/trailing CR/LF.
**   --trimspace      Enable trimming of leading/trailing spaces.
**   --wordbreak      Attempt to break lines on word boundaries.
**   --origbreak      Attempt to break when the original comment text
**                    is detected.
**   --indent         Number of spaces to indent (default (-1) is to
**                    auto-detect).  Zero means no indent.
**   -W|--width <num> Width of lines (default (-1) is to auto-detect).
**                    Zero means no limit.
*/
void test_comment_format(void){
  const char *zWidth;
  const char *zIndent;
  const char *zPrefix;
  char *zText;







|







549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
**   --trimcrlf       Enable trimming of leading/trailing CR/LF.
**   --trimspace      Enable trimming of leading/trailing spaces.
**   --wordbreak      Attempt to break lines on word boundaries.
**   --origbreak      Attempt to break when the original comment text
**                    is detected.
**   --indent         Number of spaces to indent (default (-1) is to
**                    auto-detect).  Zero means no indent.
**   -W|--width NUM   Width of lines (default (-1) is to auto-detect).
**                    Zero means no limit.
*/
void test_comment_format(void){
  const char *zWidth;
  const char *zIndent;
  const char *zPrefix;
  char *zText;

Changes to src/configure.c.

35
36
37
38
39
40
41

42
43
44
45
46
47
48
49
..
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
...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
...
174
175
176
177
178
179
180


181
182
183
184
185
186
187
...
257
258
259
260
261
262
263



264
265
266
267
268
269
270
...
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
...
594
595
596
597
598
599
600
















601
602
603
604
605
606
607
...
708
709
710
711
712
713
714

715
716
717
718
719
720
721
722
...
837
838
839
840
841
842
843

844

845

846

847
848
849
850
851
852
853
....
1051
1052
1053
1054
1055
1056
1057

1058
1059
1060
1061
1062
1063
1064
1065
1066
1067

1068
1069
#define CONFIGSET_PROJ      0x000008     /* Project name */
#define CONFIGSET_SHUN      0x000010     /* Shun settings */
#define CONFIGSET_USER      0x000020     /* The USER table */
#define CONFIGSET_ADDR      0x000040     /* The CONCEALED table */
#define CONFIGSET_XFER      0x000080     /* Transfer configuration */
#define CONFIGSET_ALIAS     0x000100     /* URL Aliases */
#define CONFIGSET_SCRIBER   0x000200     /* Email subscribers */

#define CONFIGSET_ALL       0x0003ff     /* Everything */

#define CONFIGSET_OVERWRITE 0x100000     /* Causes overwrite instead of merge */

/*
** This mask is used for the common TH1 configuration settings (i.e. those
** that are not specific to one particular subsystem, such as the transfer
** subsystem).
................................................................................
** Names of the configuration sets
*/
static struct {
  const char *zName;   /* Name of the configuration set */
  int groupMask;       /* Mask for that configuration set */
  const char *zHelp;   /* What it does */
} aGroupName[] = {
  { "/email",       CONFIGSET_ADDR,  "Concealed email addresses in tickets" },
  { "/project",     CONFIGSET_PROJ,  "Project name and description"         },
  { "/skin",        CONFIGSET_SKIN | CONFIGSET_CSS,
                                     "Web interface appearance settings"    },
  { "/css",         CONFIGSET_CSS,   "Style sheet"                          },
  { "/shun",        CONFIGSET_SHUN,  "List of shunned artifacts"            },
  { "/ticket",      CONFIGSET_TKT,   "Ticket setup",                        },
  { "/user",        CONFIGSET_USER,  "Users and privilege settings"         },
  { "/xfer",        CONFIGSET_XFER,  "Transfer setup",                      },
  { "/alias",       CONFIGSET_ALIAS, "URL Aliases",                         },
  { "/subscriber",  CONFIGSET_SCRIBER,"Email notification subscriber list"  },

  { "/all",         CONFIGSET_ALL,   "All of the above"                     },
};


/*
** The following is a list of settings that we are willing to
** transfer.
**
................................................................................
  { "clean-glob",             CONFIGSET_PROJ },
  { "ignore-glob",            CONFIGSET_PROJ },
  { "keep-glob",              CONFIGSET_PROJ },
  { "crlf-glob",              CONFIGSET_PROJ },
  { "crnl-glob",              CONFIGSET_PROJ },
  { "encoding-glob",          CONFIGSET_PROJ },
  { "empty-dirs",             CONFIGSET_PROJ },
#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
  { "allow-symlinks",         CONFIGSET_PROJ },
#endif
  { "dotfiles",               CONFIGSET_PROJ },
  { "parent-project-code",    CONFIGSET_PROJ },
  { "parent-project-name",    CONFIGSET_PROJ },
  { "hash-policy",            CONFIGSET_PROJ },
  { "comment-format",         CONFIGSET_PROJ },
  { "mimetypes",              CONFIGSET_PROJ },
  { "forbid-delta-manifests", CONFIGSET_PROJ },
................................................................................
  { "@concealed",             CONFIGSET_ADDR },

  { "@shun",                  CONFIGSET_SHUN },

  { "@alias",                 CONFIGSET_ALIAS },

  { "@subscriber",            CONFIGSET_SCRIBER },



  { "xfer-common-script",     CONFIGSET_XFER },
  { "xfer-push-script",       CONFIGSET_XFER },
  { "xfer-commit-script",     CONFIGSET_XFER },
  { "xfer-ticket-script",     CONFIGSET_XFER },

};
................................................................................
        m &= ~CONFIGSET_ADDR;
      }
      return m;
    }
  }
  if( strncmp(zName, "walias:/", 8)==0 ){
    return CONFIGSET_ALIAS;



  }
  return 0;
}

/*
** A mask of all configuration tables that have been reset already.
*/
................................................................................
       blob_append_sql(&sql, ",\"%w\"", azToken[jj]);
    }
    blob_append_sql(&sql,") VALUES(%s,%s",
       azToken[1] /*safe-for-%s*/, azToken[0]/*safe-for-%s*/);
    for(jj=2; jj<nToken; jj+=2){
       blob_append_sql(&sql, ",%s", azToken[jj+1] /*safe-for-%s*/);
    }

    db_multi_exec("%s)", blob_sql_text(&sql));
    if( db_changes()==0 ){
      blob_reset(&sql);
      blob_append_sql(&sql, "UPDATE \"%w\" SET mtime=%s",
                      &zName[1], azToken[0]/*safe-for-%s*/);
      for(jj=2; jj<nToken; jj+=2){
        blob_append_sql(&sql, ", \"%w\"=%s",
................................................................................
                        azToken[jj], azToken[jj+1]/*safe-for-%s*/);
      }
      blob_append_sql(&sql, " WHERE \"%w\"=%s AND mtime<%s",
                   aType[ii].zPrimKey, azToken[1]/*safe-for-%s*/,
                   azToken[0]/*safe-for-%s*/);
      db_multi_exec("%s", blob_sql_text(&sql));
    }

    blob_reset(&sql);
    rebuildMask |= thisMask;
  }
}

/*
** Process a file full of "config" cards.
................................................................................
      );
      blob_appendf(pOut, "config /config %d\n%s\n",
                   blob_size(&rec), blob_str(&rec));
      nCard++;
      blob_reset(&rec);
    }
    db_finalize(&q);
















  }
  if( (groupMask & CONFIGSET_SCRIBER)!=0
   && db_table_exists("repository","subscriber")
  ){
    db_prepare(&q, "SELECT mtime, quote(semail),"
                   " quote(suname), quote(sdigest),"
                   " quote(sdonotcall), quote(ssub),"
................................................................................
** accept the -R or --repository option to specify a repository.
**
** >  fossil configuration export AREA FILENAME
**
**         Write to FILENAME exported configuration information for AREA.
**         AREA can be one of:
**

**             all email project shun skin ticket user alias subscriber
**
** >  fossil configuration import FILENAME
**
**         Read a configuration from FILENAME, overwriting the current
**         configuration.
**
** >  fossil configuration merge FILENAME
................................................................................
       "SELECT strftime('config-backup-%%Y%%m%%d%%H%%M%%f','now')");
    db_begin_transaction();
    export_config(mask, g.argv[3], 0, zBackup);
    for(i=0; i<count(aConfig); i++){
      const char *zName = aConfig[i].zName;
      if( (aConfig[i].groupMask & mask)==0 ) continue;
      if( zName[0]!='@' ){

        db_multi_exec("DELETE FROM config WHERE name=%Q", zName);

      }else if( fossil_strcmp(zName,"@user")==0 ){

        db_multi_exec("DELETE FROM user");

        db_create_default_users(0, 0);
      }else if( fossil_strcmp(zName,"@concealed")==0 ){
        db_multi_exec("DELETE FROM concealed");
      }else if( fossil_strcmp(zName,"@shun")==0 ){
        db_multi_exec("DELETE FROM shun");
      }else if( fossil_strcmp(zName,"@subscriber")==0 ){
        if( db_table_exists("repository","subscriber") ){
................................................................................
    if( zBlob ) fossil_fatal("cannot do both --file or --blob");
    blob_read_from_file(&x, zFile, ExtFILE);
  }else if( zBlob ){
    blob_read_from_file(&x, zBlob, ExtFILE);
  }else{
    blob_init(&x,g.argv[3],-1);
  }

  db_prepare(&ins,
     "REPLACE INTO config(name,value,mtime)"
     "VALUES(%Q,:val,now())", zVar);
  if( zBlob ){
    db_bind_blob(&ins, ":val", &x);
  }else{
    db_bind_text(&ins, ":val", blob_str(&x));
  }
  db_step(&ins);
  db_finalize(&ins);

  blob_reset(&x);
}







>
|







 







|
|

|
|
|
|
|
|
|
|
>
|







 







<
<
<







 







>
>







 







>
>
>







 







>







 







>







 







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







 







>
|







 







>

>

>

>







 







>










>


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
..
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
...
143
144
145
146
147
148
149



150
151
152
153
154
155
156
...
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
...
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
...
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
...
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
...
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
...
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
....
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
#define CONFIGSET_PROJ      0x000008     /* Project name */
#define CONFIGSET_SHUN      0x000010     /* Shun settings */
#define CONFIGSET_USER      0x000020     /* The USER table */
#define CONFIGSET_ADDR      0x000040     /* The CONCEALED table */
#define CONFIGSET_XFER      0x000080     /* Transfer configuration */
#define CONFIGSET_ALIAS     0x000100     /* URL Aliases */
#define CONFIGSET_SCRIBER   0x000200     /* Email subscribers */
#define CONFIGSET_IWIKI     0x000400     /* Interwiki codes */
#define CONFIGSET_ALL       0x0007ff     /* Everything */

#define CONFIGSET_OVERWRITE 0x100000     /* Causes overwrite instead of merge */

/*
** This mask is used for the common TH1 configuration settings (i.e. those
** that are not specific to one particular subsystem, such as the transfer
** subsystem).
................................................................................
** Names of the configuration sets
*/
static struct {
  const char *zName;   /* Name of the configuration set */
  int groupMask;       /* Mask for that configuration set */
  const char *zHelp;   /* What it does */
} aGroupName[] = {
  { "/email",       CONFIGSET_ADDR,    "Concealed email addresses in tickets" },
  { "/project",     CONFIGSET_PROJ,    "Project name and description"         },
  { "/skin",        CONFIGSET_SKIN | CONFIGSET_CSS,
                                       "Web interface appearance settings"    },
  { "/css",         CONFIGSET_CSS,     "Style sheet"                          },
  { "/shun",        CONFIGSET_SHUN,    "List of shunned artifacts"            },
  { "/ticket",      CONFIGSET_TKT,     "Ticket setup",                        },
  { "/user",        CONFIGSET_USER,    "Users and privilege settings"         },
  { "/xfer",        CONFIGSET_XFER,    "Transfer setup",                      },
  { "/alias",       CONFIGSET_ALIAS,   "URL Aliases",                         },
  { "/subscriber",  CONFIGSET_SCRIBER, "Email notification subscriber list"   },
  { "/interwiki",   CONFIGSET_IWIKI,   "Inter-wiki link prefixes"             },
  { "/all",         CONFIGSET_ALL,     "All of the above"                     },
};


/*
** The following is a list of settings that we are willing to
** transfer.
**
................................................................................
  { "clean-glob",             CONFIGSET_PROJ },
  { "ignore-glob",            CONFIGSET_PROJ },
  { "keep-glob",              CONFIGSET_PROJ },
  { "crlf-glob",              CONFIGSET_PROJ },
  { "crnl-glob",              CONFIGSET_PROJ },
  { "encoding-glob",          CONFIGSET_PROJ },
  { "empty-dirs",             CONFIGSET_PROJ },



  { "dotfiles",               CONFIGSET_PROJ },
  { "parent-project-code",    CONFIGSET_PROJ },
  { "parent-project-name",    CONFIGSET_PROJ },
  { "hash-policy",            CONFIGSET_PROJ },
  { "comment-format",         CONFIGSET_PROJ },
  { "mimetypes",              CONFIGSET_PROJ },
  { "forbid-delta-manifests", CONFIGSET_PROJ },
................................................................................
  { "@concealed",             CONFIGSET_ADDR },

  { "@shun",                  CONFIGSET_SHUN },

  { "@alias",                 CONFIGSET_ALIAS },

  { "@subscriber",            CONFIGSET_SCRIBER },

  { "@interwiki",             CONFIGSET_IWIKI },

  { "xfer-common-script",     CONFIGSET_XFER },
  { "xfer-push-script",       CONFIGSET_XFER },
  { "xfer-commit-script",     CONFIGSET_XFER },
  { "xfer-ticket-script",     CONFIGSET_XFER },

};
................................................................................
        m &= ~CONFIGSET_ADDR;
      }
      return m;
    }
  }
  if( strncmp(zName, "walias:/", 8)==0 ){
    return CONFIGSET_ALIAS;
  }
  if( strncmp(zName, "interwiki:", 10)==0 ){
    return CONFIGSET_IWIKI;
  }
  return 0;
}

/*
** A mask of all configuration tables that have been reset already.
*/
................................................................................
       blob_append_sql(&sql, ",\"%w\"", azToken[jj]);
    }
    blob_append_sql(&sql,") VALUES(%s,%s",
       azToken[1] /*safe-for-%s*/, azToken[0]/*safe-for-%s*/);
    for(jj=2; jj<nToken; jj+=2){
       blob_append_sql(&sql, ",%s", azToken[jj+1] /*safe-for-%s*/);
    }
    db_protect_only(PROTECT_SENSITIVE);
    db_multi_exec("%s)", blob_sql_text(&sql));
    if( db_changes()==0 ){
      blob_reset(&sql);
      blob_append_sql(&sql, "UPDATE \"%w\" SET mtime=%s",
                      &zName[1], azToken[0]/*safe-for-%s*/);
      for(jj=2; jj<nToken; jj+=2){
        blob_append_sql(&sql, ", \"%w\"=%s",
................................................................................
                        azToken[jj], azToken[jj+1]/*safe-for-%s*/);
      }
      blob_append_sql(&sql, " WHERE \"%w\"=%s AND mtime<%s",
                   aType[ii].zPrimKey, azToken[1]/*safe-for-%s*/,
                   azToken[0]/*safe-for-%s*/);
      db_multi_exec("%s", blob_sql_text(&sql));
    }
    db_protect_pop();
    blob_reset(&sql);
    rebuildMask |= thisMask;
  }
}

/*
** Process a file full of "config" cards.
................................................................................
      );
      blob_appendf(pOut, "config /config %d\n%s\n",
                   blob_size(&rec), blob_str(&rec));
      nCard++;
      blob_reset(&rec);
    }
    db_finalize(&q);
  }
  if( groupMask & CONFIGSET_IWIKI ){
    db_prepare(&q, "SELECT mtime, quote(name), quote(value) FROM config"
                   " WHERE name GLOB 'interwiki:*' AND mtime>=%lld", iStart);
    while( db_step(&q)==SQLITE_ROW ){
      blob_appendf(&rec,"%s %s value %s",
        db_column_text(&q, 0),
        db_column_text(&q, 1),
        db_column_text(&q, 2)
      );
      blob_appendf(pOut, "config /config %d\n%s\n",
                   blob_size(&rec), blob_str(&rec));
      nCard++;
      blob_reset(&rec);
    }
    db_finalize(&q);
  }
  if( (groupMask & CONFIGSET_SCRIBER)!=0
   && db_table_exists("repository","subscriber")
  ){
    db_prepare(&q, "SELECT mtime, quote(semail),"
                   " quote(suname), quote(sdigest),"
                   " quote(sdonotcall), quote(ssub),"
................................................................................
** accept the -R or --repository option to specify a repository.
**
** >  fossil configuration export AREA FILENAME
**
**         Write to FILENAME exported configuration information for AREA.
**         AREA can be one of:
**
**             all email interwiki project shun skin
**             ticket user alias subscriber
**
** >  fossil configuration import FILENAME
**
**         Read a configuration from FILENAME, overwriting the current
**         configuration.
**
** >  fossil configuration merge FILENAME
................................................................................
       "SELECT strftime('config-backup-%%Y%%m%%d%%H%%M%%f','now')");
    db_begin_transaction();
    export_config(mask, g.argv[3], 0, zBackup);
    for(i=0; i<count(aConfig); i++){
      const char *zName = aConfig[i].zName;
      if( (aConfig[i].groupMask & mask)==0 ) continue;
      if( zName[0]!='@' ){
        db_unprotect(PROTECT_CONFIG);
        db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
        db_protect_pop();
      }else if( fossil_strcmp(zName,"@user")==0 ){
        db_unprotect(PROTECT_USER);
        db_multi_exec("DELETE FROM user");
        db_protect_pop();
        db_create_default_users(0, 0);
      }else if( fossil_strcmp(zName,"@concealed")==0 ){
        db_multi_exec("DELETE FROM concealed");
      }else if( fossil_strcmp(zName,"@shun")==0 ){
        db_multi_exec("DELETE FROM shun");
      }else if( fossil_strcmp(zName,"@subscriber")==0 ){
        if( db_table_exists("repository","subscriber") ){
................................................................................
    if( zBlob ) fossil_fatal("cannot do both --file or --blob");
    blob_read_from_file(&x, zFile, ExtFILE);
  }else if( zBlob ){
    blob_read_from_file(&x, zBlob, ExtFILE);
  }else{
    blob_init(&x,g.argv[3],-1);
  }
  db_unprotect(PROTECT_CONFIG);
  db_prepare(&ins,
     "REPLACE INTO config(name,value,mtime)"
     "VALUES(%Q,:val,now())", zVar);
  if( zBlob ){
    db_bind_blob(&ins, ":val", &x);
  }else{
    db_bind_text(&ins, ":val", blob_str(&x));
  }
  db_step(&ins);
  db_finalize(&ins);
  db_protect_pop();
  blob_reset(&x);
}

Changes to src/copybtn.js.

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    }
    lockCopyText = false;
  }.bind(null,this.id),400);
}
/* Create a temporary <textarea> element and copy the contents to clipboard. */
function copyTextToClipboard(text){
  if( window.clipboardData && window.clipboardData.setData ){
    clipboardData.setData('Text',text);
  }else{
    var x = document.createElement("textarea");
    x.style.position = 'fixed';
    x.value = text;
    document.body.appendChild(x);
    x.select();
    try{







|







78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    }
    lockCopyText = false;
  }.bind(null,this.id),400);
}
/* Create a temporary <textarea> element and copy the contents to clipboard. */
function copyTextToClipboard(text){
  if( window.clipboardData && window.clipboardData.setData ){
    window.clipboardData.setData('Text',text);
  }else{
    var x = document.createElement("textarea");
    x.style.position = 'fixed';
    x.value = text;
    document.body.appendChild(x);
    x.select();
    try{

Changes to src/db.c.

67
68
69
70
71
72
73

74
75
76
77
78
79
80
...
111
112
113
114
115
116
117

118
119
120
121
122
123
124
...
131
132
133
134
135
136
137





138
139
140
141
142
143
144
145
...
206
207
208
209
210
211
212



213
214
215
216
217
218
219

220
221
222
223
224
225
226
...
239
240
241
242
243
244
245

246
247
248
249
250
251
252

253
254
255
256
257
258
259
...
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
...
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
...
638
639
640
641
642
643
644

645
646
647
648
649
650
651
652
653
654

















655
656
657
658
659
660
661
...
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
....
1090
1091
1092
1093
1094
1095
1096



























1097
1098
1099
1100
1101
1102
1103
....
1120
1121
1122
1123
1124
1125
1126


1127
1128
1129
1130
1131
1132
1133
....
1378
1379
1380
1381
1382
1383
1384

1385
1386
1387
1388
1389
1390
1391
....
1813
1814
1815
1816
1817
1818
1819



1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
....
1875
1876
1877
1878
1879
1880
1881

1882
1883
1884

1885
1886
1887
1888
1889
1890
1891
....
2167
2168
2169
2170
2171
2172
2173

2174

2175
2176
2177
2178
2179
2180
2181
....
2185
2186
2187
2188
2189
2190
2191

2192
2193
2194
2195
2196
2197
2198
....
2247
2248
2249
2250
2251
2252
2253

2254
2255
2256
2257
2258
2259
2260
....
2266
2267
2268
2269
2270
2271
2272

2273
2274
2275
2276
2277
2278
2279
....
2317
2318
2319
2320
2321
2322
2323

2324
2325
2326
2327
2328
2329
2330
....
2375
2376
2377
2378
2379
2380
2381

2382
2383
2384
2385
2386
2387
2388
....
2871
2872
2873
2874
2875
2876
2877


2878
2879
2880
2881
2882
2883
2884
....
2885
2886
2887
2888
2889
2890
2891

2892
2893
2894

2895
2896
2897
2898
2899
2900
2901
2902
2903
2904

2905
2906
2907
2908
2909
2910
2911
....
2931
2932
2933
2934
2935
2936
2937


2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949

2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
....
3074
3075
3076
3077
3078
3079
3080


3081
3082
3083
3084
3085
3086
3087
3088
3089

3090
3091
3092
3093
3094

3095
3096
3097
3098
3099
3100
3101
....
3107
3108
3109
3110
3111
3112
3113

3114
3115
3116
3117
3118
3119
3120
....
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
....
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
....
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
....
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
....
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
....
3416
3417
3418
3419
3420
3421
3422
3423
3424

3425
3426
3427
3428
3429
3430
3431
....
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446

3447
3448
3449
3450
3451
3452
3453


3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
....
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
....
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
....
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
....
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
....
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
....
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
....
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
....
4116
4117
4118
4119
4120
4121
4122

4123

4124
4125
4126
4127
4128
4129
4130
*/
#define empty_Stmt_m {BLOB_INITIALIZER,NULL, NULL, NULL, 0, 0}
#endif /* INTERFACE */
const struct Stmt empty_Stmt = empty_Stmt_m;

/*
** Call this routine when a database error occurs.

*/
static void db_err(const char *zFormat, ...){
  va_list ap;
  char *z;
  va_start(ap, zFormat);
  z = vmprintf(zFormat, ap);
  va_end(ap);
................................................................................
}

/*
** All static variable that a used by only this file are gathered into
** the following structure.
*/
static struct DbLocalData {

  int nBegin;               /* Nesting depth of BEGIN */
  int doRollback;           /* True to force a rollback */
  int nCommitHook;          /* Number of commit hooks */
  int wrTxn;                /* Outer-most TNX is a write */
  Stmt *pAllStmt;           /* List of all unfinalized statements */
  int nPrepare;             /* Number of calls to sqlite3_prepare_v2() */
  int nDeleteOnFail;        /* Number of entries in azDeleteOnFail[] */
................................................................................
  int nBeforeCommit;        /* Number of entries in azBeforeCommit */
  int nPriorChanges;        /* sqlite3_total_changes() at transaction start */
  const char *zStartFile;   /* File in which transaction was started */
  int iStartLine;           /* Line of zStartFile where transaction started */
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  void *pAuthArg;           /* Argument to the authorizer */
  const char *zAuthName;    /* Name of the authorizer */





} db = {0, 0, 0, 0, 0, 0, };

/*
** Arrange for the given file to be deleted on a failure.
*/
void db_delete_on_failure(const char *zFilename){
  assert( db.nDeleteOnFail<count(db.azDeleteOnFail) );
  if( zFilename==0 ) return;
................................................................................
  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;
    db.wrTxn = 1;

  }else if( !db.wrTxn ){
    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++;
}
................................................................................
    if( g.fSqlTrace ) fossil_trace("-- ROLLBACK by request\n");
  }
  db.nBegin--;
  if( db.nBegin==0 ){
    int i;
    if( db.doRollback==0 && db.nPriorChanges<sqlite3_total_changes(g.db) ){
      i = 0;

      while( db.nBeforeCommit ){
        db.nBeforeCommit--;
        sqlite3_exec(g.db, db.azBeforeCommit[i], 0, 0, 0);
        sqlite3_free(db.azBeforeCommit[i]);
        i++;
      }
      leaf_do_pending_checks();

    }
    for(i=0; db.doRollback==0 && i<db.nCommitHook; i++){
      int rc = db.aHook[i].xHook();
      if( rc ){
        db.doRollback = 1;
        if( g.fSqlTrace ) fossil_trace("-- ROLLBACK due to aHook[%d]\n", i);
      }
................................................................................
      db.aHook[i].xHook = xS;
    }
  }
  db.aHook[db.nCommitHook].sequence = sequence;
  db.aHook[db.nCommitHook].xHook = x;
  db.nCommitHook++;
}


/*


































































































































































































** Set or unset the query authorizer callback function
*/
void db_set_authorizer(
  int(*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  void *pArg,
  const char *zName /* for tracing */
){
  if( db.xAuth ){
    fossil_panic("multiple active db_set_authorizer() calls");
  }
  if( g.db ) sqlite3_set_authorizer(g.db, xAuth, pArg);
  db.xAuth = xAuth;
  db.pAuthArg = pArg;
  db.zAuthName = zName;
  if( g.fSqlTrace ) fossil_trace("-- set authorizer %s\n", zName);
}
void db_clear_authorizer(void){
  if( db.zAuthName && g.fSqlTrace ){
    fossil_trace("-- discontinue authorizer %s\n", db.zAuthName);
  }
  if( g.db ) sqlite3_set_authorizer(g.db, 0, 0);
  db.xAuth = 0;
  db.pAuthArg = 0;

}

#if INTERFACE
/*
** Possible flags to db_vprepare
*/
#define DB_PREPARE_IGNORE_ERROR  0x001  /* Suppress errors */
................................................................................
** If the input string contains multiple SQL statements, only the first
** one is processed.  All statements beyond the first are silently ignored.
*/
int db_vprepare(Stmt *pStmt, int flags, const char *zFormat, va_list ap){
  int rc;
  int prepFlags = 0;
  char *zSql;

  blob_zero(&pStmt->sql);
  blob_vappendf(&pStmt->sql, zFormat, ap);
  va_end(ap);
  zSql = blob_str(&pStmt->sql);
  db.nPrepare++;
  if( flags & DB_PREPARE_PERSISTENT ){
    prepFlags = SQLITE_PREPARE_PERSISTENT;
  }
  rc = sqlite3_prepare_v3(g.db, zSql, -1, prepFlags, &pStmt->pStmt, 0);
  if( rc!=0 && (flags & DB_PREPARE_IGNORE_ERROR)==0 ){
    db_err("%s\n%s", sqlite3_errmsg(g.db), zSql);


  }
  pStmt->pNext = db.pAllStmt;
  pStmt->pPrev = 0;
  if( db.pAllStmt ) db.pAllStmt->pPrev = pStmt;
  db.pAllStmt = pStmt;
  pStmt->nStep = 0;
  pStmt->rc = rc;
................................................................................
  rc = db_reset(pStmt);
  db_check_result(rc, pStmt);
  return rc;
}

/*
** COMMAND: test-db-exec-error

**
** Invoke the db_exec() interface with an erroneous SQL statement
** in order to verify the error handling logic.
*/
void db_test_db_exec_cmd(void){
  Stmt err;
  db_find_and_open_repository(0,0);
  db_prepare(&err, "INSERT INTO repository.config(name) VALUES(NULL);");
  db_exec(&err);
}


















/*
** Print the output of one or more SQL queries on standard output.
** This routine is used for debugging purposes only.
*/
int db_debug(const char *zSql, ...){
  Blob sql;
................................................................................
  sqlite3 *xdb;
  int rc;
  const char *zSql;
  va_list ap;

  xdb = db_open(zFileName ? zFileName : ":memory:");
  sqlite3_exec(xdb, "BEGIN EXCLUSIVE", 0, 0, 0);
  if( db.xAuth ){
    sqlite3_set_authorizer(xdb, db.xAuth, db.pAuthArg);
  }
  rc = sqlite3_exec(xdb, zSchema, 0, 0, 0);
  if( rc!=SQLITE_OK ){
    db_err("%s", sqlite3_errmsg(xdb));
  }
  va_start(ap, zSchema);
  while( (zSql = va_arg(ap, const char*))!=0 ){
    rc = sqlite3_exec(xdb, zSql, 0, 0, 0);
................................................................................
    sqlite3_result_error_nomem(context);
    return;
  }
  strcpy(zOut, zTemp = obscure((char*)zIn));
  fossil_free(zTemp);
  sqlite3_result_text(context, zOut, strlen(zOut), sqlite3_free);
}




























/*
** Register the SQL functions that are useful both to the internal
** representation and to the "fossil sql" command.
*/
void db_add_aux_functions(sqlite3 *db){
  sqlite3_create_function(db, "checkin_mtime", 2, SQLITE_UTF8, 0,
................................................................................
                          capability_fullcap, 0, 0);
  sqlite3_create_function(db, "find_emailaddr", 1, SQLITE_UTF8, 0,
                          alert_find_emailaddr_func, 0, 0);
  sqlite3_create_function(db, "display_name", 1, SQLITE_UTF8, 0,
                          alert_display_name_func, 0, 0);
  sqlite3_create_function(db, "obscure", 1, SQLITE_UTF8, 0,
                          db_obscure, 0, 0);


}

#if USE_SEE
/*
** This is a pointer to the saved database encryption key string.
*/
static char *zSavedKey = 0;
................................................................................
    db, "if_selected", 3, SQLITE_UTF8, 0, file_is_selected,0,0
  );
  if( g.fSqlTrace ) sqlite3_trace_v2(db, SQLITE_TRACE_PROFILE, db_sql_trace, 0);
  db_add_aux_functions(db);
  re_add_sql_func(db);  /* The REGEXP operator */
  foci_register(db);    /* The "files_of_checkin" virtual table */
  sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_FKEY, 0, &rc);

  return db;
}


/*
** Detaches the zLabel database.
*/
................................................................................
  assert( g.zLocalRoot );
  if( zRepo==0 ){
    zRepo = db_lget("repository", 0);
    if( zRepo && !file_is_absolute_path(zRepo) ){
      char * zFree = zRepo;
      zRepo = mprintf("%s%s", g.zLocalRoot, zRepo);
      fossil_free(zFree);



    }
  }
  return zRepo;
}

/*
** Returns non-zero if the default value for the "allow-symlinks" setting
** is "on".  When on Windows, this always returns false.
*/
int db_allow_symlinks_by_default(void){
#if defined(_WIN32) || !defined(FOSSIL_LEGACY_ALLOW_SYMLINKS)
  return 0;
#else
  return 1;
#endif
}

/*
** Returns non-zero if support for symlinks is currently enabled.
*/
int db_allow_symlinks(void){
  return g.allowSymlinks;
}

................................................................................
    }
  }
  g.zRepositoryName = mprintf("%s", zDbName);
  db_open_or_attach(g.zRepositoryName, "repository");
  g.repositoryOpen = 1;
  sqlite3_file_control(g.db, "repository", SQLITE_FCNTL_DATA_VERSION,
                       &g.iRepoDataVers);

  /* Cache "allow-symlinks" option, because we'll need it on every stat call */
  g.allowSymlinks = db_get_boolean("allow-symlinks",
                                   db_allow_symlinks_by_default());

  g.zAuxSchema = db_get("aux-schema","");
  g.eHashPolicy = db_get_int("hash-policy",-1);
  if( g.eHashPolicy<0 ){
    g.eHashPolicy = hname_default_policy();
    db_set_int("hash-policy", g.eHashPolicy, 0);
  }

................................................................................
  /* If the localdb has a lot of unused free space,
  ** then VACUUM it as we shut down.
  */
  if( db_database_slot("localdb")>=0 ){
    int nFree = db_int(0, "PRAGMA localdb.freelist_count");
    int nTotal = db_int(0, "PRAGMA localdb.page_count");
    if( nFree>nTotal/4 ){

      db_multi_exec("VACUUM localdb;");

    }
  }

  if( g.db ){
    int rc;
    sqlite3_wal_checkpoint(g.db, 0);
    rc = sqlite3_close(g.db);
................................................................................
        fossil_warning("unfinalized SQL statement: [%s]", sqlite3_sql(pStmt));
      }
    }
    g.db = 0;
  }
  g.repositoryOpen = 0;
  g.localOpen = 0;

  assert( g.dbConfig==0 );
  assert( g.zConfigDbName==0 );
  backoffice_run_if_needed();
}

/*
** Close the database as quickly as possible without unnecessary processing.
................................................................................
  }
  if( zUser==0 ){
    zUser = fossil_getenv("USERNAME");
  }
  if( zUser==0 ){
    zUser = "root";
  }

  db_multi_exec(
     "INSERT OR IGNORE INTO user(login, info) VALUES(%Q,'')", zUser
  );
  db_multi_exec(
     "UPDATE user SET cap='s', pw=%Q"
     " WHERE login=%Q", fossil_random_password(10), zUser
  );
................................................................................
       "   VALUES('nobody','','gjorz','Nobody');"
       "INSERT OR IGNORE INTO user(login,pw,cap,info)"
       "   VALUES('developer','','ei','Dev');"
       "INSERT OR IGNORE INTO user(login,pw,cap,info)"
       "   VALUES('reader','','kptw','Reader');"
    );
  }

}

/*
** Return a pointer to a string that contains the RHS of an IN operator
** that will select CONFIG table names that are in the list of control
** settings.
*/
................................................................................
  const char *zInitialDate,    /* Initial date of repository. (ex: "now") */
  const char *zDefaultUser     /* Default user for the repository */
){
  char *zDate;
  Blob hash;
  Blob manifest;


  db_set("content-schema", CONTENT_SCHEMA, 0);
  db_set("aux-schema", AUX_SCHEMA_MAX, 0);
  db_set("rebuilt", get_version(), 0);
  db_set("admin-log", "1", 0);
  db_set("access-log", "1", 0);
  db_multi_exec(
      "INSERT INTO config(name,value,mtime)"
................................................................................
      "  mtime = (SELECT u2.mtime FROM settingSrc.user u2"
      "           WHERE u2.login = user.login),"
      "  photo = (SELECT u2.photo FROM settingSrc.user u2"
      "           WHERE u2.login = user.login)"
      " WHERE user.login IN ('anonymous','nobody','developer','reader');"
    );
  }


  if( zInitialDate ){
    int rid;
    blob_zero(&manifest);
    blob_appendf(&manifest, "C initial\\sempty\\scheck-in\n");
    zDate = date_in_standard_format(zInitialDate);
    blob_appendf(&manifest, "D %s\n", zDate);
................................................................................
    z = fossil_strdup(zDefault);
  }else if( zFormat!=0 ){
    z = db_text(0, "SELECT strftime(%Q,%Q,'unixepoch');", zFormat, z);
  }
  return z;
}
void db_set(const char *zName, const char *zValue, int globalFlag){


  db_begin_transaction();
  if( globalFlag ){
    db_swap_connections();
    db_multi_exec("REPLACE INTO global_config(name,value) VALUES(%Q,%Q)",
                   zName, zValue);
    db_swap_connections();
  }else{
................................................................................
    db_multi_exec("REPLACE INTO config(name,value,mtime) VALUES(%Q,%Q,now())",
                   zName, zValue);
  }
  if( globalFlag && g.repositoryOpen ){
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }
  db_end_transaction(0);

}
void db_unset(const char *zName, int globalFlag){
  db_begin_transaction();

  if( globalFlag ){
    db_swap_connections();
    db_multi_exec("DELETE FROM global_config WHERE name=%Q", zName);
    db_swap_connections();
  }else{
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }
  if( globalFlag && g.repositoryOpen ){
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }

  db_end_transaction(0);
}
int db_is_global(const char *zName){
  int rc = 0;
  if( g.zConfigDbName ){
    db_swap_connections();
    rc = db_exists("SELECT 1 FROM global_config WHERE name=%Q", zName);
................................................................................
    db_swap_connections();
    v = db_int(dflt, "SELECT value FROM global_config WHERE name=%Q", zName);
    db_swap_connections();
  }
  return v;
}
void db_set_int(const char *zName, int value, int globalFlag){


  if( globalFlag ){
    db_swap_connections();
    db_multi_exec("REPLACE INTO global_config(name,value) VALUES(%Q,%d)",
                  zName, value);
    db_swap_connections();
  }else{
    db_multi_exec("REPLACE INTO config(name,value,mtime) VALUES(%Q,%d,now())",
                  zName, value);
  }
  if( globalFlag && g.repositoryOpen ){
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }

}
int db_get_boolean(const char *zName, int dflt){
  char *zVal = db_get(zName, dflt ? "on" : "off");
  if( is_truth(zVal) ){
    dflt = 1;
  }else if( is_false(zVal) ){
    dflt = 0;
  }
  fossil_free(zVal);
  return dflt;
}
#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
int db_get_versioned_boolean(const char *zName, int dflt){
  char *zVal = db_get_versioned(zName, 0);
  if( zVal==0 ) return dflt;
  if( is_truth(zVal) ) return 1;
  if( is_false(zVal) ) return 0;
  return dflt;
}
#endif /* FOSSIL_LEGACY_ALLOW_SYMLINKS */
char *db_lget(const char *zName, const char *zDefault){
  return db_text(zDefault,
                 "SELECT value FROM vvar WHERE name=%Q", zName);
}
void db_lset(const char *zName, const char *zValue){
  db_multi_exec("REPLACE INTO vvar(name,value) VALUES(%Q,%Q)", zName, zValue);
}
................................................................................
    if( !g.localOpen ) return;
    zName = db_repository_filename();
  }
  file_canonical_name(zName, &full, 0);
  (void)filename_collation();  /* Initialize before connection swap */
  db_swap_connections();
  zRepoSetting = mprintf("repo:%q", blob_str(&full));


  db_multi_exec(
     "DELETE FROM global_config WHERE name %s = %Q;",
     filename_collation(), zRepoSetting
  );
  db_multi_exec(
     "INSERT OR IGNORE INTO global_config(name,value)"
     "VALUES(%Q,1);",
     zRepoSetting
  );

  fossil_free(zRepoSetting);
  if( g.localOpen && g.zLocalRoot && g.zLocalRoot[0] ){
    Blob localRoot;
    file_canonical_name(g.zLocalRoot, &localRoot, 1);
    zCkoutSetting = mprintf("ckout:%q", blob_str(&localRoot));

    db_multi_exec(
       "DELETE FROM global_config WHERE name %s = %Q;",
       filename_collation(), zCkoutSetting
    );
    db_multi_exec(
      "REPLACE INTO global_config(name, value)"
      "VALUES(%Q,%Q);",
................................................................................
        filename_collation(), zCkoutSetting
    );
    db_optional_sql("repository",
        "REPLACE INTO config(name,value,mtime)"
        "VALUES(%Q,1,now());",
        zCkoutSetting
    );

    fossil_free(zCkoutSetting);
    blob_reset(&localRoot);
  }else{
    db_swap_connections();
  }
  blob_reset(&full);
}
................................................................................
** "new-name" term means that the cloned repository will be called
** "new-name.fossil".
**
** Options:
**   --empty           Initialize checkout as being empty, but still connected
**                     with the local repository. If you commit this checkout,
**                     it will become a new "initial" commit in the repository.
**   --force           Continue with the open even if the working directory is
**                     not empty.
**   --force-missing   Force opening a repository with missing content
**   --keep            Only modify the manifest and manifest.uuid files
**   --nested          Allow opening a repository inside an opened checkout
**   --repodir DIR     If REPOSITORY is a URI that will be cloned, store
**                     the clone in DIR rather than in "."
**   --setmtime        Set timestamps of all files to match their SCM-side
................................................................................
** See also: [[close]], [[clone]]
*/
void cmd_open(void){
  int emptyFlag;
  int keepFlag;
  int forceMissingFlag;
  int allowNested;
#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
  int allowSymlinks;
#endif
  int setmtimeFlag;              /* --setmtime.  Set mtimes on files */
  int bForce = 0;                /* --force.  Open even if non-empty dir */
  static char *azNewArgv[] = { 0, "checkout", "--prompt", 0, 0, 0, 0 };
  const char *zWorkDir;          /* --workdir value */
  const char *zRepo = 0;         /* Name of the repository file */
  const char *zRepoDir = 0;      /* --repodir value */
  char *zPwd;                    /* Initial working directory */
................................................................................
  emptyFlag = find_option("empty",0,0)!=0;
  keepFlag = find_option("keep",0,0)!=0;
  forceMissingFlag = find_option("force-missing",0,0)!=0;
  allowNested = find_option("nested",0,0)!=0;
  setmtimeFlag = find_option("setmtime",0,0)!=0;
  zWorkDir = find_option("workdir",0,1);
  zRepoDir = find_option("repodir",0,1);
  bForce = find_option("force",0,0)!=0;  
  zPwd = file_getcwd(0,0);
  

  /* We should be done with options.. */
  verify_all_options();

  if( g.argc!=3 && g.argc!=4 ){
................................................................................
    }
    if( file_chdir(zWorkDir, 0) ){
      fossil_fatal("unable to make %s the working directory", zWorkDir);
    }
  }
  if( keepFlag==0 && bForce==0 && file_directory_size(".", 0, 1)>0 ){
    fossil_fatal("directory %s is not empty\n"
                 "use the --force option to override", file_getcwd(0,0));
  }

  if( db_open_local_v2(0, allowNested) ){
    fossil_fatal("there is already an open tree at %s", g.zLocalRoot);
  }

  /* If REPOSITORY looks like a URI, then try to clone it first */
................................................................................
    if( g.argc==4 ){
      g.zOpenRevision = g.argv[3];
    }else if( db_exists("SELECT 1 FROM event WHERE type='ci'") ){
      g.zOpenRevision = db_get("main-branch", 0);
    }
  }

#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
  if( g.zOpenRevision ){
    /* Since the repository is open and we know the revision now,
    ** refresh the allow-symlinks flag.  Since neither the local
    ** checkout nor the configuration database are open at this
    ** point, this should always return the versioned setting,
    ** if any, or the default value, which is negative one.  The
    ** value negative one, in this context, means that the code
    ** below should fallback to using the setting value from the
    ** repository or global configuration databases only. */
    allowSymlinks = db_get_versioned_boolean("allow-symlinks", -1);
  }else{
    allowSymlinks = -1; /* Use non-versioned settings only. */
  }
#endif

#if defined(_WIN32) || defined(__CYGWIN__)
# define LOCALDB_NAME "./_FOSSIL_"
#else
# define LOCALDB_NAME "./.fslckout"
#endif
  db_init_database(LOCALDB_NAME, zLocalSchema, zLocalSchemaVmerge,
#ifdef FOSSIL_LOCAL_WAL
                   "COMMIT; PRAGMA journal_mode=WAL; BEGIN;",
#endif
                   (char*)0);
  db_delete_on_failure(LOCALDB_NAME);
  db_open_local(0);
#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
  if( allowSymlinks>=0 ){
    /* Use the value from the versioned setting, which was read
    ** prior to opening the local checkout (i.e. which is most
    ** likely empty and does not actually contain any versioned
    ** setting files yet).  Normally, this value would be given
    ** first priority within db_get_boolean(); however, this is
    ** a special case because we know the on-disk files may not
    ** exist yet. */
    g.allowSymlinks = allowSymlinks;
  }else{
    /* Since the local checkout may not have any files at this
    ** point, this will probably be the setting value from the
    ** repository or global configuration databases. */
    g.allowSymlinks = db_get_boolean("allow-symlinks",
                                     db_allow_symlinks_by_default());
  }
#endif /* FOSSIL_LEGACY_ALLOW_SYMLINKS */
  db_lset("repository", zRepo);
  db_record_repository_filename(zRepo);
  db_set_checkout(0);
  azNewArgv[0] = g.argv[0];
  g.argv = azNewArgv;
  if( !emptyFlag ){
    g.argc = 3;
................................................................................
*/
struct Setting {
  const char *name;     /* Name of the setting */
  const char *var;      /* Internal variable name used by db_set() */
  int width;            /* Width of display.  0 for boolean values and
                        ** negative for values which should not appear
                        ** on the /setup_settings page. */
  int versionable;      /* Is this setting versionable? */
  int forceTextArea;    /* Force using a text area for display? */

  const char *def;      /* Default value */
};
#endif /* INTERFACE */

/*
** SETTING: access-log      boolean default=off
**
................................................................................
*/
/*
** SETTING: admin-log       boolean default=off
**
** When the admin-log setting is enabled, configuration changes are recorded
** in the "admin_log" table of the repository.
*/
#if !defined(FOSSIL_LEGACY_ALLOW_SYMLINKS)
/*
** SETTING: allow-symlinks  boolean default=off
**
** When allow-symlinks is OFF (which is the default and recommended setting)

** symbolic links are treated like text files that contain a single line of
** content which is the name of their target.  If allow-symlinks is ON,
** the symbolic links are actually followed.
**
** The use of symbolic links is dangerous.  If you checkout a maliciously
** crafted checkin that contains symbolic links, it is possible that files
** outside of the working directory might be overwritten.


**
** Keep this setting OFF unless you have a very good reason to turn it
** on and you implicitly trust the integrity of the repositories you
** open.
*/
#endif
#if defined(_WIN32) && defined(FOSSIL_LEGACY_ALLOW_SYMLINKS)
/*
** SETTING: allow-symlinks  boolean default=off versionable
**
** When allow-symlinks is OFF, symbolic links in the repository are followed
** and treated no differently from real files.  When allow-symlinks is ON,
** the object to which the symbolic link points is ignored, and the content
** of the symbolic link that is stored in the repository is the name of the
** object to which the symbolic link points.
*/
#endif
#if !defined(_WIN32) && defined(FOSSIL_LEGACY_ALLOW_SYMLINKS)
/*
** SETTING: allow-symlinks  boolean default=on versionable
**
** When allow-symlinks is OFF, symbolic links in the repository are followed
** and treated no differently from real files.  When allow-symlinks is ON,
** the object to which the symbolic link points is ignored, and the content
** of the symbolic link that is stored in the repository is the name of the
** object to which the symbolic link points.
*/
#endif
/*
** SETTING: auto-captcha    boolean default=on variable=autocaptcha
** If enabled, the /login page provides a button that will automatically
** fill in the captcha password.  This makes things easier for human users,
** at the expense of also making logins easier for malicious robots.
*/
/*
................................................................................
** Backoffice processing does things such as delivering
** email notifications.  So if this setting is true, and if
** there is no cron job periodically running "fossil backoffice",
** email notifications and other work normally done by the
** backoffice will not occur.
*/
/*
** SETTING: backoffice-logfile width=40
** If backoffice-logfile is not an empty string and is a valid
** filename, then a one-line message is appended to that file
** every time the backoffice runs.  This can be used for debugging,
** to ensure that backoffice is running appropriately.
*/
/*
** SETTING: binary-glob     width=40 versionable block-text
................................................................................
** The crnl-glob setting is a compatibility alias.
*/
/*
** SETTING: crnl-glob       width=40 versionable block-text
** This is an alias for the crlf-glob setting.
*/
/*
** SETTING: default-perms   width=16 default=u
** Permissions given automatically to new users.  For more
** information on permissions see the Users page in Server
** Administration of the HTTP UI.
*/
/*
** SETTING: diff-binary     boolean default=on
** If enabled, permit files that may be binary
** or that match the "binary-glob" setting to be used with
** external diff programs.  If disabled, skip these files.
*/
/*
** SETTING: diff-command    width=40
** The value is an external command to run when performing a diff.
** If undefined, the internal text diff will be used.
*/
/*
** SETTING: dont-push       boolean default=off
** If enabled, prevent this repository from pushing from client to
** server.  This can be used as an extra precaution to prevent
................................................................................
** accidental pushes to a public server from a private clone.
*/
/*
** SETTING: dotfiles        boolean versionable default=off
** If enabled, include --dotfiles option for all compatible commands.
*/
/*
** SETTING: editor          width=32
** The value is an external command that will launch the
** text editor command used for check-in comments.
*/
/*
** SETTING: empty-dirs      width=40 versionable block-text
** The value is a comma or newline-separated list of pathnames. On
** update and checkout commands, if no file or directory
................................................................................
** A comma- or newline-separated list of globs of filenames
** which are allowed to be edited using the /fileedit page.
** An empty list prohibits editing via that page. Note that
** it cannot edit binary files, so the list should not
** contain any globs for, e.g., images or PDFs.
*/
/*
** SETTING: gdiff-command    width=40 default=gdiff
** The value is an external command to run when performing a graphical
** diff. If undefined, text diff will be used.
*/
/*
** SETTING: gmerge-command   width=40
** The value is a graphical merge conflict resolver command operating
** on four files.  Examples:
**
**     kdiff3 "%baseline" "%original" "%merge" -o "%output"
**     xxdiff "%original" "%baseline" "%merge" -M "%output"
**     meld "%baseline" "%original" "%merge" "%output"
*/
................................................................................
** SETTING: mv-rm-files      boolean default=off
** If enabled, the "mv" and "rename" commands will also move
** the associated files within the checkout -AND- the "rm"
** and "delete" commands will also remove the associated
** files from within the checkout.
*/
/*
** SETTING: pgp-command      width=40
** Command used to clear-sign manifests at check-in.
** Default value is "gpg --clearsign -o"
*/
/*
** SETTING: forbid-delta-manifests    boolean default=off
** If enabled on a client, new delta manifests are prohibited on
** commits.  If enabled on a server, whenever a client attempts
................................................................................
** have a non-zero "repolist-skin" setting then the repository list is
** displayed using unadorned HTML ("skinless").
**
** If repolist-skin has a value of 2, then the repository is omitted from
** the list in use cases 1 through 4, but not for 5 and 6.
*/
/*
** SETTING: self-register    boolean default=off
** Allow users to register themselves through the HTTP UI.
** This is useful if you want to see other names than
** "Anonymous" in e.g. ticketing system. On the other hand
** users can not be deleted.
*/
/*
** SETTING: ssh-command      width=40
** The command used to talk to a remote machine with  the "ssh://" protocol.
*/
/*
** SETTING: ssl-ca-location  width=40
** The full pathname to a file containing PEM encoded
** CA root certificates, or a directory of certificates
** with filenames formed from the certificate hashes as
** required by OpenSSL.
**
** If set, this will override the OS default list of
** OpenSSL CAs. If unset, the default list will be used.
** Some platforms may add additional certificates.
** Checking your platform behaviour is required if the
** exact contents of the CA root is critical for your
** application.
*/
/*
** SETTING: ssl-identity     width=40
** The full pathname to a file containing a certificate
** and private key in PEM format. Create by concatenating
** the certificate and private key files.
**
** This identity will be presented to SSL servers to
** authenticate this client, in addition to the normal
** password authentication.
*/
#ifdef FOSSIL_ENABLE_TCL
/*
** SETTING: tcl              boolean default=off
** If enabled Tcl integration commands will be added to the TH1
** interpreter, allowing arbitrary Tcl expressions and
** scripts to be evaluated from TH1.  Additionally, the Tcl
** interpreter will be able to evaluate arbitrary TH1
** expressions and scripts.
*/
/*
** SETTING: tcl-setup        width=40 block-text
** This is the setup script to be evaluated after creating
** and initializing the Tcl interpreter.  By default, this
** is empty and no extra setup is performed.
*/
#endif /* FOSSIL_ENABLE_TCL */
/*
** SETTING: tclsh            width=80 default=tclsh
** Name of the external TCL interpreter used for such things
** as running the GUI diff viewer launched by the --tk option
** of the various "diff" commands.
*/
#ifdef FOSSIL_ENABLE_TH1_DOCS
/*
** SETTING: th1-docs         boolean default=off
** If enabled, this allows embedded documentation files to contain
** arbitrary TH1 scripts that are evaluated on the server.  If native
** Tcl integration is also enabled, this setting has the
** potential to allow anybody with check-in privileges to
** do almost anything that the associated operating system
** user account could do.  Extreme caution should be used
** when enabling this setting.
................................................................................
** SETTING: uv-sync          boolean default=off
** If true, automatically send unversioned files as part
** of a "fossil clone" or "fossil sync" command.  The
** default is false, in which case the -u option is
** needed to clone or sync unversioned files.
*/
/*
** SETTING: web-browser      width=30
** A shell command used to launch your preferred
** web browser when given a URL as an argument.
** Defaults to "start" on windows, "open" on Mac,
** and "firefox" on Unix.
*/

/*
................................................................................
      }
      if( globalFlag && isManifest ){
        fossil_fatal("cannot set 'manifest' globally");
      }
      if( unsetFlag ){
        db_unset(pSetting->name, globalFlag);
      }else{

        db_set(pSetting->name, g.argv[3], globalFlag);

      }
      if( isManifest && g.localOpen ){
        manifest_to_disk(db_lget_int("checkout", 0));
      }
    }else{
      while( pSetting->name ){
        if( exactFlag ){







>







 







>







 







>
>
>
>
>
|







 







>
>
>
|
|
|
|
|
|
|
>







 







>







>







 








>

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










<









<


>







 







>








|


>
>







 







>










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







 







<
<
<







 







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







 







>
>







 







>







 







>
>
>





<
<
<
<
<
<
<
<
<
<
<
<







 







>

|
<
>







 







>

>







 







>







 







>







 







>







 







>







 







>







 







>
>







 







>



>










>







 







>
>












>











<







<







 







>
>









>





>







 







>







 







|







 







<
<
<







 







|







 







|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<













<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|
|
>







 







<

|

|
>
|
|
|

|
|
|
>
>

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

<
<
<
<
<
<
<
<
<
<
<
<







 







|







 







|











|







 







|







 







|




|







 







|







 







|






|



|













|










|







|






|






|







 







|







 







>

>







67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
...
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
...
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
...
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
...
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
...
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
...
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
....
1106
1107
1108
1109
1110
1111
1112



1113
1114
1115
1116
1117
1118
1119
....
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
....
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
....
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
....
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082












2083
2084
2085
2086
2087
2088
2089
....
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130

2131
2132
2133
2134
2135
2136
2137
2138
....
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
....
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
....
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
....
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
....
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
....
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
....
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
....
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
....
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222

3223
3224
3225
3226
3227
3228
3229

3230
3231
3232
3233
3234
3235
3236
....
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
....
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
....
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
....
3430
3431
3432
3433
3434
3435
3436



3437
3438
3439
3440
3441
3442
3443
....
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
....
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
....
3540
3541
3542
3543
3544
3545
3546















3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559


















3560
3561
3562
3563
3564
3565
3566
....
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
....
3665
3666
3667
3668
3669
3670
3671

3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686


3687
3688
3689









3690












3691
3692
3693
3694
3695
3696
3697
....
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
....
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
....
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
....
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
....
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
....
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
....
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
....
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
*/
#define empty_Stmt_m {BLOB_INITIALIZER,NULL, NULL, NULL, 0, 0}
#endif /* INTERFACE */
const struct Stmt empty_Stmt = empty_Stmt_m;

/*
** Call this routine when a database error occurs.
** This routine throws a fatal error.  It does not return.
*/
static void db_err(const char *zFormat, ...){
  va_list ap;
  char *z;
  va_start(ap, zFormat);
  z = vmprintf(zFormat, ap);
  va_end(ap);
................................................................................
}

/*
** All static variable that a used by only this file are gathered into
** the following structure.
*/
static struct DbLocalData {
  unsigned protectMask;     /* Prevent changes to database */
  int nBegin;               /* Nesting depth of BEGIN */
  int doRollback;           /* True to force a rollback */
  int nCommitHook;          /* Number of commit hooks */
  int wrTxn;                /* Outer-most TNX is a write */
  Stmt *pAllStmt;           /* List of all unfinalized statements */
  int nPrepare;             /* Number of calls to sqlite3_prepare_v2() */
  int nDeleteOnFail;        /* Number of entries in azDeleteOnFail[] */
................................................................................
  int nBeforeCommit;        /* Number of entries in azBeforeCommit */
  int nPriorChanges;        /* sqlite3_total_changes() at transaction start */
  const char *zStartFile;   /* File in which transaction was started */
  int iStartLine;           /* Line of zStartFile where transaction started */
  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  void *pAuthArg;           /* Argument to the authorizer */
  const char *zAuthName;    /* Name of the authorizer */
  int bProtectTriggers;     /* True if protection triggers already exist */
  int nProtect;             /* Slots of aProtect used */
  unsigned aProtect[10];    /* Saved values of protectMask */
} db = {
  PROTECT_USER|PROTECT_CONFIG|PROTECT_BASELINE,  /* protectMask */
  0, 0, 0, 0, 0, 0, };

/*
** Arrange for the given file to be deleted on a failure.
*/
void db_delete_on_failure(const char *zFilename){
  assert( db.nDeleteOnFail<count(db.azDeleteOnFail) );
  if( zFilename==0 ) return;
................................................................................
  db.nBegin++;
}
/*
** Begin a new transaction for writing.
*/
void db_begin_write_real(const char *zStartFile, int iStartLine){
  if( db.nBegin==0 ){
    if( !db_is_writeable("repository") ){
      db_multi_exec("BEGIN");
    }else{
      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;
      db.wrTxn = 1;
    }
  }else if( !db.wrTxn ){
    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++;
}
................................................................................
    if( g.fSqlTrace ) fossil_trace("-- ROLLBACK by request\n");
  }
  db.nBegin--;
  if( db.nBegin==0 ){
    int i;
    if( db.doRollback==0 && db.nPriorChanges<sqlite3_total_changes(g.db) ){
      i = 0;
      db_protect_only(PROTECT_SENSITIVE);
      while( db.nBeforeCommit ){
        db.nBeforeCommit--;
        sqlite3_exec(g.db, db.azBeforeCommit[i], 0, 0, 0);
        sqlite3_free(db.azBeforeCommit[i]);
        i++;
      }
      leaf_do_pending_checks();
      db_protect_pop();
    }
    for(i=0; db.doRollback==0 && i<db.nCommitHook; i++){
      int rc = db.aHook[i].xHook();
      if( rc ){
        db.doRollback = 1;
        if( g.fSqlTrace ) fossil_trace("-- ROLLBACK due to aHook[%d]\n", i);
      }
................................................................................
      db.aHook[i].xHook = xS;
    }
  }
  db.aHook[db.nCommitHook].sequence = sequence;
  db.aHook[db.nCommitHook].xHook = x;
  db.nCommitHook++;
}

#if INTERFACE
/*
** Flag bits for db_protect() and db_unprotect() indicating which parts
** of the databases should be write protected or write enabled, respectively.
*/
#define PROTECT_USER       0x01  /* USER table */
#define PROTECT_CONFIG     0x02  /* CONFIG and GLOBAL_CONFIG tables */
#define PROTECT_SENSITIVE  0x04  /* Sensitive and/or global settings */
#define PROTECT_READONLY   0x08  /* everything except TEMP tables */
#define PROTECT_BASELINE   0x10  /* protection system is working */
#define PROTECT_ALL        0x1f  /* All of the above */
#define PROTECT_NONE       0x00  /* Nothing.  Everything is open */
#endif /* INTERFACE */

/*
** Enable or disable database write protections.
**
**    db_protext(X)         Add protects on X
**    db_unprotect(X)       Remove protections on X
**    db_protect_only(X)    Remove all prior protections then set
**                          protections to only X.
**
** Each of these routines pushes the previous protection mask onto
** a finite-size stack.  Each should be followed by a call to
** db_protect_pop() to pop the stack and restore the protections that
** existed prior to the call.  The protection mask stack has a limited
** depth, so take care not to nest calls too deeply.
**
** About Database Write Protection
** -------------------------------
**
** This is *not* a primary means of defending the application from
** attack.  Fossil should be secure even if this mechanism is disabled.
** The purpose of database write protection is to provide an additional
** layer of defense in case SQL injection bugs somehow slip into other
** parts of the system.  In other words, database write protection is
** not primary defense but rather defense in depth.
**
** This mechanism mostly focuses on the USER table, to prevent an
** attacker from giving themselves Admin privilegs, and on the
** CONFIG table and specially "sensitive" settings such as
** "diff-command" or "editor" that if compromised by an attacker
** could lead to an RCE.
**
** By default, the USER and CONFIG tables are read-only.  Various
** subsystems that legitimately need to change those tables can
** temporarily do so using:
**
**     db_unprotect(PROTECT_xxx);
**     // make the legitmate changes here
**     db_protect_pop();
**
** Code that runs inside of reduced protections should be carefully
** reviewed to ensure that it is harmless and not subject to SQL
** injection.
**
** Read-only operations (such as many web pages like /timeline)
** can invoke db_protect(PROTECT_ALL) to effectively make the database
** read-only.  TEMP tables (which are often used for these kinds of
** pages) are still writable, however.
**
** The PROTECT_SENSITIVE protection is a subset of PROTECT_CONFIG
** that blocks changes to all of the global_config table, but only
** "sensitive" settings in the config table.  PROTECT_SENSITIVE
** relies on triggers and the protected_setting() SQL function to
** prevent changes to sensitive settings.
**
** Additional Notes
** ----------------
**
** Calls to routines like db_set() and db_unset() temporarily disable
** the PROTECT_CONFIG protection.  The assumption is that these calls
** cannot be invoked by an SQL injection and are thus safe.  Make sure
** this is the case by always using a string literal as the name argument
** to db_set() and db_unset() and friend, not a variable that might
** be compromised by an attack.
*/
void db_protect_only(unsigned flags){
  if( db.nProtect>=count(db.aProtect)-2 ){
    fossil_panic("too many db_protect() calls");
  }
  db.aProtect[db.nProtect++] = db.protectMask;
  if( (flags & PROTECT_SENSITIVE)!=0 
   && db.bProtectTriggers==0
   && g.repositoryOpen
  ){
    /* Create the triggers needed to protect sensitive settings from
    ** being created or modified the first time that PROTECT_SENSITIVE
    ** is enabled.  Deleting a sensitive setting is harmless, so there
    ** is not trigger to block deletes.  After being created once, the
    ** triggers persist for the life of the database connection. */
    db_multi_exec(
      "CREATE TEMP TRIGGER protect_1 BEFORE INSERT ON config"
      " WHEN protected_setting(new.name) BEGIN"
      "  SELECT raise(abort,'not authorized');"
      "END;\n"
      "CREATE TEMP TRIGGER protect_2 BEFORE UPDATE ON config"
      " WHEN protected_setting(new.name) BEGIN"
      "  SELECT raise(abort,'not authorized');"
      "END;\n"
    );
    db.bProtectTriggers = 1;
  }
  db.protectMask = flags;
}
void db_protect(unsigned flags){
  db_protect_only(db.protectMask | flags);
}
void db_unprotect(unsigned flags){
  if( db.nProtect>=count(db.aProtect)-2 ){
    fossil_panic("too many db_unprotect() calls");
  }
  db.aProtect[db.nProtect++] = db.protectMask;
  db.protectMask &= ~flags;
}
void db_protect_pop(void){
  if( db.nProtect<1 ){
    fossil_panic("too many db_protect_pop() calls");
  }
  db.protectMask = db.aProtect[--db.nProtect];
}

/*
** Verify that the desired database write pertections are in place.
** Throw a fatal error if not.
*/
void db_assert_protected(unsigned flags){
  if( (flags & db.protectMask)!=flags ){
    fossil_panic("missing database write protection bits: %02x",
                 flags & ~db.protectMask);
  }
}

/*
** Assert that either all protections are off (including PROTECT_BASELINE
** which is usually always enabled), or the setting named in the argument
** is no a sensitive setting.
**
** This assert() is used to verify that the db_set() and db_set_int()
** interfaces do not modify a sensitive setting.
*/
void db_assert_protection_off_or_not_sensitive(const char *zName){
  if( db.protectMask!=0 && db_setting_is_protected(zName) ){
    fossil_panic("unauthorized change to protected setting \"%s\"", zName);
  }
}

/*
** Every Fossil database connection automatically registers the following
** overarching authenticator callback, and leaves it registered for the
** duration of the connection.  This authenticator will call any
** sub-authenticators that are registered using db_set_authorizer().
*/
int db_top_authorizer(
  void *pNotUsed,
  int eCode,
  const char *z0,
  const char *z1,
  const char *z2,
  const char *z3
){
  int rc = SQLITE_OK;
  switch( eCode ){
    case SQLITE_INSERT:
    case SQLITE_UPDATE:
    case SQLITE_DELETE: {
      if( (db.protectMask & PROTECT_USER)!=0
          && sqlite3_stricmp(z0,"user")==0 ){
        rc = SQLITE_DENY;
      }else if( (db.protectMask & PROTECT_CONFIG)!=0 &&
               (sqlite3_stricmp(z0,"config")==0 ||
                sqlite3_stricmp(z0,"global_config")==0) ){
        rc = SQLITE_DENY;
      }else if( (db.protectMask & PROTECT_SENSITIVE)!=0 &&
                sqlite3_stricmp(z0,"global_config")==0 ){
        rc = SQLITE_DENY;
      }else if( (db.protectMask & PROTECT_READONLY)!=0
                && sqlite3_stricmp(z2,"temp")!=0 ){
        rc = SQLITE_DENY;
      }
      break;
    }
    case SQLITE_DROP_TEMP_TRIGGER: {
      /* Do not allow the triggers that enforce PROTECT_SENSITIVE
      ** to be dropped */
      rc = SQLITE_DENY;
      break;
    }
  }
  if( db.xAuth && rc==SQLITE_OK ){
    rc = db.xAuth(db.pAuthArg, eCode, z0, z1, z2, z3);
  }
  return rc;
}

/*
** Set or unset the query authorizer callback function
*/
void db_set_authorizer(
  int(*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  void *pArg,
  const char *zName /* for tracing */
){
  if( db.xAuth ){
    fossil_panic("multiple active db_set_authorizer() calls");
  }

  db.xAuth = xAuth;
  db.pAuthArg = pArg;
  db.zAuthName = zName;
  if( g.fSqlTrace ) fossil_trace("-- set authorizer %s\n", zName);
}
void db_clear_authorizer(void){
  if( db.zAuthName && g.fSqlTrace ){
    fossil_trace("-- discontinue authorizer %s\n", db.zAuthName);
  }

  db.xAuth = 0;
  db.pAuthArg = 0;
  db.zAuthName = 0;
}

#if INTERFACE
/*
** Possible flags to db_vprepare
*/
#define DB_PREPARE_IGNORE_ERROR  0x001  /* Suppress errors */
................................................................................
** If the input string contains multiple SQL statements, only the first
** one is processed.  All statements beyond the first are silently ignored.
*/
int db_vprepare(Stmt *pStmt, int flags, const char *zFormat, va_list ap){
  int rc;
  int prepFlags = 0;
  char *zSql;
  const char *zExtra = 0;
  blob_zero(&pStmt->sql);
  blob_vappendf(&pStmt->sql, zFormat, ap);
  va_end(ap);
  zSql = blob_str(&pStmt->sql);
  db.nPrepare++;
  if( flags & DB_PREPARE_PERSISTENT ){
    prepFlags = SQLITE_PREPARE_PERSISTENT;
  }
  rc = sqlite3_prepare_v3(g.db, zSql, -1, prepFlags, &pStmt->pStmt, &zExtra);
  if( rc!=0 && (flags & DB_PREPARE_IGNORE_ERROR)==0 ){
    db_err("%s\n%s", sqlite3_errmsg(g.db), zSql);
  }else if( zExtra && !fossil_all_whitespace(zExtra) ){
    db_err("surplus text follows SQL: \"%s\"", zExtra);
  }
  pStmt->pNext = db.pAllStmt;
  pStmt->pPrev = 0;
  if( db.pAllStmt ) db.pAllStmt->pPrev = pStmt;
  db.pAllStmt = pStmt;
  pStmt->nStep = 0;
  pStmt->rc = rc;
................................................................................
  rc = db_reset(pStmt);
  db_check_result(rc, pStmt);
  return rc;
}

/*
** COMMAND: test-db-exec-error
** Usage: %fossil test-db-exec-error
**
** Invoke the db_exec() interface with an erroneous SQL statement
** in order to verify the error handling logic.
*/
void db_test_db_exec_cmd(void){
  Stmt err;
  db_find_and_open_repository(0,0);
  db_prepare(&err, "INSERT INTO repository.config(name) VALUES(NULL);");
  db_exec(&err);
}

/*
** COMMAND: test-db-prepare
** Usage: %fossil test-db-prepare ?OPTIONS? SQL
**
** Invoke db_prepare() on the SQL input.  Report any errors encountered.
** This command is used to verify error detection logic in the db_prepare()
** utility routine.
*/
void db_test_db_prepare(void){
  Stmt err;
  db_find_and_open_repository(0,0);
  verify_all_options();
  if( g.argc!=3 ) usage("?OPTIONS? SQL");
  db_prepare(&err, "%s", g.argv[2]/*safe-for-%s*/);
  db_finalize(&err);
}

/*
** Print the output of one or more SQL queries on standard output.
** This routine is used for debugging purposes only.
*/
int db_debug(const char *zSql, ...){
  Blob sql;
................................................................................
  sqlite3 *xdb;
  int rc;
  const char *zSql;
  va_list ap;

  xdb = db_open(zFileName ? zFileName : ":memory:");
  sqlite3_exec(xdb, "BEGIN EXCLUSIVE", 0, 0, 0);



  rc = sqlite3_exec(xdb, zSchema, 0, 0, 0);
  if( rc!=SQLITE_OK ){
    db_err("%s", sqlite3_errmsg(xdb));
  }
  va_start(ap, zSchema);
  while( (zSql = va_arg(ap, const char*))!=0 ){
    rc = sqlite3_exec(xdb, zSql, 0, 0, 0);
................................................................................
    sqlite3_result_error_nomem(context);
    return;
  }
  strcpy(zOut, zTemp = obscure((char*)zIn));
  fossil_free(zTemp);
  sqlite3_result_text(context, zOut, strlen(zOut), sqlite3_free);
}

/*
** Return True if zName is a protected (a.k.a. "sensitive") setting.
*/
int db_setting_is_protected(const char *zName){
  const Setting *pSetting = zName ? db_find_setting(zName,0) : 0;
  return pSetting!=0 && pSetting->sensitive!=0;
}

/*
** Implement the protected_setting(X) SQL function.  This function returns
** true if X is the name of a protected (security-sensitive) setting and
** the db.protectSensitive flag is enabled.  It returns false otherwise.
*/
LOCAL void db_protected_setting_func(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zSetting;
  if( (db.protectMask & PROTECT_SENSITIVE)==0 ){
    sqlite3_result_int(context, 0);
    return;
  }
  zSetting = (const char*)sqlite3_value_text(argv[0]);
  sqlite3_result_int(context, db_setting_is_protected(zSetting));
}

/*
** Register the SQL functions that are useful both to the internal
** representation and to the "fossil sql" command.
*/
void db_add_aux_functions(sqlite3 *db){
  sqlite3_create_function(db, "checkin_mtime", 2, SQLITE_UTF8, 0,
................................................................................
                          capability_fullcap, 0, 0);
  sqlite3_create_function(db, "find_emailaddr", 1, SQLITE_UTF8, 0,
                          alert_find_emailaddr_func, 0, 0);
  sqlite3_create_function(db, "display_name", 1, SQLITE_UTF8, 0,
                          alert_display_name_func, 0, 0);
  sqlite3_create_function(db, "obscure", 1, SQLITE_UTF8, 0,
                          db_obscure, 0, 0);
  sqlite3_create_function(db, "protected_setting", 1, SQLITE_UTF8, 0,
                          db_protected_setting_func, 0, 0);
}

#if USE_SEE
/*
** This is a pointer to the saved database encryption key string.
*/
static char *zSavedKey = 0;
................................................................................
    db, "if_selected", 3, SQLITE_UTF8, 0, file_is_selected,0,0
  );
  if( g.fSqlTrace ) sqlite3_trace_v2(db, SQLITE_TRACE_PROFILE, db_sql_trace, 0);
  db_add_aux_functions(db);
  re_add_sql_func(db);  /* The REGEXP operator */
  foci_register(db);    /* The "files_of_checkin" virtual table */
  sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_FKEY, 0, &rc);
  sqlite3_set_authorizer(db, db_top_authorizer, db);
  return db;
}


/*
** Detaches the zLabel database.
*/
................................................................................
  assert( g.zLocalRoot );
  if( zRepo==0 ){
    zRepo = db_lget("repository", 0);
    if( zRepo && !file_is_absolute_path(zRepo) ){
      char * zFree = zRepo;
      zRepo = mprintf("%s%s", g.zLocalRoot, zRepo);
      fossil_free(zFree);
      zFree = zRepo;
      zRepo = file_canonical_name_dup(zFree);
      fossil_free(zFree);
    }
  }
  return zRepo;
}













/*
** Returns non-zero if support for symlinks is currently enabled.
*/
int db_allow_symlinks(void){
  return g.allowSymlinks;
}

................................................................................
    }
  }
  g.zRepositoryName = mprintf("%s", zDbName);
  db_open_or_attach(g.zRepositoryName, "repository");
  g.repositoryOpen = 1;
  sqlite3_file_control(g.db, "repository", SQLITE_FCNTL_DATA_VERSION,
                       &g.iRepoDataVers);

  /* Cache "allow-symlinks" option, because we'll need it on every stat call */
  g.allowSymlinks = db_get_boolean("allow-symlinks",0);


  g.zAuxSchema = db_get("aux-schema","");
  g.eHashPolicy = db_get_int("hash-policy",-1);
  if( g.eHashPolicy<0 ){
    g.eHashPolicy = hname_default_policy();
    db_set_int("hash-policy", g.eHashPolicy, 0);
  }

................................................................................
  /* If the localdb has a lot of unused free space,
  ** then VACUUM it as we shut down.
  */
  if( db_database_slot("localdb")>=0 ){
    int nFree = db_int(0, "PRAGMA localdb.freelist_count");
    int nTotal = db_int(0, "PRAGMA localdb.page_count");
    if( nFree>nTotal/4 ){
      db_unprotect(PROTECT_ALL);
      db_multi_exec("VACUUM localdb;");
      db_protect_pop();
    }
  }

  if( g.db ){
    int rc;
    sqlite3_wal_checkpoint(g.db, 0);
    rc = sqlite3_close(g.db);
................................................................................
        fossil_warning("unfinalized SQL statement: [%s]", sqlite3_sql(pStmt));
      }
    }
    g.db = 0;
  }
  g.repositoryOpen = 0;
  g.localOpen = 0;
  db.bProtectTriggers = 0;
  assert( g.dbConfig==0 );
  assert( g.zConfigDbName==0 );
  backoffice_run_if_needed();
}

/*
** Close the database as quickly as possible without unnecessary processing.
................................................................................
  }
  if( zUser==0 ){
    zUser = fossil_getenv("USERNAME");
  }
  if( zUser==0 ){
    zUser = "root";
  }
  db_unprotect(PROTECT_USER);
  db_multi_exec(
     "INSERT OR IGNORE INTO user(login, info) VALUES(%Q,'')", zUser
  );
  db_multi_exec(
     "UPDATE user SET cap='s', pw=%Q"
     " WHERE login=%Q", fossil_random_password(10), zUser
  );
................................................................................
       "   VALUES('nobody','','gjorz','Nobody');"
       "INSERT OR IGNORE INTO user(login,pw,cap,info)"
       "   VALUES('developer','','ei','Dev');"
       "INSERT OR IGNORE INTO user(login,pw,cap,info)"
       "   VALUES('reader','','kptw','Reader');"
    );
  }
  db_protect_pop();
}

/*
** Return a pointer to a string that contains the RHS of an IN operator
** that will select CONFIG table names that are in the list of control
** settings.
*/
................................................................................
  const char *zInitialDate,    /* Initial date of repository. (ex: "now") */
  const char *zDefaultUser     /* Default user for the repository */
){
  char *zDate;
  Blob hash;
  Blob manifest;

  db_unprotect(PROTECT_ALL);
  db_set("content-schema", CONTENT_SCHEMA, 0);
  db_set("aux-schema", AUX_SCHEMA_MAX, 0);
  db_set("rebuilt", get_version(), 0);
  db_set("admin-log", "1", 0);
  db_set("access-log", "1", 0);
  db_multi_exec(
      "INSERT INTO config(name,value,mtime)"
................................................................................
      "  mtime = (SELECT u2.mtime FROM settingSrc.user u2"
      "           WHERE u2.login = user.login),"
      "  photo = (SELECT u2.photo FROM settingSrc.user u2"
      "           WHERE u2.login = user.login)"
      " WHERE user.login IN ('anonymous','nobody','developer','reader');"
    );
  }
  db_protect_pop();

  if( zInitialDate ){
    int rid;
    blob_zero(&manifest);
    blob_appendf(&manifest, "C initial\\sempty\\scheck-in\n");
    zDate = date_in_standard_format(zInitialDate);
    blob_appendf(&manifest, "D %s\n", zDate);
................................................................................
    z = fossil_strdup(zDefault);
  }else if( zFormat!=0 ){
    z = db_text(0, "SELECT strftime(%Q,%Q,'unixepoch');", zFormat, z);
  }
  return z;
}
void db_set(const char *zName, const char *zValue, int globalFlag){
  db_assert_protection_off_or_not_sensitive(zName);
  db_unprotect(PROTECT_CONFIG);
  db_begin_transaction();
  if( globalFlag ){
    db_swap_connections();
    db_multi_exec("REPLACE INTO global_config(name,value) VALUES(%Q,%Q)",
                   zName, zValue);
    db_swap_connections();
  }else{
................................................................................
    db_multi_exec("REPLACE INTO config(name,value,mtime) VALUES(%Q,%Q,now())",
                   zName, zValue);
  }
  if( globalFlag && g.repositoryOpen ){
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }
  db_end_transaction(0);
  db_protect_pop();
}
void db_unset(const char *zName, int globalFlag){
  db_begin_transaction();
  db_unprotect(PROTECT_CONFIG);
  if( globalFlag ){
    db_swap_connections();
    db_multi_exec("DELETE FROM global_config WHERE name=%Q", zName);
    db_swap_connections();
  }else{
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }
  if( globalFlag && g.repositoryOpen ){
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }
  db_protect_pop();
  db_end_transaction(0);
}
int db_is_global(const char *zName){
  int rc = 0;
  if( g.zConfigDbName ){
    db_swap_connections();
    rc = db_exists("SELECT 1 FROM global_config WHERE name=%Q", zName);
................................................................................
    db_swap_connections();
    v = db_int(dflt, "SELECT value FROM global_config WHERE name=%Q", zName);
    db_swap_connections();
  }
  return v;
}
void db_set_int(const char *zName, int value, int globalFlag){
  db_assert_protection_off_or_not_sensitive(zName);
  db_unprotect(PROTECT_CONFIG);
  if( globalFlag ){
    db_swap_connections();
    db_multi_exec("REPLACE INTO global_config(name,value) VALUES(%Q,%d)",
                  zName, value);
    db_swap_connections();
  }else{
    db_multi_exec("REPLACE INTO config(name,value,mtime) VALUES(%Q,%d,now())",
                  zName, value);
  }
  if( globalFlag && g.repositoryOpen ){
    db_multi_exec("DELETE FROM config WHERE name=%Q", zName);
  }
  db_protect_pop();
}
int db_get_boolean(const char *zName, int dflt){
  char *zVal = db_get(zName, dflt ? "on" : "off");
  if( is_truth(zVal) ){
    dflt = 1;
  }else if( is_false(zVal) ){
    dflt = 0;
  }
  fossil_free(zVal);
  return dflt;
}

int db_get_versioned_boolean(const char *zName, int dflt){
  char *zVal = db_get_versioned(zName, 0);
  if( zVal==0 ) return dflt;
  if( is_truth(zVal) ) return 1;
  if( is_false(zVal) ) return 0;
  return dflt;
}

char *db_lget(const char *zName, const char *zDefault){
  return db_text(zDefault,
                 "SELECT value FROM vvar WHERE name=%Q", zName);
}
void db_lset(const char *zName, const char *zValue){
  db_multi_exec("REPLACE INTO vvar(name,value) VALUES(%Q,%Q)", zName, zValue);
}
................................................................................
    if( !g.localOpen ) return;
    zName = db_repository_filename();
  }
  file_canonical_name(zName, &full, 0);
  (void)filename_collation();  /* Initialize before connection swap */
  db_swap_connections();
  zRepoSetting = mprintf("repo:%q", blob_str(&full));
  
  db_unprotect(PROTECT_CONFIG);
  db_multi_exec(
     "DELETE FROM global_config WHERE name %s = %Q;",
     filename_collation(), zRepoSetting
  );
  db_multi_exec(
     "INSERT OR IGNORE INTO global_config(name,value)"
     "VALUES(%Q,1);",
     zRepoSetting
  );
  db_protect_pop();
  fossil_free(zRepoSetting);
  if( g.localOpen && g.zLocalRoot && g.zLocalRoot[0] ){
    Blob localRoot;
    file_canonical_name(g.zLocalRoot, &localRoot, 1);
    zCkoutSetting = mprintf("ckout:%q", blob_str(&localRoot));
    db_unprotect(PROTECT_CONFIG);
    db_multi_exec(
       "DELETE FROM global_config WHERE name %s = %Q;",
       filename_collation(), zCkoutSetting
    );
    db_multi_exec(
      "REPLACE INTO global_config(name, value)"
      "VALUES(%Q,%Q);",
................................................................................
        filename_collation(), zCkoutSetting
    );
    db_optional_sql("repository",
        "REPLACE INTO config(name,value,mtime)"
        "VALUES(%Q,1,now());",
        zCkoutSetting
    );
    db_protect_pop();
    fossil_free(zCkoutSetting);
    blob_reset(&localRoot);
  }else{
    db_swap_connections();
  }
  blob_reset(&full);
}
................................................................................
** "new-name" term means that the cloned repository will be called
** "new-name.fossil".
**
** Options:
**   --empty           Initialize checkout as being empty, but still connected
**                     with the local repository. If you commit this checkout,
**                     it will become a new "initial" commit in the repository.
**   -f|--force        Continue with the open even if the working directory is
**                     not empty.
**   --force-missing   Force opening a repository with missing content
**   --keep            Only modify the manifest and manifest.uuid files
**   --nested          Allow opening a repository inside an opened checkout
**   --repodir DIR     If REPOSITORY is a URI that will be cloned, store
**                     the clone in DIR rather than in "."
**   --setmtime        Set timestamps of all files to match their SCM-side
................................................................................
** See also: [[close]], [[clone]]
*/
void cmd_open(void){
  int emptyFlag;
  int keepFlag;
  int forceMissingFlag;
  int allowNested;



  int setmtimeFlag;              /* --setmtime.  Set mtimes on files */
  int bForce = 0;                /* --force.  Open even if non-empty dir */
  static char *azNewArgv[] = { 0, "checkout", "--prompt", 0, 0, 0, 0 };
  const char *zWorkDir;          /* --workdir value */
  const char *zRepo = 0;         /* Name of the repository file */
  const char *zRepoDir = 0;      /* --repodir value */
  char *zPwd;                    /* Initial working directory */
................................................................................
  emptyFlag = find_option("empty",0,0)!=0;
  keepFlag = find_option("keep",0,0)!=0;
  forceMissingFlag = find_option("force-missing",0,0)!=0;
  allowNested = find_option("nested",0,0)!=0;
  setmtimeFlag = find_option("setmtime",0,0)!=0;
  zWorkDir = find_option("workdir",0,1);
  zRepoDir = find_option("repodir",0,1);
  bForce = find_option("force","f",0)!=0;  
  zPwd = file_getcwd(0,0);
  

  /* We should be done with options.. */
  verify_all_options();

  if( g.argc!=3 && g.argc!=4 ){
................................................................................
    }
    if( file_chdir(zWorkDir, 0) ){
      fossil_fatal("unable to make %s the working directory", zWorkDir);
    }
  }
  if( keepFlag==0 && bForce==0 && file_directory_size(".", 0, 1)>0 ){
    fossil_fatal("directory %s is not empty\n"
                 "use the -f or --force option to override", file_getcwd(0,0));
  }

  if( db_open_local_v2(0, allowNested) ){
    fossil_fatal("there is already an open tree at %s", g.zLocalRoot);
  }

  /* If REPOSITORY looks like a URI, then try to clone it first */
................................................................................
    if( g.argc==4 ){
      g.zOpenRevision = g.argv[3];
    }else if( db_exists("SELECT 1 FROM event WHERE type='ci'") ){
      g.zOpenRevision = db_get("main-branch", 0);
    }
  }

















#if defined(_WIN32) || defined(__CYGWIN__)
# define LOCALDB_NAME "./_FOSSIL_"
#else
# define LOCALDB_NAME "./.fslckout"
#endif
  db_init_database(LOCALDB_NAME, zLocalSchema, zLocalSchemaVmerge,
#ifdef FOSSIL_LOCAL_WAL
                   "COMMIT; PRAGMA journal_mode=WAL; BEGIN;",
#endif
                   (char*)0);
  db_delete_on_failure(LOCALDB_NAME);
  db_open_local(0);


















  db_lset("repository", zRepo);
  db_record_repository_filename(zRepo);
  db_set_checkout(0);
  azNewArgv[0] = g.argv[0];
  g.argv = azNewArgv;
  if( !emptyFlag ){
    g.argc = 3;
................................................................................
*/
struct Setting {
  const char *name;     /* Name of the setting */
  const char *var;      /* Internal variable name used by db_set() */
  int width;            /* Width of display.  0 for boolean values and
                        ** negative for values which should not appear
                        ** on the /setup_settings page. */
  char versionable;     /* Is this setting versionable? */
  char forceTextArea;   /* Force using a text area for display? */
  char sensitive;       /* True if this a security-sensitive setting */
  const char *def;      /* Default value */
};
#endif /* INTERFACE */

/*
** SETTING: access-log      boolean default=off
**
................................................................................
*/
/*
** SETTING: admin-log       boolean default=off
**
** When the admin-log setting is enabled, configuration changes are recorded
** in the "admin_log" table of the repository.
*/

/*
** SETTING: allow-symlinks  boolean default=off sensitive
**
** When allow-symlinks is OFF, Fossil does not see symbolic links 
** (a.k.a "symlinks") on disk as a separate class of object.  Instead Fossil
** sees the object that the symlink points to.  Fossil will only manage files
** and directories, not symlinks.  When a symlink is added to a repository,
** the object that the symlink points to is added, not the symlink itself.
**
** When allow-symlinks is ON, Fossil sees symlinks on disk as a separate
** object class that is distinct from files and directories.  When a symlink
** is added to a repository, Fossil stores the target filename. In other
** words, Fossil stores the symlink itself, not the object that the symlink
** points to.
**


** Symlinks are not cross-platform. They are not available on all
** operating systems and file systems. Hence the allow-symlinks setting is
** OFF by default, for portability.









*/












/*
** SETTING: auto-captcha    boolean default=on variable=autocaptcha
** If enabled, the /login page provides a button that will automatically
** fill in the captcha password.  This makes things easier for human users,
** at the expense of also making logins easier for malicious robots.
*/
/*
................................................................................
** Backoffice processing does things such as delivering
** email notifications.  So if this setting is true, and if
** there is no cron job periodically running "fossil backoffice",
** email notifications and other work normally done by the
** backoffice will not occur.
*/
/*
** SETTING: backoffice-logfile width=40 sensitive
** If backoffice-logfile is not an empty string and is a valid
** filename, then a one-line message is appended to that file
** every time the backoffice runs.  This can be used for debugging,
** to ensure that backoffice is running appropriately.
*/
/*
** SETTING: binary-glob     width=40 versionable block-text
................................................................................
** The crnl-glob setting is a compatibility alias.
*/
/*
** SETTING: crnl-glob       width=40 versionable block-text
** This is an alias for the crlf-glob setting.
*/
/*
** SETTING: default-perms   width=16 default=u sensitive
** Permissions given automatically to new users.  For more
** information on permissions see the Users page in Server
** Administration of the HTTP UI.
*/
/*
** SETTING: diff-binary     boolean default=on
** If enabled, permit files that may be binary
** or that match the "binary-glob" setting to be used with
** external diff programs.  If disabled, skip these files.
*/
/*
** SETTING: diff-command    width=40 sensitive
** The value is an external command to run when performing a diff.
** If undefined, the internal text diff will be used.
*/
/*
** SETTING: dont-push       boolean default=off
** If enabled, prevent this repository from pushing from client to
** server.  This can be used as an extra precaution to prevent
................................................................................
** accidental pushes to a public server from a private clone.
*/
/*
** SETTING: dotfiles        boolean versionable default=off
** If enabled, include --dotfiles option for all compatible commands.
*/
/*
** SETTING: editor          width=32 sensitive
** The value is an external command that will launch the
** text editor command used for check-in comments.
*/
/*
** SETTING: empty-dirs      width=40 versionable block-text
** The value is a comma or newline-separated list of pathnames. On
** update and checkout commands, if no file or directory
................................................................................
** A comma- or newline-separated list of globs of filenames
** which are allowed to be edited using the /fileedit page.
** An empty list prohibits editing via that page. Note that
** it cannot edit binary files, so the list should not
** contain any globs for, e.g., images or PDFs.
*/
/*
** SETTING: gdiff-command    width=40 default=gdiff sensitive
** The value is an external command to run when performing a graphical
** diff. If undefined, text diff will be used.
*/
/*
** SETTING: gmerge-command   width=40 sensitive
** The value is a graphical merge conflict resolver command operating
** on four files.  Examples:
**
**     kdiff3 "%baseline" "%original" "%merge" -o "%output"
**     xxdiff "%original" "%baseline" "%merge" -M "%output"
**     meld "%baseline" "%original" "%merge" "%output"
*/
................................................................................
** SETTING: mv-rm-files      boolean default=off
** If enabled, the "mv" and "rename" commands will also move
** the associated files within the checkout -AND- the "rm"
** and "delete" commands will also remove the associated
** files from within the checkout.
*/
/*
** SETTING: pgp-command      width=40 sensitive
** Command used to clear-sign manifests at check-in.
** Default value is "gpg --clearsign -o"
*/
/*
** SETTING: forbid-delta-manifests    boolean default=off
** If enabled on a client, new delta manifests are prohibited on
** commits.  If enabled on a server, whenever a client attempts
................................................................................
** have a non-zero "repolist-skin" setting then the repository list is
** displayed using unadorned HTML ("skinless").
**
** If repolist-skin has a value of 2, then the repository is omitted from
** the list in use cases 1 through 4, but not for 5 and 6.
*/
/*
** SETTING: self-register    boolean default=off sensitive
** Allow users to register themselves through the HTTP UI.
** This is useful if you want to see other names than
** "Anonymous" in e.g. ticketing system. On the other hand
** users can not be deleted.
*/
/*
** SETTING: ssh-command      width=40 sensitive
** The command used to talk to a remote machine with  the "ssh://" protocol.
*/
/*
** SETTING: ssl-ca-location  width=40 sensitive
** The full pathname to a file containing PEM encoded
** CA root certificates, or a directory of certificates
** with filenames formed from the certificate hashes as
** required by OpenSSL.
**
** If set, this will override the OS default list of
** OpenSSL CAs. If unset, the default list will be used.
** Some platforms may add additional certificates.
** Checking your platform behaviour is required if the
** exact contents of the CA root is critical for your
** application.
*/
/*
** SETTING: ssl-identity     width=40 sensitive
** The full pathname to a file containing a certificate
** and private key in PEM format. Create by concatenating
** the certificate and private key files.
**
** This identity will be presented to SSL servers to
** authenticate this client, in addition to the normal
** password authentication.
*/
#ifdef FOSSIL_ENABLE_TCL
/*
** SETTING: tcl              boolean default=off sensitive
** If enabled Tcl integration commands will be added to the TH1
** interpreter, allowing arbitrary Tcl expressions and
** scripts to be evaluated from TH1.  Additionally, the Tcl
** interpreter will be able to evaluate arbitrary TH1
** expressions and scripts.
*/
/*
** SETTING: tcl-setup        width=40 block-text sensitive
** This is the setup script to be evaluated after creating
** and initializing the Tcl interpreter.  By default, this
** is empty and no extra setup is performed.
*/
#endif /* FOSSIL_ENABLE_TCL */
/*
** SETTING: tclsh            width=80 default=tclsh sensitive
** Name of the external TCL interpreter used for such things
** as running the GUI diff viewer launched by the --tk option
** of the various "diff" commands.
*/
#ifdef FOSSIL_ENABLE_TH1_DOCS
/*
** SETTING: th1-docs         boolean default=off sensitive
** If enabled, this allows embedded documentation files to contain
** arbitrary TH1 scripts that are evaluated on the server.  If native
** Tcl integration is also enabled, this setting has the
** potential to allow anybody with check-in privileges to
** do almost anything that the associated operating system
** user account could do.  Extreme caution should be used
** when enabling this setting.
................................................................................
** SETTING: uv-sync          boolean default=off
** If true, automatically send unversioned files as part
** of a "fossil clone" or "fossil sync" command.  The
** default is false, in which case the -u option is
** needed to clone or sync unversioned files.
*/
/*
** SETTING: web-browser      width=30 sensitive
** A shell command used to launch your preferred
** web browser when given a URL as an argument.
** Defaults to "start" on windows, "open" on Mac,
** and "firefox" on Unix.
*/

/*
................................................................................
      }
      if( globalFlag && isManifest ){
        fossil_fatal("cannot set 'manifest' globally");
      }
      if( unsetFlag ){
        db_unset(pSetting->name, globalFlag);
      }else{
        db_protect_only(PROTECT_NONE);
        db_set(pSetting->name, g.argv[3], globalFlag);
        db_protect_pop();
      }
      if( isManifest && g.localOpen ){
        manifest_to_disk(db_lget_int("checkout", 0));
      }
    }else{
      while( pSetting->name ){
        if( exactFlag ){

Changes to src/default.css.

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
...
907
908
909
910
911
912
913




914
915
916
917
918
919
920
...
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
...
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
....
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
....
1145
1146
1147
1148
1149
1150
1151




1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162





















































































































































































































































































































}
span.usertype:before {
  content:"'";
}
span.usertype:after {
  content:"'";
}
div.selectedText {
  font-weight: bold;
  color: blue;
  background-color: #d5d5ff;
  border: 1px blue solid;
}
p.missingPriv {
 color: blue;
}
span.wikiruleHead {
  font-weight: bold;
}
td.tktDspLabel {
................................................................................
d='M4,5h4v1h-4zm0,2h4v1h-4z'/%3E%3Cpath style='fill:rgb(64,64,64)' \
d='M5,3h5l3,3v7h-8z'/%3E%3Cpath style='fill:rgb(248,248,248)' \
d='M10,4.4v1.6h1.6zm-4,-0.6h3v3h-3zm0,3h6v5.4h-6z'/%3E%3Cpath style='fill:rgb(80,128,208)' \
d='M7,8h4v1h-4zm0,2h4v1h-4z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  cursor: pointer;




}
.copy-button-flipped {
/*Note: .16em is suitable for element grouping.*/
  margin-left: .16em;
  margin-right: 0;
}
.nobr {
................................................................................
  transition: max-height 0.25s ease-out;
}
.error {
  color: darkred;
  background: yellow;
}
.warning {
  color: darkred;
  background: yellow;
  opacity: 0.7;
}
.hidden {





  position: absolute;
  opacity: 0;
  pointer-events: none;
  display: none;
}
input {
  max-width: 95%;
}
textarea {
  max-width: 95%;
}
img {
  max-width: 100%;
  height: auto;
}
hr {
  /* Needed to keep /dir README.txt from floating right in some skins */
  clear: both;
}

/**
................................................................................
  margin: 0;
  display: flex;
  flex-direction: column;
  border-width: 1px;
  border-style: outset;
  border-color: inherit;
}
.tab-container > .tabs > .tab-panel,
.tab-container > .tabs > fieldset.tab-wrapper {
  align-self: stretch;
  flex: 10 1 auto;
  display: flex;
  flex-direction: row;
  border: 0;
  padding: 0;
  margin: 0;
}
.tab-container > .tabs > fieldset.tab-wrapper > .tab-panel{
  align-self: stretch;
  flex: 10 1 auto;
  display: block;
  border: 0;
  padding: 0;
  margin: 0;
}
................................................................................
  font-size: 175%;
}
.font-size-200 {
  font-size: 200%;
}

/**
   .input-with-label is intended to be a wrapper element which
   contain both a LABEL tag and an INPUT or SELECT control.
   The wrapper is "necessary", as opposed to placing the INPUT
   in the LABEL, so that we can include multiple INPUT
   elements (e.g. a set of radio buttons).

*/
.input-with-label {
  border: 1px inset #808080;
  border-radius: 0.25em;
  padding: 0.25em 0.4em;
  margin: 0 0.5em;
  display: inline-block;
  cursor: default;

}
.input-with-label > * {
  vertical-align: middle;
}
.input-with-label > label {
  display: inline; /* some skins set label display to block! */

}
.input-with-label > input {
  margin: 0;
}
.input-with-label > button {
  margin: 0;
}
................................................................................
}
.input-with-label > input[type=text] {
  margin: 0;
}
.input-with-label > textarea {
  margin: 0;
}




.input-with-label > input[type=checkbox] {
  vertical-align: sub;
}
.input-with-label > input[type=radio] {
  vertical-align: sub;
}
.input-with-label > label {
  font-weight: initial;
  margin: 0 0.25em 0 0.25em;
  vertical-align: middle;
}




























































































































































































































































































































<
<
<
<
<
<







 







>
>
>
>







 







|

<


>
>
>
>
>
|
|
|
|









<







 







|
<
<
<
<
<
<
<
<
<
<







 







|
|
|
|
|
>


|

|



>






>







 







>
>
>
>

|


|






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
438
439
440
441
442
443
444






445
446
447
448
449
450
451
...
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
...
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
...
993
994
995
996
997
998
999
1000










1001
1002
1003
1004
1005
1006
1007
....
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
....
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
}
span.usertype:before {
  content:"'";
}
span.usertype:after {
  content:"'";
}






p.missingPriv {
 color: blue;
}
span.wikiruleHead {
  font-weight: bold;
}
td.tktDspLabel {
................................................................................
d='M4,5h4v1h-4zm0,2h4v1h-4z'/%3E%3Cpath style='fill:rgb(64,64,64)' \
d='M5,3h5l3,3v7h-8z'/%3E%3Cpath style='fill:rgb(248,248,248)' \
d='M10,4.4v1.6h1.6zm-4,-0.6h3v3h-3zm0,3h6v5.4h-6z'/%3E%3Cpath style='fill:rgb(80,128,208)' \
d='M7,8h4v1h-4zm0,2h4v1h-4z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  cursor: pointer;
}
.copy-button.disabled {
  filter: grayscale(1);
  opacity: 0.4;
}
.copy-button-flipped {
/*Note: .16em is suitable for element grouping.*/
  margin-left: .16em;
  margin-right: 0;
}
.nobr {
................................................................................
  transition: max-height 0.25s ease-out;
}
.error {
  color: darkred;
  background: yellow;
}
.warning {
  color: black;
  background: yellow;

}
.hidden {
  /* The framework-wide way of hiding elements is to assign them this
     CSS class. To make them visible again, remove it. The !important
     qualifiers are unfortunate but sometimes necessary when hidden
     element has other classes which specify visibility-related
     options. */
  position: absolute !important;
  opacity: 0 !important;
  pointer-events: none !important;
  display: none !important;
}
input {
  max-width: 95%;
}
textarea {
  max-width: 95%;
}
img {
  max-width: 100%;

}
hr {
  /* Needed to keep /dir README.txt from floating right in some skins */
  clear: both;
}

/**
................................................................................
  margin: 0;
  display: flex;
  flex-direction: column;
  border-width: 1px;
  border-style: outset;
  border-color: inherit;
}
.tab-container > .tabs > .tab-panel {










  align-self: stretch;
  flex: 10 1 auto;
  display: block;
  border: 0;
  padding: 0;
  margin: 0;
}
................................................................................
  font-size: 175%;
}
.font-size-200 {
  font-size: 200%;
}

/**
   .input-with-label is intended to be a wrapper element which contain
   both a LABEL tag and an INPUT or SELECT control.  The wrapper is
   "necessary", as opposed to placing the INPUT in the LABEL, so that
   we can include multiple INPUT elements (e.g. a set of radio
   buttons). Note that these elements must sometimes be BLOCK elements
   (e.g. DIV) so that certain nesting constructs are legal.
*/
.input-with-label {
  border: 1px inset rgba(128, 128, 128, 0.5);
  border-radius: 0.25em;
  padding: 0.1em;
  margin: 0 0.5em;
  display: inline-block;
  cursor: default;
  white-space: nowrap;
}
.input-with-label > * {
  vertical-align: middle;
}
.input-with-label > label {
  display: inline; /* some skins set label display to block! */
  cursor: pointer;
}
.input-with-label > input {
  margin: 0;
}
.input-with-label > button {
  margin: 0;
}
................................................................................
}
.input-with-label > input[type=text] {
  margin: 0;
}
.input-with-label > textarea {
  margin: 0;
}
/* Browsers are unfortunately inconsistent in how they
   align checkboxes and radio buttons, even if they're
   given the same vertical-align value. 'middle' seems to
   be the least bad option, rather than the ideal. */
.input-with-label > input[type=checkbox] {
  vertical-align: middle;
}
.input-with-label > input[type=radio] {
  vertical-align: middle;
}
.input-with-label > label {
  font-weight: initial;
  margin: 0 0.25em 0 0.25em;
  vertical-align: middle;
}

table.numbered-lines {
  width: 100%;
  table-layout: fixed /* required to keep ultra-wide code from exceeding
                         window width, and instead force a scrollbar
                         on them. */;
}
table.numbered-lines > tbody > tr {
  font-family: monospace;
  line-height: 1.35;
  white-space: pre;
}
table.numbered-lines > tbody > tr > td {
  font-family: inherit;
  font-size: inherit;
  line-height: inherit;
  white-space: inherit;
  margin: 0;
  vertical-align: top;
  padding: 0.25em 0 0 0 /*prevents slight overlap at top */;
}
table.numbered-lines td.line-numbers {
  width: 4.5em;
}
table.numbered-lines td.line-numbers > span:first-of-type {
  margin-top: 0.25em/*must match top PADDING of
                      td.file-content > pre > code*/;
}
table.numbered-lines td.line-numbers > span {
  display: block;
  margin: 0;
  padding: 0;
  line-height: inherit;
  font-size: inherit;
  font-family: inherit;
  cursor: pointer;
  white-space: pre;
  margin-right: 2px/*keep selection from nudging the right column */;
  text-align: right;
}
table.numbered-lines td.line-numbers > span:hover {
  background-color: rgba(112, 112, 112, 0.25);
}
table.numbered-lines td.file-content {
  padding-left: 0.25em;
}
table.numbered-lines td.file-content > pre,
table.numbered-lines td.file-content > pre > code {
  margin: 0;
  padding: 0;
  line-height: inherit;
  font-size: inherit;
  font-family: inherit;
  white-space: pre;
  display: block/*necessary for certain skins!*/;
}
table.numbered-lines td.file-content > pre {
}
table.numbered-lines td.file-content > pre > code {
  overflow: auto;
  padding-left: 0.5em;
  padding-right: 0.5em;
  padding-top: 0.25em/*any top padding here must match the top MARGIN of
                       td.line-numbers's first span child or the
                       lines/code will get misaligned. */;
  padding-bottom: 0.25em/*prevents a slight overlap at bottom from
                          triggering a scroller*/;
}
table.numbered-lines td.file-content > pre > code > * {
  /* Defense against syntax highlighters indirectly messing up these
     properties... */
  line-height: inherit;
  font-size: inherit;
  font-family: inherit;
}
table.numbered-lines td.line-numbers span.selected-line/*replacement*/ {
  font-weight: bold;
  color: blue;
  background-color: #d5d5ff;
  border: 1px blue solid;
  border-top-width: 0;
  border-bottom-width: 0;
  padding: 0;
  margin: 0;
}
table.numbered-lines td.line-numbers span.selected-line.start {
  border-top-width: 1px;
  margin-top: -1px/*restore alignment*/;
}
table.numbered-lines td.line-numbers span.selected-line.end {
  border-bottom-width: 1px;
  margin-top: -1px/*restore alignment*/;
}
table.numbered-lines td.line-numbers span.selected-line.start.end {
  margin-top: -2px/*restore alignment*/;
}

.fossil-tooltip {
  text-align: center;
  padding: 0.2em 1em;
  border: 1px solid black;
  border-radius: 0.25em;
  position: absolute;
  display: inline-block;
  z-index: 19/*below default skin's hamburger popup*/;
  box-shadow: -0.15em 0.15em 0.2em rgba(0, 0, 0, 0.75);
  background-color: inherit;
  color: inherit;
}

.fossil-toast-message {
  /* "toast"-style popup message.
     See fossil.popupwidget:toast() */
  position: absolute;
  display: block;
  z-index: 101;
  text-align: left;
  padding: 0.15em 0.5em;
  margin: 0;
  font-size: 1em;
  border-width: 1px;
  border-style: solid;
  border-color: rgba( 127, 127, 127, 0.75 );
  border-radius: 0.25em;
  background-color: rgba(20, 20, 20, 1)
  /* problem: if we inherit the color it may either be
     transparent or inherit translucency via the
     skin, leaving it unreadable. Since we set the bg
     color we must also set the fg color. */;
  color: rgba(235, 235, 235, 0.9);
}
.fossil-toast-message.error,
.fossil-toast-message.warning {
  background: yellow;
}
.fossil-toast-message.error {
  font-weight: bold;
  color: darkred;
  border-color: darkred;
}
.fossil-toast-message.warning {
  color: black;
}

blockquote.file-content {
  /* file content block in the /file page */
  margin: 0 1em;
}


/**
   Circular "help" buttons intended to be placed to the right of
   another element and hold text text for it. These typically get
   initialized automatically at page startup via
   fossil.popupwidget.js, and can be manually initialized/created
   using window.fossil.helpButtonlets.setup/create(). All of their
   child content (plain text and/or DOM elements) gets moved out of
   the DOM and shown in a singleton popup when they are clicked. They
   may be SPAN elements if their children are all inline elements,
   otherwise they must be DIVs (block elements) so that nesting of
   block-element content is legal.
*/
.help-buttonlet {
  display: inline-block;
  min-width: 1em;
  max-width: 1em;
  min-height: 1em;
  max-height: 1em;
  cursor: pointer;
  margin: 0 0 0 0.35em;
  background-image: /* white question mark on blue circular background */
    url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' \
viewBox='0 0 15.867574 15.867574'%3e%3ccircle cx='7.9337869' cy='7.9337869' r='7.9337869' \
style='fill:%23f0f0f0;stroke-width:1' /%3e%3ccircle cx='7.9337869' cy='7.9337869' \
r='6.9662519' style='fill:%23404040;stroke-width:1' /%3e%3ccircle cx='7.9337869' \
cy='7.9337869' r='5.9987168' style='fill:%235080d0;stroke-width:1' /%3e%3cpath \
d='M 9.2253789,9.8629486 H 6.5997716 v -0.356384 q 0,-0.5963983 0.2400139,-1.0546067 \
0.240014,-0.4654816 1.0109681,-1.1782504 L 8.316235,6.8518647 Q 8.7308046,6.473661 \
8.9199065,6.1390961 9.1162816,5.8045312 9.1162816,5.4699662 q 0,-0.5091205 -0.3491113,-0.7927734 \
-0.3491111,-0.2909259 -0.9746021,-0.2909259 -0.5891252,0 -1.2728012,0.247287 \
-0.6836761,0.240014 -1.4255375,0.720042 V 3.0698267 q 0.8800513,-0.3054724 1.6073661,-0.4509353 \
0.7273151,-0.145463 1.403718,-0.145463 1.7746486,0 2.7056104,0.727315 0.930965,0.720042 \
0.930965,2.1092135 0,0.7127686 -0.283654,1.2800746 -0.283652,0.5600324 -0.967329,1.2073428 \
L 10.025425,8.2119439 Q 9.530851,8.6628792 9.3781148,8.9392588 9.2253789,9.2083654 \
9.2253789,9.535657 Z M 6.5997716,10.939376 h 2.6256073 v 2.589241 H 6.5997716 Z' \
style='fill:%23f8f8f8;stroke-width:1.35412836' /%3e%3c/svg%3e ");    
  background-repeat: no-repeat;
  background-position: center;
  /* When not using a background image, this additional style works
     reasonably well along with a ::before content of "?": */
  /*border-width: 1px;
  border-style: outset;
  border-radius: 0.5em;
  font-size: 100%;
  font-family: monspace;
  font-weight: 700;
  overflow: hidden;
  background-color: rgba(54, 54, 255,1);
  color: rgb(255, 255, 255);
  text-align: center;
  line-height: 1; */
}
/*.help-buttonlet::before {
  content: "?";
}*/
/**
   We really want to hide all help text via CSS but CSS cannot select
   TEXT nodes. Thus we move them out of the way programmatically
   during initialization.
*/
.help-buttonlet > *{}

/**
   CSS class for PopupWidget which wraps .help-buttonlet content.
   They also have class fossil-tooltip. We need an overly-exact
   selector here to be certain that this class's style overrides
   that of fossil-tooltip.
*/
.fossil-tooltip.help-buttonlet-content {
  cursor: default;
  text-align: left;
  border-style: outset;
}

noscript > .error {
  /* Part of the style_emit_noscript_for_js_page() interface. */
  padding: 1em;
  font-size: 150%;
}

/************************************************************
 pikchr...
 DOM structure:
  <DIV.pikchr-wrapper>
    <DIV.pikchr-svg>
      <SVG.pikchr>...</SVG>
    </DIV.pikchr-svg>
    <PRE.pikchr-src>...</PRE>
  </DIV.pikchr-wrapper>

************************************************************/
div.pikchr-wrapper {/*outer wrapper elem for a pikchr construct*/}
div.pikchr-svg {/*wrapper for SVG.pikchr element*/}
svg.pikchr {/*pikchr SVG*/
  width: 100%/*necessary for SOME SVGs for Chrome!*/;
}
pre.pikchr-src {/*source code view for a pikchr (see fossil.pikchr.js)*/
  box-sizing: border-box;
  text-align: left;
}
/* The .source-inline class tells the .source class that the
   source view, when enbaled, should be "inline" (same position
   as the graphic), else the sources are shifted to the left as
   if they were "plain text". */
div.pikchr-wrapper.center:not(.source),
div.pikchr-wrapper.center.source.source-inline{
  text-align: center;
  /* Reminder for The Future: this impl also works:

      display: grid; place-items: center;

     and does not require setting display:inline-block on the relevant
     child items, but caniuse.com/css-grid suggests that some
     still-seemingly-legitimate browsers don't support grid mode. */
}
div.pikchr-wrapper.center > div.pikchr-svg {
}
div.pikchr-wrapper.center:not(.source) > pre.pikchr-src,
div.pikchr-wrapper.center:not(.source) > div.pikchr-svg,
/* ^^^ Centered non-source-view elements */
div.pikchr-wrapper.center.source.source-inline > pre.pikchr-src,
div.pikchr-wrapper.center.source.source-inline > div.pikchr-svg
/* ^^^ Centered inline-source-view elements */{
  display:inline-block/*allows parent text-align to do the alignment*/;
}
div.pikchr-wrapper.indent:not(.source),
div.pikchr-wrapper.indent.source.source-inline{
  margin-left: 4em;
}
div.pikchr-wrapper.float-left:not(.source),
div.pikchr-wrapper.float-left.source.source-inline {
  float: left;
  padding: 4em;
}
div.pikchr-wrapper.float-right:not(.source),
div.pikchr-wrapper.float-right.source.source-inline{
  float: right;
  padding: 4em;
}

/* For pikchr-wrapper.source mode, toggle pre.pikchr-src and
   svg.pikchr visibility... */
div.pikchr-wrapper.source > pre.pikchr-src {
  /* Source code  ^^^^^^^ is visible, else it is hidden */
}
div.pikchr-wrapper:not(.source) > pre.pikchr-src {
  /* Hide sources when image is being shown. */
  position: absolute !important;
  opacity: 0 !important;
  pointer-events: none !important;
  display: none !important;
}
div.pikchr-wrapper.source > div.pikchr-svg {
  /* Hide image when sources are being shown. */
  position: absolute !important;
  opacity: 0 !important;
  pointer-events: none !important;
  display: none !important;
}

Changes to src/descendants.c.

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
...
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
** Usage: %fossil descendants ?CHECKIN? ?OPTIONS?
**
** Find all leaf descendants of the check-in specified or if the argument
** is omitted, of the check-in currently checked out.
**
** Options:
**    -R|--repository FILE       Extract info from repository FILE
**    -W|--width <num>           Width of lines (default is to auto-detect).
**                               Must be >20 or 0 (= no limit, resulting in a
**                               single line per entry).
**
** See also: [[finfo]], [[info]], [[leaves]]
*/
void descendants_cmd(void){
  Stmt q;
  int base, width;
  const char *zWidth;
................................................................................
**
** Options:
**   -a|--all         show ALL leaves
**   --bybranch       order output by branch name
**   -c|--closed      show only closed leaves
**   -m|--multiple    show only cases with multiple leaves on a single branch
**   --recompute      recompute the "leaf" table in the repository DB
**   -W|--width <num> Width of lines (default is to auto-detect). Must be
**                    >39 or 0 (= no limit, resulting in a single line per
**                    entry).
**
** See also: [[descendants]], [[finfo]], [[info]], [[branch]]
*/
void leaves_cmd(void){
  Stmt q;
  Blob sql;
  int showAll = find_option("all", "a", 0)!=0;







|
|
|







 







|
|
|







342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
...
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
** Usage: %fossil descendants ?CHECKIN? ?OPTIONS?
**
** Find all leaf descendants of the check-in specified or if the argument
** is omitted, of the check-in currently checked out.
**
** Options:
**    -R|--repository FILE       Extract info from repository FILE
**    -W|--width N               Width of lines (default is to auto-detect).
**                               Must be greater than 20 or else 0 for no
**                               limit, resulting in a one line per entry.
**
** See also: [[finfo]], [[info]], [[leaves]]
*/
void descendants_cmd(void){
  Stmt q;
  int base, width;
  const char *zWidth;
................................................................................
**
** Options:
**   -a|--all         show ALL leaves
**   --bybranch       order output by branch name
**   -c|--closed      show only closed leaves
**   -m|--multiple    show only cases with multiple leaves on a single branch
**   --recompute      recompute the "leaf" table in the repository DB
**   -W|--width N     Width of lines (default is to auto-detect). Must be
**                    more than 39 or else 0 no limit, resulting in a single
**                    line per entry.
**
** See also: [[descendants]], [[finfo]], [[info]], [[branch]]
*/
void leaves_cmd(void){
  Stmt q;
  Blob sql;
  int showAll = find_option("all", "a", 0)!=0;

Changes to src/diff.c.

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
....
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
/*
** Count the number of lines in the input string.  Include the last line
** in the count even if it lacks the \n terminator.  If an empty string
** is specified, the number of lines is zero.  For the purposes of this
** function, a string is considered empty if it contains no characters
** -OR- it contains only NUL characters.
*/
static int count_lines(
  const char *z,
  int n,
  int *pnLine
){
  int nLine;
  const char *zNL, *z2;
  for(nLine=0, z2=z; (zNL = strchr(z2,'\n'))!=0; z2=zNL+1, nLine++){}
................................................................................
    }else if( iEX>iEXp ){
      iSXp = iSX;
      iSYp = iSY;
      iEXp = iEX;
      iEYp = iEY;
    }
  }
  if( iSXb==iEXb && (iE1-iS1)*(iE2-iS2)<400 ){
    /* If no common sequence is found using the hashing heuristic and
    ** the input is not too big, use the expensive exact solution */
    optimalLCS(p, iS1, iE1, iS2, iE2, piSX, piEX, piSY, piEY);
  }else{
    *piSX = iSXb;
    *piSY = iSYb;
    *piEX = iEXb;







|







 







|







123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
....
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
/*
** Count the number of lines in the input string.  Include the last line
** in the count even if it lacks the \n terminator.  If an empty string
** is specified, the number of lines is zero.  For the purposes of this
** function, a string is considered empty if it contains no characters
** -OR- it contains only NUL characters.
*/
int count_lines(
  const char *z,
  int n,
  int *pnLine
){
  int nLine;
  const char *zNL, *z2;
  for(nLine=0, z2=z; (zNL = strchr(z2,'\n'))!=0; z2=zNL+1, nLine++){}
................................................................................
    }else if( iEX>iEXp ){
      iSXp = iSX;
      iSYp = iSY;
      iEXp = iEX;
      iEYp = iEY;
    }
  }
  if( iSXb==iEXb && (sqlite3_int64)(iE1-iS1)*(iE2-iS2)<400 ){
    /* If no common sequence is found using the hashing heuristic and
    ** the input is not too big, use the expensive exact solution */
    optimalLCS(p, iS1, iE1, iS2, iE2, piSX, piEX, piSY, piEY);
  }else{
    *piSX = iSXb;
    *piSY = iSYb;
    *piEX = iEXb;

Changes to src/diffcmd.c.

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
** when using an external diff program.
**
** The "--binary" option causes files matching the glob PATTERN to be treated
** as binary when considering if they should be used with external diff program.
** This option overrides the "binary-glob" setting.
**
** Options:
**   --binary PATTERN           Treat files that match the glob PATTERN as binary

**   --branch BRANCH            Show diff of all changes on BRANCH
**   --brief                    Show filenames only
**   --checkin VERSION          Show diff of all changes in VERSION
**   --command PROG             External diff program - overrides "diff-command"
**   --context|-c N             Use N lines of context
**   --diff-binary BOOL         Include binary files when using external commands
**   --exec-abs-paths           Force absolute path names with external commands.
**   --exec-rel-paths           Force relative path names with external commands.
**   --from|-r VERSION          Select VERSION as source for the diff
**   --internal|-i              Use internal diff logic
**   --new-file|-N              Show complete text of added and deleted files
**   --numstat                  Show only the number of lines delete and added
**   --side-by-side|-y          Side-by-side diff
**   --strip-trailing-cr        Strip trailing CR
**   --tclsh PATH               Tcl/Tk used for --tk (default: "tclsh")
**   --tk                       Launch a Tcl/Tk GUI for display
**   --to VERSION               Select VERSION as target for the diff
**   --undo                     Diff against the "undo" buffer
**   --unified                  Unified diff
**   -v|--verbose               Output complete text of added or deleted files
**   -w|--ignore-all-space      Ignore white space when comparing lines
**   -W|--width <num>           Width of lines in side-by-side diff
**   -Z|--ignore-trailing-space Ignore changes to end-of-line whitespace
*/
void diff_cmd(void){
  int isGDiff;               /* True for gdiff.  False for normal diff */
  int isInternDiff;          /* True for internal diff */
  int verboseFlag;           /* True if -v or --verbose flag is used */
  const char *zFrom;         /* Source version number */
  const char *zTo;           /* Target version number */







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







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
** when using an external diff program.
**
** The "--binary" option causes files matching the glob PATTERN to be treated
** as binary when considering if they should be used with external diff program.
** This option overrides the "binary-glob" setting.
**
** Options:
**   --binary PATTERN            Treat files that match the glob PATTERN
**                               as binary
**   --branch BRANCH             Show diff of all changes on BRANCH
**   --brief                     Show filenames only
**   --checkin VERSION           Show diff of all changes in VERSION
**   --command PROG              External diff program. Overrides "diff-command"
**   --context|-c N              Use N lines of context
**   --diff-binary BOOL          Include binary files with external commands
**   --exec-abs-paths            Force absolute path names on external commands
**   --exec-rel-paths            Force relative path names on external commands
**   --from|-r VERSION           Select VERSION as source for the diff
**   --internal|-i               Use internal diff logic
**   --new-file|-N               Show complete text of added and deleted files
**   --numstat                   Show only the number of lines delete and added
**   --side-by-side|-y           Side-by-side diff
**   --strip-trailing-cr         Strip trailing CR
**   --tclsh PATH                Tcl/Tk used for --tk (default: "tclsh")
**   --tk                        Launch a Tcl/Tk GUI for display
**   --to VERSION                Select VERSION as target for the diff
**   --undo                      Diff against the "undo" buffer
**   --unified                   Unified diff
**   -v|--verbose                Output complete text of added or deleted files
**   -w|--ignore-all-space       Ignore white space when comparing lines
**   -W|--width N                Width of lines in side-by-side diff
**   -Z|--ignore-trailing-space  Ignore changes to end-of-line whitespace
*/
void diff_cmd(void){
  int isGDiff;               /* True for gdiff.  False for normal diff */
  int isInternDiff;          /* True for internal diff */
  int verboseFlag;           /* True if -v or --verbose flag is used */
  const char *zFrom;         /* Source version number */
  const char *zTo;           /* Target version number */

Changes to src/dispatch.c.

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
...
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
...
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
...
425
426
427
428
429
430
431
432

433
434
435
436

437
438
439
440
441
442
443
  int i;
  for(i=3; i<n-1; i++){
    if( z[i]==' ' && z[i+1]!=' ' && z[i-1]==' ' && z[i-2]!='.' ) return i+1;
  }
  return 0 ;
}

/*
** Append text to pOut, adding formatting markup.  Terms that
** have all lower-case letters are within <tt>..</tt>.  Terms
** that have all upper-case letters are within <i>..</i>.
*/
static void appendMixedFont(Blob *pOut, const char *z, int n){
  const char *zEnd = "";
  int i = 0;
  int j;
  while( i<n ){
    if( z[i]==' ' || z[i]=='=' ){
      for(j=i+1; j<n && (z[j]==' ' || z[j]=='='); j++){}
      blob_append(pOut, z+i, j-i);
      i = j;
    }else{
      for(j=i; j<n && z[j]!=' ' && z[j]!='=' && !fossil_isalpha(z[j]); j++){}
      if( j>=n || z[j]==' ' || z[j]=='=' ){
        zEnd = "";
      }else{
        if( fossil_isupper(z[j]) && z[i]!='-' ){
          blob_append(pOut, "<i>",3);
          zEnd = "</i>";
        }else{
          blob_append(pOut, "<tt>", 4);
          zEnd = "</tt>";
        }
      }
      while( j<n && z[j]!=' ' && z[j]!='=' ){ j++; }
      blob_appendf(pOut, "%#h", j-i, z+i);
      if( zEnd[0] ) blob_append(pOut, zEnd, -1);
      i = j;
    }
  }
}

/*
** Input string zIn starts with '['.  If the content is a hyperlink of the
** form [[...]] then return the index of the closing ']'.  Otherwise return 0.
*/
static int help_is_link(const char *z, int n){
  int i;
  char c;
................................................................................
  for(i=3; i<n && (c = z[i])!=0; i++){
    if( c==']' && z[i-1]==']' ) return i;
  }
  return 0;
}

/*
** Append text to pOut, adding hyperlink markup for [...].




*/
static void appendLinked(Blob *pOut, const char *z, int n){
  int i = 0;
  int j;
  while( i<n ){

    if( z[i]=='[' && (j = help_is_link(z+i, n-i))>0 ){
      if( i ) blob_append(pOut, z, i);
      z += i+2;
      n -= i+2;
      blob_appendf(pOut, "<a href='%R/help?cmd=%.*s'>%.*s</a>",
         j-3, z, j-3, z);
      z += j-1;
      n -= j-1;
      i = 0;
























    }else{
      i++;
    }
  }
  blob_append(pOut, z, i);
}




































/*
** Attempt to reformat plain-text help into HTML for display on a webpage.
**
** The HTML output is appended to Blob pHtml, which should already be
** initialized.
**
................................................................................
  static const char *zEndUL = "</ul>";
  static const char *zEndDD = "</dd>";

  aIndent[0] = 0;
  azEnd[0] = "";
  while( zHelp[0] ){
    i = 0;
    while( (c = zHelp[i])!=0
        && c!='\n'
        && c!='<'
        && (c!='%' || strncmp(zHelp+i,"%fossil",7)!=0)
    ){ i++; }
    if( c=='%' ){
      if( i ) blob_appendf(pHtml, "%#h", i, zHelp);
      zHelp += i + 1;
      wantBR = 1;
      continue;
    }else if( c=='<' ){
      if( i ) blob_appendf(pHtml, "%#h", i, zHelp);
      blob_append(pHtml, "&amp;", 5);
      zHelp += i + 1;
      continue;
    }
    if( i>2 && zHelp[0]=='>' && zHelp[1]==' ' ){
      isDT = 1;
      for(nIndent=1; nIndent<i && zHelp[nIndent]==' '; nIndent++){}
    }else{
      isDT = 0;
      for(nIndent=0; nIndent<i && zHelp[nIndent]==' '; nIndent++){}
    }
    if( nIndent==i ){
      if( c==0 ) break;



      blob_append(pHtml, "\n", 1);

      wantP = 1;
      wantBR = 0;
      zHelp += i+1;
      continue;
    }
    if( nIndent+2<i && zHelp[nIndent]=='*' && zHelp[nIndent+1]==' ' ){
      nIndent += 2;
................................................................................
      if( iDD ){
        int x;
        assert( iLevel<ArraySize(aIndent)-1 );
        iLevel++;
        aIndent[iLevel] = x = nIndent+iDD;
        azEnd[iLevel] = zEndDD;
        appendMixedFont(pHtml, zHelp+nIndent, iDD-2);
        blob_appendf(pHtml, "</dt><dd>%#h\n", i-x, zHelp+x);

      }else{
        appendMixedFont(pHtml, zHelp+nIndent, i-nIndent);
        blob_append(pHtml, "</dt>\n", 6);
      }

    }else if( wantBR ){
      appendMixedFont(pHtml, zHelp+nIndent, i-nIndent);
      blob_append(pHtml, "<br>\n", 5);
      wantBR = 0;
    }else{
      appendLinked(pHtml, zHelp+nIndent, i-nIndent);
      blob_append_char(pHtml, '\n');







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|
>
>
>
>





>
|








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






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







 







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










>
>
>
|
>







 







|
>


<

>







227
228
229
230
231
232
233



































234
235
236
237
238
239
240
...
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
...
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
...
452
453
454
455
456
457
458
459
460
461
462

463
464
465
466
467
468
469
470
471
  int i;
  for(i=3; i<n-1; i++){
    if( z[i]==' ' && z[i+1]!=' ' && z[i-1]==' ' && z[i-2]!='.' ) return i+1;
  }
  return 0 ;
}




































/*
** Input string zIn starts with '['.  If the content is a hyperlink of the
** form [[...]] then return the index of the closing ']'.  Otherwise return 0.
*/
static int help_is_link(const char *z, int n){
  int i;
  char c;
................................................................................
  for(i=3; i<n && (c = z[i])!=0; i++){
    if( c==']' && z[i-1]==']' ) return i;
  }
  return 0;
}

/*
** Append text to pOut with changes:
**
**    *   Add hyperlink markup for [[...]]
**    *   Escape HTML characters: < > & and "
**    *   Change "%fossil" to just "fossil"
*/
static void appendLinked(Blob *pOut, const char *z, int n){
  int i = 0;
  int j;
  while( i<n ){
    char c = z[i];
    if( c=='[' && (j = help_is_link(z+i, n-i))>0 ){
      if( i ) blob_append(pOut, z, i);
      z += i+2;
      n -= i+2;
      blob_appendf(pOut, "<a href='%R/help?cmd=%.*s'>%.*s</a>",
         j-3, z, j-3, z);
      z += j-1;
      n -= j-1;
      i = 0;
    }else if( c=='%' && n-i>=7 && strncmp(z+i,"%fossil",7)==0 ){
      if( i ) blob_append(pOut, z, i);
      z += i+7;
      n -= i+7;
      blob_append(pOut, "fossil", 6);
      i = 0;
    }else if( c=='<' ){
      if( i ) blob_append(pOut, z, i);
      blob_append(pOut, "&lt;", 4);
      z += i+1;
      n -= i+1;
      i = 0;
    }else if( c=='>' ){
      if( i ) blob_append(pOut, z, i);
      blob_append(pOut, "&gt;", 4);
      z += i+1;
      n -= i+1;
      i = 0;
    }else if( c=='&' ){
      if( i ) blob_append(pOut, z, i);
      blob_append(pOut, "&amp;", 5);
      z += i+1;
      n -= i+1;
      i = 0;
    }else{
      i++;
    }
  }
  blob_append(pOut, z, i);
}

/*
** Append text to pOut, adding formatting markup.  Terms that
** have all lower-case letters are within <tt>..</tt>.  Terms
** that have all upper-case letters are within <i>..</i>.
*/
static void appendMixedFont(Blob *pOut, const char *z, int n){
  const char *zEnd = "";
  int i = 0;
  int j;
  while( i<n ){
    if( z[i]==' ' || z[i]=='=' ){
      for(j=i+1; j<n && (z[j]==' ' || z[j]=='='); j++){}
      appendLinked(pOut, z+i, j-i);
      i = j;
    }else{
      for(j=i; j<n && z[j]!=' ' && z[j]!='=' && !fossil_isalpha(z[j]); j++){}
      if( j>=n || z[j]==' ' || z[j]=='=' ){
        zEnd = "";
      }else{
        if( fossil_isupper(z[j]) && z[i]!='-' ){
          blob_append(pOut, "<i>",3);
          zEnd = "</i>";
        }else{
          blob_append(pOut, "<tt>", 4);
          zEnd = "</tt>";
        }
      }
      while( j<n && z[j]!=' ' && z[j]!='=' ){ j++; }
      appendLinked(pOut, z+i, j-i);
      if( zEnd[0] ) blob_append(pOut, zEnd, -1);
      i = j;
    }
  }
}

/*
** Attempt to reformat plain-text help into HTML for display on a webpage.
**
** The HTML output is appended to Blob pHtml, which should already be
** initialized.
**
................................................................................
  static const char *zEndUL = "</ul>";
  static const char *zEndDD = "</dd>";

  aIndent[0] = 0;
  azEnd[0] = "";
  while( zHelp[0] ){
    i = 0;
    while( (c = zHelp[i])!=0 && c!='\n' ){
      if( c=='%' && i>2 && zHelp[i-2]==':' && strncmp(zHelp+i,"%fossil",7)==0 ){
        appendLinked(pHtml, zHelp, i);
        zHelp += i+1;
        i = 0;
        wantBR = 1;
        continue;
      }
      i++;






    }
    if( i>2 && zHelp[0]=='>' && zHelp[1]==' ' ){
      isDT = 1;
      for(nIndent=1; nIndent<i && zHelp[nIndent]==' '; nIndent++){}
    }else{
      isDT = 0;
      for(nIndent=0; nIndent<i && zHelp[nIndent]==' '; nIndent++){}
    }
    if( nIndent==i ){
      if( c==0 ) break;
      if( iLevel && azEnd[iLevel]==zEndPRE ){
        /* Skip the newline at the end of a <pre> */
      }else{
        blob_append_char(pHtml, '\n');
      }
      wantP = 1;
      wantBR = 0;
      zHelp += i+1;
      continue;
    }
    if( nIndent+2<i && zHelp[nIndent]=='*' && zHelp[nIndent+1]==' ' ){
      nIndent += 2;
................................................................................
      if( iDD ){
        int x;
        assert( iLevel<ArraySize(aIndent)-1 );
        iLevel++;
        aIndent[iLevel] = x = nIndent+iDD;
        azEnd[iLevel] = zEndDD;
        appendMixedFont(pHtml, zHelp+nIndent, iDD-2);
        blob_append(pHtml, "</dt><dd>",9);
        appendLinked(pHtml, zHelp+x, i-x);
      }else{
        appendMixedFont(pHtml, zHelp+nIndent, i-nIndent);

      }
      blob_append(pHtml, "</dt>\n", 6);
    }else if( wantBR ){
      appendMixedFont(pHtml, zHelp+nIndent, i-nIndent);
      blob_append(pHtml, "<br>\n", 5);
      wantBR = 0;
    }else{
      appendLinked(pHtml, zHelp+nIndent, i-nIndent);
      blob_append_char(pHtml, '\n');

Changes to src/doc.c.

395
396
397
398
399
400
401


















402
403
404
405
406
407
408
...
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
...
790
791
792
793
794
795
796

797
798
799
800
801
802
803
        return z;
      default:
        assert(!"cannot happen - invalid tokenizerState value.");
    }
  }
  return 0;
}



















/*
** Guess the mime-type of a document based on its name.
*/
const char *mimetype_from_name(const char *zName){
  const char *z;
  int i;
................................................................................
    if( wiki_find_title(pBody, &title, &tail) ){
      style_header("%s", blob_str(&title));
      wiki_convert(&tail, 0, WIKI_BUTTONS);
    }else{
      style_header("%s", zDefaultTitle);
      wiki_convert(pBody, 0, WIKI_BUTTONS);
    }

    style_footer();
  }else if( fossil_strcmp(zMime, "text/x-markdown")==0 ){
    Blob tail = BLOB_INITIALIZER;
    markdown_to_html(pBody, &title, &tail);
    if( blob_size(&title)>0 ){
      style_header("%s", blob_str(&title));
    }else{
      style_header("%s", zDefaultTitle);
    }
    convert_href_and_output(&tail);

    style_footer();
  }else if( fossil_strcmp(zMime, "text/plain")==0 ){
    style_header("%s", zDefaultTitle);
    @ <blockquote><pre>
    @ %h(blob_str(pBody))
    @ </pre></blockquote>

    style_footer();
  }else if( fossil_strcmp(zMime, "text/html")==0
            && doc_is_embedded_html(pBody, &title) ){
    if( blob_size(&title)==0 ) blob_append(&title,zFilename,-1);
    style_header("%s", blob_str(&title));
    convert_href_and_output(pBody);

    style_footer();
#ifdef FOSSIL_ENABLE_TH1_DOCS
  }else if( Th_AreDocsEnabled() &&
            fossil_strcmp(zMime, "application/x-th1")==0 ){
    int raw = P("raw")!=0;
    if( !raw ){
      Blob tail;
................................................................................
        style_header("%h", zFilename);
        Th_Render(blob_str(pBody));
      }
    }else{
      Th_Render(blob_str(pBody));
    }
    if( !raw ){

      style_footer();
    }
#endif
  }else{
    fossil_free(style_csp(1));
    cgi_set_content_type(zMime);
    cgi_set_content(pBody);







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







 







>










>






>






>







 







>







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
...
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
...
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
        return z;
      default:
        assert(!"cannot happen - invalid tokenizerState value.");
    }
  }
  return 0;
}

/*
** Emit Javascript which applies (or optionally can apply) to both the
** /doc and /wiki pages. None of this implements required
** functionality, just nice-to-haves. Any calls after the first are
** no-ops.
*/
void document_emit_js(void){
  static int once = 0;
  if(0==once++){
    builtin_fossil_js_bundle_or("pikchr", 0);
    style_script_begin(__FILE__,__LINE__);
    CX("window.addEventListener('load', "
       "()=>window.fossil.pikchr.addSrcView(), "
       "false);\n");
    style_script_end();
  }
}

/*
** Guess the mime-type of a document based on its name.
*/
const char *mimetype_from_name(const char *zName){
  const char *z;
  int i;
................................................................................
    if( wiki_find_title(pBody, &title, &tail) ){
      style_header("%s", blob_str(&title));
      wiki_convert(&tail, 0, WIKI_BUTTONS);
    }else{
      style_header("%s", zDefaultTitle);
      wiki_convert(pBody, 0, WIKI_BUTTONS);
    }
    document_emit_js();
    style_footer();
  }else if( fossil_strcmp(zMime, "text/x-markdown")==0 ){
    Blob tail = BLOB_INITIALIZER;
    markdown_to_html(pBody, &title, &tail);
    if( blob_size(&title)>0 ){
      style_header("%s", blob_str(&title));
    }else{
      style_header("%s", zDefaultTitle);
    }
    convert_href_and_output(&tail);
    document_emit_js();
    style_footer();
  }else if( fossil_strcmp(zMime, "text/plain")==0 ){
    style_header("%s", zDefaultTitle);
    @ <blockquote><pre>
    @ %h(blob_str(pBody))
    @ </pre></blockquote>
    document_emit_js();
    style_footer();
  }else if( fossil_strcmp(zMime, "text/html")==0
            && doc_is_embedded_html(pBody, &title) ){
    if( blob_size(&title)==0 ) blob_append(&title,zFilename,-1);
    style_header("%s", blob_str(&title));
    convert_href_and_output(pBody);
    document_emit_js();
    style_footer();
#ifdef FOSSIL_ENABLE_TH1_DOCS
  }else if( Th_AreDocsEnabled() &&
            fossil_strcmp(zMime, "application/x-th1")==0 ){
    int raw = P("raw")!=0;
    if( !raw ){
      Blob tail;
................................................................................
        style_header("%h", zFilename);
        Th_Render(blob_str(pBody));
      }
    }else{
      Th_Render(blob_str(pBody));
    }
    if( !raw ){
      document_emit_js();
      style_footer();
    }
#endif
  }else{
    fossil_free(style_csp(1));
    cgi_set_content_type(zMime);
    cgi_set_content(pBody);

Changes to src/event.c.

226
227
228
229
230
231
232

233
234
235
236
237
238
239
    @ </pre>
  }
  zFullId = db_text(0, "SELECT SUBSTR(tagname,7)"
                       "  FROM tag"
                       " WHERE tagname GLOB 'event-%q*'",
                    zId);
  attachment_list(zFullId, "<hr /><h2>Attachments:</h2><ul>");

  style_footer();
  manifest_destroy(pTNote);
}

/*
** Add or update a new tech note to the repository.  rid is id of
** the prior version of this technote, if any.







>







226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    @ </pre>
  }
  zFullId = db_text(0, "SELECT SUBSTR(tagname,7)"
                       "  FROM tag"
                       " WHERE tagname GLOB 'event-%q*'",
                    zId);
  attachment_list(zFullId, "<hr /><h2>Attachments:</h2><ul>");
  document_emit_js();
  style_footer();
  manifest_destroy(pTNote);
}

/*
** Add or update a new tech note to the repository.  rid is id of
** the prior version of this technote, if any.

Changes to src/file.c.

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
...
132
133
134
135
136
137
138
139


140
141

142
143
144
145
146
147
148
...
314
315
316
317
318
319
320
321

322
323
324
325
326
327
328
...
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
...
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
...
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
...
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
....
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
....
1358
1359
1360
1361
1362
1363
1364



1365
1366
1367
1368
1369
1370
1371
....
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
....
2470
2471
2472
2473
2474
2475
2476











2477
2478
2479
2480
2481
2482
2483
....
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
**
** The difference is in the handling of symbolic links.  RepoFILE should be
** used for files that are under management by a Fossil repository.  ExtFILE
** should be used for files that are not under management.  SymFILE is for
** a few special cases such as the "fossil test-tarball" command when we never
** want to follow symlinks.
**
** If RepoFILE is used and if the allow-symlinks setting is true and if
** the object is a symbolic link, then the object is treated like an ordinary
** file whose content is name of the object to which the symbolic link
** points.
**

** If ExtFILE is used or allow-symlinks is false, then operations on a
** symbolic link are the same as operations on the object to which the
** symbolic link points.
**


** SymFILE is like RepoFILE except that it always uses the target filename of
** a symbolic link as the content, instead of the content of the object
** that the symlink points to.  SymFILE acts as if allow-symlinks is always ON.
*/
#define ExtFILE    0  /* Always follow symlinks */
#define RepoFILE   1  /* Follow symlinks if and only if allow-symlinks is OFF */
#define SymFILE    2  /* Never follow symlinks */

#include <dirent.h>
#if defined(_WIN32)
................................................................................
  const char *zFilename,  /* name of file or directory to inspect. */
  struct fossilStat *buf, /* pointer to buffer where info should go. */
  int eFType              /* Look at symlink itself if RepoFILE and enabled. */
){
  int rc;
  void *zMbcs = fossil_utf8_to_path(zFilename, 0);
#if !defined(_WIN32)
  if( eFType>=RepoFILE && (eFType==SymFILE || db_allow_symlinks()) ){


    rc = lstat(zMbcs, buf);
  }else{

    rc = stat(zMbcs, buf);
  }
#else
  rc = win32_stat(zMbcs, buf, eFType);
#endif
  fossil_path_free(zMbcs);
  return rc;
................................................................................
  return file_perm(zFilename, eFType)==PERM_EXE;
}

/*
** Return TRUE if the named file is a symlink and symlinks are allowed.
** Return false for all other cases.
**
** This routines RepoFILE - that zFilename is always a file under management.

**
** On Windows, always return False.
*/
int file_islink(const char *zFilename){
  return file_perm(zFilename, RepoFILE)==PERM_LNK;
}

................................................................................
  static const char *azReqTab[] = {
     "blob", "delta", "rcvfrom", "user", "config"
  };
  if( !file_isfile(zFilename, ExtFILE) ) return 0;
  sz = file_size(zFilename, ExtFILE);
  if( sz<35328 ) return 0;
  if( sz%512!=0 ) return 0;
  rc = sqlite3_open_v2(zFilename, &db, 
          SQLITE_OPEN_READWRITE, 0);
  if( rc!=0 ) goto not_a_repo;
  for(i=0; i<count(azReqTab); i++){
    if( sqlite3_table_column_metadata(db, "main", azReqTab[i],0,0,0,0,0,0) ){
      goto not_a_repo;
    }
  }
................................................................................
** zFilename is a symbolic link, it is the object that zFilename points
** to that is modified.
*/
int file_setexe(const char *zFilename, int onoff){
  int rc = 0;
#if !defined(_WIN32)
  struct stat buf;
  if( fossil_stat(zFilename, &buf, RepoFILE)!=0 
   || S_ISLNK(buf.st_mode)
   || S_ISDIR(buf.st_mode)
  ){
    return 0;
  }
  if( onoff ){
    int targetMode = (buf.st_mode & 0444)>>2;
................................................................................
  }
  if( rc!=1 ){
#if defined(_WIN32)
    wchar_t *zMbcs = fossil_utf8_to_path(zName, 1);
    rc = _wmkdir(zMbcs);
#else
    char *zMbcs = fossil_utf8_to_path(zName, 1);
    rc = mkdir(zName, 0755);
#endif
    fossil_path_free(zMbcs);
    return rc;
  }
  return 0;
}

................................................................................
  int nName, rc = 0;
  char *zName;

  nName = strlen(zFilename);
  zName = mprintf("%s", zFilename);
  nName = file_simplify_name(zName, nName, 0);
  while( nName>0 && zName[nName-1]!='/' ){ nName--; }
  if( nName ){
    zName[nName-1] = 0;
    if( file_isdir(zName, eFType)!=1 ){
      rc = file_mkfolder(zName, eFType, forceFlag, errorReturn);
      if( rc==0 ){
        if( file_mkdir(zName, eFType, forceFlag)
         && file_isdir(zName, eFType)!=1
        ){
................................................................................
  Blob x;
  int rc;
  sqlite3_int64 iMtime;
  struct fossilStat testFileStat;
  memset(zBuf, 0, sizeof(zBuf));
  blob_zero(&x);
  file_canonical_name(zPath, &x, slash);
  fossil_print("[%s] -> [%s]\n", zPath, blob_buffer(&x));
  blob_reset(&x);
  memset(&testFileStat, 0, sizeof(struct fossilStat));
  rc = fossil_stat(zPath, &testFileStat, 0);
  fossil_print("  stat_rc                = %d\n", rc);
  sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", testFileStat.st_size);
  fossil_print("  stat_size              = %s\n", zBuf);
  if( g.db==0 ) sqlite3_open(":memory:", &g.db);
  z = db_text(0, "SELECT datetime(%lld, 'unixepoch')", testFileStat.st_mtime);
................................................................................
  fossil_print("  file_mode(RepoFILE)    = 0%o\n", file_mode(zPath,RepoFILE));
  fossil_print("  file_isfile(RepoFILE)  = %d\n", file_isfile(zPath,RepoFILE));
  fossil_print("  file_isfile_or_link    = %d\n", file_isfile_or_link(zPath));
  fossil_print("  file_islink            = %d\n", file_islink(zPath));
  fossil_print("  file_isexe(RepoFILE)   = %d\n", file_isexe(zPath,RepoFILE));
  fossil_print("  file_isdir(RepoFILE)   = %d\n", file_isdir(zPath,RepoFILE));
  fossil_print("  file_is_repository     = %d\n", file_is_repository(zPath));



  if( reset ) resetStat();
}

/*
** COMMAND: test-file-environment
**
** Usage: %fossil test-file-environment FILENAME...
................................................................................
** Display the effective file handling subsystem "settings" and then
** display file system information about the files specified, if any.
**
** Options:
**
**     --allow-symlinks BOOLEAN     Temporarily turn allow-symlinks on/off
**     --open-config                Open the configuration database first.
**     --slash                      Trailing slashes, if any, are retained.
**     --reset                      Reset cached stat() info for each file.


*/
void cmd_test_file_environment(void){
  int i;
  int slashFlag = find_option("slash",0,0)!=0;
  int resetFlag = find_option("reset",0,0)!=0;

  const char *zAllow = find_option("allow-symlinks",0,1);
  if( find_option("open-config", 0, 0)!=0 ){
    Th_OpenConfig(1);
  }
  db_find_and_open_repository(OPEN_ANY_SCHEMA|OPEN_OK_NOT_FOUND, 0);
  fossil_print("filenames_are_case_sensitive() = %d\n",
               filenames_are_case_sensitive());
  fossil_print("db_allow_symlinks_by_default() = %d\n",
               db_allow_symlinks_by_default());
  if( zAllow ){
    g.allowSymlinks = !is_false(zAllow);
  }

  fossil_print("db_allow_symlinks() = %d\n", db_allow_symlinks());

  for(i=2; i<g.argc; i++){

    emitFileStat(g.argv[i], slashFlag, resetFlag);










  }
}

/*
** COMMAND: test-canonical-name
**
** Usage: %fossil test-canonical-name FILENAME...
................................................................................
  if( dryRunFlag!=0 ){
    fossil_print("dry-run: would have touched %d file(s)\n",
                 changeCount);
  }else{
    fossil_print("Touched %d file(s)\n", changeCount);
  }
}












/*
** Returns non-zero if the specified file name ends with any reserved name,
** e.g.: _FOSSIL_ or .fslckout.  Specifically, it returns 1 for exact match
** or 2 for a tail match on a longer file name.
**
** For the sake of efficiency, zFilename must be a canonical name, e.g. an
................................................................................
      if( 8==nFilename ) return 1;
      return zEnd[-9]=='/' ? 2 : gotSuffix;
    }
    case 'T':
    case 't':{
      if( nFilename<9 || zEnd[-9]!='.'
       || fossil_strnicmp(".fslckout", &zEnd[-9], 9) ){
        return 0; 
      }
      if( 9==nFilename ) return 1;
      return zEnd[-10]=='/' ? 2 : gotSuffix;
    }
    default:{
      return 0;
    }
  }
}

/*
** COMMAND: test-is-reserved-name
**
** Usage: %fossil test-is-ckout-db FILENAMES...
**
** Passes each given name to file_is_reserved_name() and outputs one
** line per file: the result value of that function followed by the
** name.
*/
void test_is_reserved_name_cmd(void){
  int i;

  if(g.argc<3){
    usage("FILENAME_1 [...FILENAME_N]");
  }
  for( i = 2; i < g.argc; ++i ){
    const int check = file_is_reserved_name(g.argv[i], -1);
    fossil_print("%d %s\n", check, g.argv[i]);
  }
}







|
|
|
<

>
|
<
<

>
>
|
|
<







 







|
>
>


>







 







|
>







 







|







 







|







 







|







 







|







 







|
|







 







>
>
>







 







<

>
>





>







<
<



>

>

>

>
>
>
>
>
>
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>







 







|









<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
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
...
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
...
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
...
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
...
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
...
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
...
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
....
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
....
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
....
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
....
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
....
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568





















**
** The difference is in the handling of symbolic links.  RepoFILE should be
** used for files that are under management by a Fossil repository.  ExtFILE
** should be used for files that are not under management.  SymFILE is for
** a few special cases such as the "fossil test-tarball" command when we never
** want to follow symlinks.
**
**   ExtFILE      Symbolic links always refer to the object to which the
**                link points.  Symlinks are never recognized as symlinks but
**                instead always appear to the the target object.

**
**   SymFILE      Symbolic links always appear to be files whose name is
**                the target pathname of the symbolic link.


**
**   RepoFILE     Like SymFILE if allow-symlinks is true, or like
**                ExtFILE if allow-symlinks is false.  In other words,
**                symbolic links are only recognized as something different
**                from files or directories if allow-symlinks is true.

*/
#define ExtFILE    0  /* Always follow symlinks */
#define RepoFILE   1  /* Follow symlinks if and only if allow-symlinks is OFF */
#define SymFILE    2  /* Never follow symlinks */

#include <dirent.h>
#if defined(_WIN32)
................................................................................
  const char *zFilename,  /* name of file or directory to inspect. */
  struct fossilStat *buf, /* pointer to buffer where info should go. */
  int eFType              /* Look at symlink itself if RepoFILE and enabled. */
){
  int rc;
  void *zMbcs = fossil_utf8_to_path(zFilename, 0);
#if !defined(_WIN32)
  if( (eFType=RepoFILE && db_allow_symlinks())
   || eFType==SymFILE ){
    /* Symlinks look like files whose content is the name of the target */
    rc = lstat(zMbcs, buf);
  }else{
    /* Symlinks look like the object to which they point */
    rc = stat(zMbcs, buf);
  }
#else
  rc = win32_stat(zMbcs, buf, eFType);
#endif
  fossil_path_free(zMbcs);
  return rc;
................................................................................
  return file_perm(zFilename, eFType)==PERM_EXE;
}

/*
** Return TRUE if the named file is a symlink and symlinks are allowed.
** Return false for all other cases.
**
** This routines assumes RepoFILE - that zFilename is always a file
** under management.
**
** On Windows, always return False.
*/
int file_islink(const char *zFilename){
  return file_perm(zFilename, RepoFILE)==PERM_LNK;
}

................................................................................
  static const char *azReqTab[] = {
     "blob", "delta", "rcvfrom", "user", "config"
  };
  if( !file_isfile(zFilename, ExtFILE) ) return 0;
  sz = file_size(zFilename, ExtFILE);
  if( sz<35328 ) return 0;
  if( sz%512!=0 ) return 0;
  rc = sqlite3_open_v2(zFilename, &db,
          SQLITE_OPEN_READWRITE, 0);
  if( rc!=0 ) goto not_a_repo;
  for(i=0; i<count(azReqTab); i++){
    if( sqlite3_table_column_metadata(db, "main", azReqTab[i],0,0,0,0,0,0) ){
      goto not_a_repo;
    }
  }
................................................................................
** zFilename is a symbolic link, it is the object that zFilename points
** to that is modified.
*/
int file_setexe(const char *zFilename, int onoff){
  int rc = 0;
#if !defined(_WIN32)
  struct stat buf;
  if( fossil_stat(zFilename, &buf, RepoFILE)!=0
   || S_ISLNK(buf.st_mode)
   || S_ISDIR(buf.st_mode)
  ){
    return 0;
  }
  if( onoff ){
    int targetMode = (buf.st_mode & 0444)>>2;
................................................................................
  }
  if( rc!=1 ){
#if defined(_WIN32)
    wchar_t *zMbcs = fossil_utf8_to_path(zName, 1);
    rc = _wmkdir(zMbcs);
#else
    char *zMbcs = fossil_utf8_to_path(zName, 1);
    rc = mkdir(zMbcs, 0755);
#endif
    fossil_path_free(zMbcs);
    return rc;
  }
  return 0;
}

................................................................................
  int nName, rc = 0;
  char *zName;

  nName = strlen(zFilename);
  zName = mprintf("%s", zFilename);
  nName = file_simplify_name(zName, nName, 0);
  while( nName>0 && zName[nName-1]!='/' ){ nName--; }
  if( nName>1 ){
    zName[nName-1] = 0;
    if( file_isdir(zName, eFType)!=1 ){
      rc = file_mkfolder(zName, eFType, forceFlag, errorReturn);
      if( rc==0 ){
        if( file_mkdir(zName, eFType, forceFlag)
         && file_isdir(zName, eFType)!=1
        ){
................................................................................
  Blob x;
  int rc;
  sqlite3_int64 iMtime;
  struct fossilStat testFileStat;
  memset(zBuf, 0, sizeof(zBuf));
  blob_zero(&x);
  file_canonical_name(zPath, &x, slash);
  char *zFull = blob_str(&x);
  fossil_print("[%s] -> [%s]\n", zPath, zFull);
  memset(&testFileStat, 0, sizeof(struct fossilStat));
  rc = fossil_stat(zPath, &testFileStat, 0);
  fossil_print("  stat_rc                = %d\n", rc);
  sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", testFileStat.st_size);
  fossil_print("  stat_size              = %s\n", zBuf);
  if( g.db==0 ) sqlite3_open(":memory:", &g.db);
  z = db_text(0, "SELECT datetime(%lld, 'unixepoch')", testFileStat.st_mtime);
................................................................................
  fossil_print("  file_mode(RepoFILE)    = 0%o\n", file_mode(zPath,RepoFILE));
  fossil_print("  file_isfile(RepoFILE)  = %d\n", file_isfile(zPath,RepoFILE));
  fossil_print("  file_isfile_or_link    = %d\n", file_isfile_or_link(zPath));
  fossil_print("  file_islink            = %d\n", file_islink(zPath));
  fossil_print("  file_isexe(RepoFILE)   = %d\n", file_isexe(zPath,RepoFILE));
  fossil_print("  file_isdir(RepoFILE)   = %d\n", file_isdir(zPath,RepoFILE));
  fossil_print("  file_is_repository     = %d\n", file_is_repository(zPath));
  fossil_print("  file_is_reserved_name  = %d\n",
                                             file_is_reserved_name(zFull,-1));
  blob_reset(&x);
  if( reset ) resetStat();
}

/*
** COMMAND: test-file-environment
**
** Usage: %fossil test-file-environment FILENAME...
................................................................................
** Display the effective file handling subsystem "settings" and then
** display file system information about the files specified, if any.
**
** Options:
**
**     --allow-symlinks BOOLEAN     Temporarily turn allow-symlinks on/off
**     --open-config                Open the configuration database first.

**     --reset                      Reset cached stat() info for each file.
**     --root ROOT                  Use ROOT as the root of the checkout
**     --slash                      Trailing slashes, if any, are retained.
*/
void cmd_test_file_environment(void){
  int i;
  int slashFlag = find_option("slash",0,0)!=0;
  int resetFlag = find_option("reset",0,0)!=0;
  const char *zRoot = find_option("root",0,1);
  const char *zAllow = find_option("allow-symlinks",0,1);
  if( find_option("open-config", 0, 0)!=0 ){
    Th_OpenConfig(1);
  }
  db_find_and_open_repository(OPEN_ANY_SCHEMA|OPEN_OK_NOT_FOUND, 0);
  fossil_print("filenames_are_case_sensitive() = %d\n",
               filenames_are_case_sensitive());


  if( zAllow ){
    g.allowSymlinks = !is_false(zAllow);
  }
  if( zRoot==0 ) zRoot = g.zLocalRoot;
  fossil_print("db_allow_symlinks() = %d\n", db_allow_symlinks());
  fossil_print("local-root = [%s]\n", zRoot);
  for(i=2; i<g.argc; i++){
    char *z;
    emitFileStat(g.argv[i], slashFlag, resetFlag);
    z = file_canonical_name_dup(g.argv[i]);
    fossil_print("  file_canonical_name    = %s\n", z);
    fossil_print("  file_nondir_path       = ");
    if( fossil_strnicmp(zRoot,z,(int)strlen(zRoot))!=0 ){
      fossil_print("(--root is not a prefix of this file)\n");
    }else{
      int n = file_nondir_objects_on_path(zRoot, z);
      fossil_print("%.*s\n", n, z);
    }
    fossil_free(z);
  }
}

/*
** COMMAND: test-canonical-name
**
** Usage: %fossil test-canonical-name FILENAME...
................................................................................
  if( dryRunFlag!=0 ){
    fossil_print("dry-run: would have touched %d file(s)\n",
                 changeCount);
  }else{
    fossil_print("Touched %d file(s)\n", changeCount);
  }
}

/*
** If zFileName is not NULL and contains a '.', this returns a pointer
** to the position after the final '.', else it returns NULL. As a
** special case, if it ends with a period then a pointer to the
** terminating NUL byte is returned.
*/
const char * file_extension(const char *zFileName){
  const char * zExt = zFileName ? strrchr(zFileName, '.') : 0;
  return zExt ? &zExt[1] : 0;
}

/*
** Returns non-zero if the specified file name ends with any reserved name,
** e.g.: _FOSSIL_ or .fslckout.  Specifically, it returns 1 for exact match
** or 2 for a tail match on a longer file name.
**
** For the sake of efficiency, zFilename must be a canonical name, e.g. an
................................................................................
      if( 8==nFilename ) return 1;
      return zEnd[-9]=='/' ? 2 : gotSuffix;
    }
    case 'T':
    case 't':{
      if( nFilename<9 || zEnd[-9]!='.'
       || fossil_strnicmp(".fslckout", &zEnd[-9], 9) ){
        return 0;
      }
      if( 9==nFilename ) return 1;
      return zEnd[-10]=='/' ? 2 : gotSuffix;
    }
    default:{
      return 0;
    }
  }
}





















Changes to src/fileedit.c.

1631
1632
1633
1634
1635
1636
1637

1638
1639
1640
1641
1642
1643
1644
....
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
....
1703
1704
1705
1706
1707
1708
1709

1710


1711
1712
1713
1714
1715


1716
1717
1718
1719
1720
1721
1722
....
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752

1753
1754

1755
1756


1757
1758
1759
1760
1761
1762
1763
....
1977
1978
1979
1980
1981
1982
1983
1984
1985

1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996

1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
....
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
    }
    return;
  }

  db_begin_transaction();
  CheckinMiniInfo_init(&cimi);
  style_header("File Editor");

  /* As of this point, don't use return or fossil_fatal(). Write any
  ** error in (&err) and goto end_footer instead so that we can be
  ** sure to emit the error message, do any cleanup, and end the
  ** transaction cleanly.
  */
  {
    int isMissingArg = 0;
................................................................................

  /* The CSS for this page lives in a common file but much of it we
  ** don't want inadvertently being used by other pages. We don't
  ** have a common, page-specific container we can filter our CSS
  ** selectors, but we do have the BODY, which we can decorate with
  ** whatever CSS we wish...
  */
  style_emit_script_tag(0,0);
  CX("document.body.classList.add('fileedit');\n");
  style_emit_script_tag(1,0);
  
  /* Status bar */
  CX("<div id='fossil-status-bar' "
     "title='Status message area. Double-click to clear them.'>"
     "Status messages will go here.</div>\n"
     /* will be moved into the tab container via JS */);

................................................................................
  {
    CX("<div id='fileedit-tab-content' "
       "data-tab-parent='fileedit-tabs' "
       "data-tab-label='File Content' "
       "class='hidden'"
       ">");
    CX("<div class='flex-container flex-row child-gap-small'>");

    CX("<button class='fileedit-content-reload confirmer' "


       "title='Reload the file from the server, discarding "
       "any local edits. To help avoid accidental loss of "
       "edits, it requires confirmation (a second click) within "
       "a few seconds or it will not reload.'"
       ">Discard &amp; Reload</button>");


    style_select_list_int("select-font-size",
                          "editor_font_size", "Editor font size",
                          NULL/*tooltip*/,
                          100,
                          "100%", 100, "125%", 125,
                          "150%", 150, "175%", 175,
                          "200%", 200, NULL);
................................................................................
    CX("<button id='btn-preview-refresh' "
       "data-f-preview-from='fileContent' "
       /* ^^^ fossil.page[methodName]() OR text source elem ID,
      ** but we need a method in order to support clients swapping out
      ** the text editor with their own. */
       "data-f-preview-via='_postPreview' "
       /* ^^^ fossil.page[methodName](content, callback) */
       "data-f-preview-to='#fileedit-tab-preview-wrapper' "
       /* ^^^ dest elem ID */
       ">Refresh</button>");
    /* Toggle auto-update of preview when the Preview tab is selected. */
    style_labeled_checkbox("cb-preview-autoupdate",
                           NULL,

                           "Auto-refresh?",
                           "1", 1,

                           "If on, the preview will automatically "
                           "refresh when this tab is selected.");



    /* Default preview rendering mode selection... */
    previewRenderMode = zFileMime
      ? ajax_render_mode_for_mimetype(zFileMime)
      : AJAX_RENDER_GUESS;
    style_select_list_int("select-preview-mode",
                          "preview_render_mode",
................................................................................
       "is unspecified and may differ across environments. When "
       "committing or force-reloading a file, local edits to that "
       "file/check-in combination are discarded.</li>");
    CX("</ul>");
  }
  CX("</div>"/*#fileedit-tab-help*/);

  builtin_request_js("sbsdiff.js");
  style_emit_fossil_js_apis(0, "fetch", "dom", "tabs", "confirmer",

                            "storage", 0);
  builtin_fulfill_js_requests();
  /*
  ** Set up a JS-side mapping of the AJAX_RENDER_xyz values. This is
  ** used for dynamically toggling certain UI components on and off.
  ** Must come after window.fossil has been intialized and before
  ** fossil.page.fileedit.js. Potential TODO: move this into the
  ** window.fossil bootstrapping so that we don't have to "fulfill"
  ** the JS multiple times.
  */
  ajax_emit_js_preview_modes(1);

  builtin_request_js("fossil.page.fileedit.js");
  builtin_fulfill_js_requests();
  {
    /* Dynamically populate the editor, display any error in the err
    ** blob, and/or switch to tab #0, where the file selector
    ** lives. The extra C scopes here correspond to JS-level scopes,
    ** to improve grokability. */
    style_emit_script_tag(0,0);
    CX("\n(function(){\n");
    CX("try{\n");
    {
      char * zFirstLeafUuid = 0;
      CX("fossil.config['fileedit-glob'] = ");
      glob_render_json_to_cgi(fileedit_glob());
      CX(";\n");
................................................................................
      }
      CX("});\n")/*fossil.onPageLoad()*/;
    }
    CX("}catch(e){"
       "fossil.error(e); console.error('Exception:',e);"
       "}\n");
    CX("})();")/*anonymous function*/;
    style_emit_script_tag(1,0);
  }
  blob_reset(&err);
  CheckinMiniInfo_cleanup(&cimi);
  db_end_transaction(0);
  style_footer();
}







>







 







|

|







 







>
|
>
>
|


|
<
>
>







 







|



|
<
>
|
|
>
|
|
>
>







 







<
|
>
|
<









>







|







 







|






1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
....
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
....
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718

1719
1720
1721
1722
1723
1724
1725
1726
1727
....
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756

1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
....
1985
1986
1987
1988
1989
1990
1991

1992
1993
1994

1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
....
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
    }
    return;
  }

  db_begin_transaction();
  CheckinMiniInfo_init(&cimi);
  style_header("File Editor");
  style_emit_noscript_for_js_page();
  /* As of this point, don't use return or fossil_fatal(). Write any
  ** error in (&err) and goto end_footer instead so that we can be
  ** sure to emit the error message, do any cleanup, and end the
  ** transaction cleanly.
  */
  {
    int isMissingArg = 0;
................................................................................

  /* The CSS for this page lives in a common file but much of it we
  ** don't want inadvertently being used by other pages. We don't
  ** have a common, page-specific container we can filter our CSS
  ** selectors, but we do have the BODY, which we can decorate with
  ** whatever CSS we wish...
  */
  style_script_begin(__FILE__,__LINE__);
  CX("document.body.classList.add('fileedit');\n");
  style_script_end();
  
  /* Status bar */
  CX("<div id='fossil-status-bar' "
     "title='Status message area. Double-click to clear them.'>"
     "Status messages will go here.</div>\n"
     /* will be moved into the tab container via JS */);

................................................................................
  {
    CX("<div id='fileedit-tab-content' "
       "data-tab-parent='fileedit-tabs' "
       "data-tab-label='File Content' "
       "class='hidden'"
       ">");
    CX("<div class='flex-container flex-row child-gap-small'>");
    CX("<div class='input-with-label'>"
       "<button class='fileedit-content-reload confirmer' "
       ">Discard &amp; Reload</button>"
       "<div class='help-buttonlet'>"
       "Reload the file from the server, discarding "
       "any local edits. To help avoid accidental loss of "
       "edits, it requires confirmation (a second click) within "
       "a few seconds or it will not reload."

       "</div>"
       "</div>");
    style_select_list_int("select-font-size",
                          "editor_font_size", "Editor font size",
                          NULL/*tooltip*/,
                          100,
                          "100%", 100, "125%", 125,
                          "150%", 150, "175%", 175,
                          "200%", 200, NULL);
................................................................................
    CX("<button id='btn-preview-refresh' "
       "data-f-preview-from='fileContent' "
       /* ^^^ fossil.page[methodName]() OR text source elem ID,
      ** but we need a method in order to support clients swapping out
      ** the text editor with their own. */
       "data-f-preview-via='_postPreview' "
       /* ^^^ fossil.page[methodName](content, callback) */
       "data-f-preview-to='_previewTo' "
       /* ^^^ dest elem ID */
       ">Refresh</button>");
    /* Toggle auto-update of preview when the Preview tab is selected. */
    CX("<div class='input-with-label'>"

       "<input type='checkbox' value='1' "
       "id='cb-preview-autorefresh' checked>"
       "<label for='cb-preview-autorefresh'>Auto-refresh?</label>"
       "<div class='help-buttonlet'>"
       "If on, the preview will automatically "
       "refresh (if needed) when this tab is selected."
       "</div>"
       "</div>");

    /* Default preview rendering mode selection... */
    previewRenderMode = zFileMime
      ? ajax_render_mode_for_mimetype(zFileMime)
      : AJAX_RENDER_GUESS;
    style_select_list_int("select-preview-mode",
                          "preview_render_mode",
................................................................................
       "is unspecified and may differ across environments. When "
       "committing or force-reloading a file, local edits to that "
       "file/check-in combination are discarded.</li>");
    CX("</ul>");
  }
  CX("</div>"/*#fileedit-tab-help*/);


  builtin_fossil_js_bundle_or("fetch", "dom", "tabs", "confirmer",
                              "storage", "popupwidget", "copybutton",
                              "pikchr", 0);

  /*
  ** Set up a JS-side mapping of the AJAX_RENDER_xyz values. This is
  ** used for dynamically toggling certain UI components on and off.
  ** Must come after window.fossil has been intialized and before
  ** fossil.page.fileedit.js. Potential TODO: move this into the
  ** window.fossil bootstrapping so that we don't have to "fulfill"
  ** the JS multiple times.
  */
  ajax_emit_js_preview_modes(1);
  builtin_request_js("sbsdiff.js");
  builtin_request_js("fossil.page.fileedit.js");
  builtin_fulfill_js_requests();
  {
    /* Dynamically populate the editor, display any error in the err
    ** blob, and/or switch to tab #0, where the file selector
    ** lives. The extra C scopes here correspond to JS-level scopes,
    ** to improve grokability. */
    style_script_begin(__FILE__,__LINE__);
    CX("\n(function(){\n");
    CX("try{\n");
    {
      char * zFirstLeafUuid = 0;
      CX("fossil.config['fileedit-glob'] = ");
      glob_render_json_to_cgi(fileedit_glob());
      CX(";\n");
................................................................................
      }
      CX("});\n")/*fossil.onPageLoad()*/;
    }
    CX("}catch(e){"
       "fossil.error(e); console.error('Exception:',e);"
       "}\n");
    CX("})();")/*anonymous function*/;
    style_script_end();
  }
  blob_reset(&err);
  CheckinMiniInfo_cleanup(&cimi);
  db_end_transaction(0);
  style_footer();
}

Changes to src/finfo.c.

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
**
** Options:
**   -b|--brief           display a brief (one line / revision) summary
**   --case-sensitive B   Enable or disable case-sensitive filenames.  B is a
**                        boolean: "yes", "no", "true", "false", etc.
**   -l|--log             select log mode (the default)
**   -n|--limit N         Display the first N changes (default unlimited).
**                        N<=0 means no limit.
**   --offset P           skip P changes
**   -p|--print           select print mode
**   -r|--revision R      print the given revision (or ckout, if none is given)
**                        to stdout (only in print mode)
**   -s|--status          select status mode (print a status indicator for FILE)
**   -W|--width <num>     Width of lines (default is to auto-detect). Must be
**                        >22 or 0 (= no limit, resulting in a single line per
**                        entry).
**
** See also: [[artifact]], [[cat]], [[descendants]], [[info]], [[leaves]]
*/
void finfo_cmd(void){
  db_must_be_within_tree();
  if( find_option("status","s",0) ){
    Stmt q;







|





|
<
|







42
43
44
45
46
47
48
49
50
51
52
53
54
55

56
57
58
59
60
61
62
63
**
** Options:
**   -b|--brief           display a brief (one line / revision) summary
**   --case-sensitive B   Enable or disable case-sensitive filenames.  B is a
**                        boolean: "yes", "no", "true", "false", etc.
**   -l|--log             select log mode (the default)
**   -n|--limit N         Display the first N changes (default unlimited).
**                        N less than 0 means no limit.
**   --offset P           skip P changes
**   -p|--print           select print mode
**   -r|--revision R      print the given revision (or ckout, if none is given)
**                        to stdout (only in print mode)
**   -s|--status          select status mode (print a status indicator for FILE)
**   -W|--width N         Width of lines (default is to auto-detect). Must be

**                        more than 22 or else 0 to indicate no limit.
**
** See also: [[artifact]], [[cat]], [[descendants]], [[info]], [[leaves]]
*/
void finfo_cmd(void){
  db_must_be_within_tree();
  if( find_option("status","s",0) ){
    Stmt q;

Changes to src/forum.c.

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
..
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
...
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
...
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
...
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
...
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
...
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
...
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
....
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
....
1084
1085
1086
1087
1088
1089
1090

1091
1092
1093
1094
1095
1096
1097
....
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
....
1144
1145
1146
1147
1148
1149
1150

1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
....
1193
1194
1195
1196
1197
1198
1199

1200
1201
1202

1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
....
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
....
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
....
1321
1322
1323
1324
1325
1326
1327

1328
1329
1330
1331
1332
1333
1334
/*
** Default to using Markdown markup
*/
#define DEFAULT_FORUM_MIMETYPE  "text/x-markdown"

#if INTERFACE
/*
** Each instance of the following object represents a single message - 
** either the initial post, an edit to a post, a reply, or an edit to
** a reply.
*/
struct ForumEntry {
  int fpid;              /* rid for this entry */
  int fprev;             /* zero if initial entry.  non-zero if an edit */
  int firt;              /* This entry replies to firt */
  int mfirt;             /* Root in-reply-to */
  int nReply;            /* Number of replies to this entry */
  int sid;               /* Serial ID number */
  char *zUuid;           /* Artifact hash */
  ForumEntry *pLeaf;     /* Most recent edit for this entry */
  ForumEntry *pEdit;     /* This entry is an edit of pEdit */
  ForumEntry *pNext;     /* Next in chronological order */
  ForumEntry *pPrev;     /* Previous in chronological order */
  ForumEntry *pDisplay;  /* Next in display order */
  int nIndent;           /* Number of levels of indentation for this entry */



};

/*
** A single instance of the following tracks all entries for a thread.
*/
struct ForumThread {
  ForumEntry *pFirst;    /* First entry in chronological order */
  ForumEntry *pLast;     /* Last entry in chronological order */
  ForumEntry *pDisplay;  /* Entries in display order */
  ForumEntry *pTail;     /* Last on the display list */
  int mxIndent;          /* Maximum indentation level */
};
#endif /* INTERFACE */

/*
** Return true if the forum entry with the given rid has been
** subsequently edited.
*/
int forum_rid_has_been_edited(int rid){
  static Stmt q;
  int res;
  db_static_prepare(&q,
     "SELECT 1 FROM forumpost A, forumpost B"
................................................................................
  return res;
}

/*
** Delete a complete ForumThread and all its entries.
*/
static void forumthread_delete(ForumThread *pThread){
  ForumEntry *pEntry, *pNext;
  for(pEntry=pThread->pFirst; pEntry; pEntry = pNext){
    pNext = pEntry->pNext;
    fossil_free(pEntry->zUuid);

    fossil_free(pEntry);
  }
  fossil_free(pThread);
}

#if 0 /* not used */
/*
** Search a ForumEntry list forwards looking for the entry with fpid
*/
static ForumEntry *forumentry_forward(ForumEntry *p, int fpid){

  while( p && p->fpid!=fpid ) p = p->pNext;
  return p;
}
#endif

/*
** Search backwards for a ForumEntry
*/
static ForumEntry *forumentry_backward(ForumEntry *p, int fpid){

  while( p && p->fpid!=fpid ) p = p->pPrev;
  return p;
}

/*
** Add an entry to the display list
*/
static void forumentry_add_to_display(ForumThread *pThread, ForumEntry *p){
  if( pThread->pDisplay==0 ){
    pThread->pDisplay = p;
  }else{
    pThread->pTail->pDisplay = p;
  }
  pThread->pTail = p;
}

/*
** Extend the display list for pThread by adding all entries that
** reference fpid.  The first such entry will be no earlier then
** entry "p".
*/
static void forumthread_display_order(
  ForumThread *pThread,    /* The complete thread */
  ForumEntry *pBase        /* Add replies to this entry */
){
  ForumEntry *p;
  ForumEntry *pPrev = 0;

  for(p=pBase->pNext; p; p=p->pNext){
    if( p->fprev==0 && p->mfirt==pBase->fpid ){



      if( pPrev ){
        pPrev->nIndent = pBase->nIndent + 1;
        forumentry_add_to_display(pThread, pPrev);
        forumthread_display_order(pThread, pPrev);
      }
      pBase->nReply++;
      pPrev = p;

    }
  }
  if( pPrev ){
    pPrev->nIndent = pBase->nIndent + 1;
    if( pPrev->nIndent>pThread->mxIndent ) pThread->mxIndent = pPrev->nIndent;
    forumentry_add_to_display(pThread, pPrev);
    forumthread_display_order(pThread, pPrev);
  }
}

/*
** Construct a ForumThread object given the root record id.
*/
static ForumThread *forumthread_create(int froot, int computeHierarchy){
  ForumThread *pThread;
  ForumEntry *pEntry;

  Stmt q;
  int sid = 1;
  Bag seen = Bag_INIT;

  pThread = fossil_malloc( sizeof(*pThread) );
  memset(pThread, 0, sizeof(*pThread));
  db_prepare(&q,
     "SELECT fpid, firt, fprev, (SELECT uuid FROM blob WHERE rid=fpid)"
     "  FROM forumpost"
     " WHERE froot=%d ORDER BY fmtime",
     froot
  );
  while( db_step(&q)==SQLITE_ROW ){
    pEntry = fossil_malloc( sizeof(*pEntry) );
    memset(pEntry, 0, sizeof(*pEntry));
    pEntry->fpid = db_column_int(&q, 0);
    pEntry->firt = db_column_int(&q, 1);
    pEntry->fprev = db_column_int(&q, 2);
    pEntry->zUuid = fossil_strdup(db_column_text(&q,3));
    pEntry->mfirt = pEntry->firt;
    pEntry->sid = sid++;
    pEntry->pPrev = pThread->pLast;
    pEntry->pNext = 0;
    bag_insert(&seen, pEntry->fpid);
    if( pThread->pLast==0 ){
      pThread->pFirst = pEntry;
    }else{
      pThread->pLast->pNext = pEntry;
    }
    if( pEntry->firt && !bag_find(&seen,pEntry->firt) ){
      pEntry->firt = froot;
      pEntry->mfirt = froot;

    }



    pThread->pLast = pEntry;




  }
  db_finalize(&q);
  bag_clear(&seen);

  /* Establish which entries are the latest edit.  After this loop
  ** completes, entries that have non-NULL pLeaf should not be
  ** displayed.
  */


  for(pEntry=pThread->pFirst; pEntry; pEntry=pEntry->pNext){
    if( pEntry->fprev ){
      ForumEntry *pBase = 0, *p;
      p = forumentry_backward(pEntry->pPrev, pEntry->fprev);
      pEntry->pEdit = p;

      while( p ){
        pBase = p;
        p->pLeaf = pEntry;
        p = pBase->pEdit;
      }

      for(p=pEntry->pNext; p; p=p->pNext){
        if( p->mfirt==pEntry->fpid ) p->mfirt = pBase->fpid;
      }
    }
  }


  if( computeHierarchy ){
    /* Compute the hierarchical display order */
    pEntry = pThread->pFirst;
    pEntry->nIndent = 1;
    pThread->mxIndent = 1;
    forumentry_add_to_display(pThread, pEntry);
    forumthread_display_order(pThread, pEntry);
  }

  /* Return the result */
  return pThread;
}

/*
................................................................................
** This command is intended for testing an analysis only.
*/
void forumthread_cmd(void){
  int fpid;
  int froot;
  const char *zName;
  ForumThread *pThread;
  ForumEntry *p;

  db_find_and_open_repository(0,0);
  verify_all_options();
  if( g.argc==2 ){
    forum_thread_list();
    return;
  }
................................................................................
  fossil_print("fpid  = %d\n", fpid);
  fossil_print("froot = %d\n", froot);
  pThread = forumthread_create(froot, 1);
  fossil_print("Chronological:\n");
  fossil_print(
/* 0         1         2         3         4         5         6         7    */
/*  123456789 123456789 123456789 123456789 123456789 123456789 123456789 123 */
  " sid      fpid      firt     fprev     mfirt     pLeaf  nReply  hash\n");
  for(p=pThread->pFirst; p; p=p->pNext){
    fossil_print("%4d %9d %9d %9d %9d %9d  %6d  %8.8s\n", p->sid,
       p->fpid, p->firt, p->fprev, p->mfirt, p->pLeaf ? p->pLeaf->fpid : 0,
       p->nReply, p->zUuid);

  }
  fossil_print("\nDisplay\n");
  for(p=pThread->pDisplay; p; p=p->pDisplay){
    fossil_print("%*s", (p->nIndent-1)*3, "");
    if( p->pLeaf ){
      fossil_print("%d->%d\n", p->fpid, p->pLeaf->fpid);
    }else{
      fossil_print("%d\n", p->fpid);
    }
  }
  forumthread_delete(pThread);
}

................................................................................
      @ <h1>%h(zTitle)</h1>
    }else{
      @ <h1><i>Deleted</i></h1>
    }
  }
  if( zContent && zContent[0] ){
    Blob x;


    if( bScroll ){
      @ <div class='forumPostBody'>
    }else{
      @ <div class='forumPostFullBody'>
    }
    blob_init(&x, 0, 0);
    blob_append(&x, zContent, -1);
    safe_html_context(DOCSRC_FORUM);








    wiki_render_by_mimetype(&x, zMimetype);



    blob_reset(&x);
    @ </div>
  }else{
    @ <i>Deleted</i>
  }
  if( zClass ){
    @ </div>
  }
}

/*
** Generate the buttons in the display that allow a forum supervisor to
** mark a user as trusted.  Only do this if:
**
**   (1)  The poster is an individual, not a special user like "anonymous"
**   (2)  The current user has Forum Supervisor privilege
*/
static void generateTrustControls(Manifest *pPost){
  if( !g.perm.AdminForum ) return;
  if( login_is_special(pPost->zUser) ) return;
  @ <br>
  @ <label><input type="checkbox" name="trust">
  @ Trust user "%h(pPost->zUser)"
  @ so that future posts by "%h(pPost->zUser)" do not require moderation.
  @ </label>
  @ <input type="hidden" name="trustuser" value="%h(pPost->zUser)">
}

/*
** Compute a display name from a login name.
**
** If the input login is found in the USER table, then check the USER.INFO
** field to see if it has display-name followed by an email address.
** If it does, that becomes the new display name.  If not, let the display
** name just be the login.
**
** Space to hold the returned name is obtained from fossil_strdup() or
** mprintf() and should be freed by the caller.
*/
char *display_name_from_login(const char *zLogin){
  static Stmt q;
  char *zResult;
  db_static_prepare(&q,
     "SELECT display_name(info) FROM user WHERE login=$login"
  );
  db_bind_text(&q, "$login", zLogin);
  if( db_step(&q)==SQLITE_ROW && db_column_type(&q,0)==SQLITE_TEXT ){
................................................................................
    zResult = fossil_strdup(zLogin);
  }
  db_reset(&q);
  return zResult;
}

/*
** Display all posts in a forum thread in chronological order







*/

















static void forum_display_chronological(int froot, int target, int bRawMode){
  ForumThread *pThread = forumthread_create(froot, 0);
  ForumEntry *p;
  int notAnon = login_is_individual();
  char cMode = bRawMode ? 'r' : 'c';
  for(p=pThread->pFirst; p; p=p->pNext){










    char *zDate;
    Manifest *pPost;


    int isPrivate;        /* True for posts awaiting moderation */
    int sameUser;         /* True if author is also the reader */

    const char *zUuid;
    char *zDisplayName;   /* The display name */
    int sid;


    pPost = manifest_get(p->fpid, CFTYPE_FORUM, 0);
    if( pPost==0 ) continue;
    if( p->fpid==target ){
      @ <div id="forum%d(p->fpid)" class="forumTime forumSel">
    }else if( p->pLeaf!=0 ){
      @ <div id="forum%d(p->fpid)" class="forumTime forumObs">












    }else{
      @ <div id="forum%d(p->fpid)" class="forumTime">

    }


    if( pPost->zThreadTitle ){
      @ <h1>%h(pPost->zThreadTitle)</h1>
    }













    zDate = db_text(0, "SELECT datetime(%.17g)", pPost->rDate);
    zDisplayName = display_name_from_login(pPost->zUser);
    sid = p->pEdit ? p->pEdit->sid : p->sid;




    @ <h3 class='forumPostHdr'>(%d(sid)) By %h(zDisplayName) on %h(zDate)
    fossil_free(zDisplayName);
















    fossil_free(zDate);
    if( p->pEdit ){
      @ edit of %z(href("%R/forumpost/%S?t=%c",p->pEdit->zUuid,cMode))\
      @ %d(p->pEdit->sid)</a>
    }


    if( g.perm.Debug ){
      @ <span class="debug">\
      @ <a href="%R/artifact/%h(p->zUuid)">(artifact-%d(p->fpid))</a></span>
    }


    if( p->firt ){
      ForumEntry *pIrt = p->pPrev;
      while( pIrt && pIrt->fpid!=p->firt ) pIrt = pIrt->pPrev;
      if( pIrt ){
        @ in reply to %z(href("%R/forumpost/%S?t=%c",pIrt->zUuid,cMode))\
        @ %d(pIrt->sid)</a>


      }

    }
    zUuid = p->zUuid;


    if( p->pLeaf ){
      @ updated by %z(href("%R/forumpost/%S?t=%c",p->pLeaf->zUuid,cMode))\
      @ %d(p->pLeaf->sid)</a>
      zUuid = p->pLeaf->zUuid;

    }
    if( p->fpid!=target ){



      @ %z(href("%R/forumpost/%S?t=%c",zUuid,cMode))[link]</a>
    }


    if( !bRawMode ){
      @ %z(href("%R/forumpost/%S?raw",zUuid))[source]</a>
    }




    isPrivate = content_is_private(p->fpid);

    sameUser = notAnon && fossil_strcmp(pPost->zUser, g.zLogin)==0;
    @ </h3>


    if( isPrivate && !g.perm.ModForum && !sameUser ){
      @ <p><span class="modpending">Awaiting Moderator Approval</span></p>
    }else{
      const char *zMimetype;
      if( bRawMode ){

        zMimetype = "text/plain";
      }else if( p->pLeaf!=0 ){
        zMimetype = "text/plain";
      }else{
        zMimetype = pPost->zMimetype;
      }
      forum_render(0, zMimetype, pPost->zWiki, 0, 1);
    }





    if( g.perm.WrForum && p->pLeaf==0 ){
      int sameUser = login_is_individual()
                     && fossil_strcmp(pPost->zUser, g.zLogin)==0;
      @ <div><form action="%R/forumedit" method="POST">
      @ <input type="hidden" name="fpid" value="%s(p->zUuid)">
      if( !isPrivate ){
        /* Reply and Edit are only available if the post has already
        ** been approved */
        @ <input type="submit" name="reply" value="Reply">
        if( g.perm.Admin || sameUser ){
          @ <input type="submit" name="edit" value="Edit">
          @ <input type="submit" name="nullout" value="Delete">
        }
      }else if( g.perm.ModForum ){
        /* Provide moderators with moderation buttons for posts that
        ** are pending moderation */

        @ <input type="submit" name="approve" value="Approve">
        @ <input type="submit" name="reject" value="Reject">
        generateTrustControls(pPost);







      }else if( sameUser ){
        /* A post that is pending moderation can be deleted by the
        ** person who originally submitted the post */

        @ <input type="submit" name="reject" value="Delete">
      }
      @ </form></div>
    }
    manifest_destroy(pPost);
    @ </div>
  }


















































































































  /* Undocumented "threadtable" query parameter causes thread table
  ** to be displayed for debugging purposes.
  */
  if( PB("threadtable") ){
    @ <hr>
    @ <table border="1" cellpadding="3" cellspacing="0">
    @ <tr><th>sid<th>fpid<th>firt<th>fprev<th>mfirt<th>pLeaf<th>nReply<th>hash


    for(p=pThread->pFirst; p; p=p->pNext){
      @ <tr><td>%d(p->sid)<td>%d(p->fpid)<td>%d(p->firt)\
      @ <td>%d(p->fprev)<td>%d(p->mfirt)\
      @ <td>%d(p->pLeaf?p->pLeaf->fpid:0)<td>%d(p->nReply)\






      @ <td>%S(p->zUuid)</tr>
    }
    @ </table>
  }

  forumthread_delete(pThread);
}
/*
** Display all the edit history of post "target".
*/
static void forum_display_history(int froot, int target, int bRawMode){
  ForumThread *pThread = forumthread_create(froot, 0);
  ForumEntry *p;
  int notAnon = login_is_individual();
  char cMode = bRawMode ? 'r' : 'c';
  ForumEntry *pLeaf = 0;
  int cnt = 0;
  for(p=pThread->pFirst; p; p=p->pNext){
    if( p->fpid==target ){
      pLeaf = p->pLeaf ? p->pLeaf : p;
      break;
    }
  }
  for(p=pThread->pFirst; p; p=p->pNext){
    char *zDate;
    Manifest *pPost;
    int isPrivate;        /* True for posts awaiting moderation */
    int sameUser;         /* True if author is also the reader */
    const char *zUuid;
    char *zDisplayName;   /* The display name */

    if( p->fpid!=pLeaf->fpid && p->pLeaf!=pLeaf ) continue;
    cnt++;
    pPost = manifest_get(p->fpid, CFTYPE_FORUM, 0);
    if( pPost==0 ) continue;
    @ <div id="forum%d(p->fpid)" class="forumTime">
    zDate = db_text(0, "SELECT datetime(%.17g)", pPost->rDate);
    zDisplayName = display_name_from_login(pPost->zUser);
    @ <h3 class='forumPostHdr'>(%d(p->sid)) By %h(zDisplayName) on %h(zDate)
    fossil_free(zDisplayName);
    fossil_free(zDate);
    if( g.perm.Debug ){
      @ <span class="debug">\
      @ <a href="%R/artifact/%h(p->zUuid)">(artifact-%d(p->fpid))</a></span>
    }
    if( p->firt && cnt==1 ){
      ForumEntry *pIrt = p->pPrev;
      while( pIrt && pIrt->fpid!=p->firt ) pIrt = pIrt->pPrev;
      if( pIrt ){
        @ in reply to %z(href("%R/forumpost/%S?t=%c",pIrt->zUuid,cMode))\
        @ %d(pIrt->sid)</a>
      }
    }
    zUuid = p->zUuid;
    @ %z(href("%R/forumpost/%S?t=c",zUuid))[link]</a>
    if( !bRawMode ){
      @ %z(href("%R/forumpost/%S?raw",zUuid))[source]</a>
    }
    isPrivate = content_is_private(p->fpid);
    sameUser = notAnon && fossil_strcmp(pPost->zUser, g.zLogin)==0;
    @ </h3>
    if( isPrivate && !g.perm.ModForum && !sameUser ){
      @ <p><span class="modpending">Awaiting Moderator Approval</span></p>
    }else{
      forum_render(0, bRawMode?"text/plain":pPost->zMimetype, pPost->zWiki,
                   0, 1);
    }
    if( g.perm.WrForum && p->pLeaf==0 ){
      int sameUser = login_is_individual()
                     && fossil_strcmp(pPost->zUser, g.zLogin)==0;
      @ <div><form action="%R/forumedit" method="POST">
      @ <input type="hidden" name="fpid" value="%s(p->zUuid)">
      if( !isPrivate ){
        /* Reply and Edit are only available if the post has already
        ** been approved */
        @ <input type="submit" name="reply" value="Reply">
        if( g.perm.Admin || sameUser ){
          @ <input type="submit" name="edit" value="Edit">
          @ <input type="submit" name="nullout" value="Delete">
        }
      }else if( g.perm.ModForum ){
        /* Provide moderators with moderation buttons for posts that
        ** are pending moderation */
        @ <input type="submit" name="approve" value="Approve">
        @ <input type="submit" name="reject" value="Reject">
        generateTrustControls(pPost);
      }else if( sameUser ){
        /* A post that is pending moderation can be deleted by the
        ** person who originally submitted the post */
        @ <input type="submit" name="reject" value="Delete">
      }
      @ </form></div>
    }
    manifest_destroy(pPost);
    @ </div>
  }
  forumthread_delete(pThread);
}

/*
** Display all messages in a forumthread with indentation.
*/
static int forum_display_hierarchical(int froot, int target){
  ForumThread *pThread;
  ForumEntry *p;
  Manifest *pPost, *pOPost;
  int fpid;
  const char *zUuid;
  char *zDate;
  const char *zSel;
  int notAnon = login_is_individual();
  int iIndentScale = 4;

  pThread = forumthread_create(froot, 1);
  for(p=pThread->pFirst; p; p=p->pNext){
    if( p->fpid==target ){
      while( p->pEdit ) p = p->pEdit;
      target = p->fpid;
      break;
    }
  }
  while( iIndentScale>1 && iIndentScale*pThread->mxIndent>25 ){
    iIndentScale--;
  }
  for(p=pThread->pDisplay; p; p=p->pDisplay){
    int isPrivate;         /* True for posts awaiting moderation */
    int sameUser;          /* True if reader is also the poster */
    char *zDisplayName;    /* User name to be displayed */
    pOPost = manifest_get(p->fpid, CFTYPE_FORUM, 0);
    if( p->pLeaf ){
      fpid = p->pLeaf->fpid;
      zUuid = p->pLeaf->zUuid;
      pPost = manifest_get(fpid, CFTYPE_FORUM, 0);
    }else{
      fpid = p->fpid;
      zUuid = p->zUuid;
      pPost = pOPost;
    }
    zSel = p->fpid==target ? " forumSel" : "";
    if( p->nIndent==1 ){
      @ <div id='forum%d(fpid)' class='forumHierRoot%s(zSel)'>
    }else{
      @ <div id='forum%d(fpid)' class='forumHier%s(zSel)' \
      @ style='margin-left: %d((p->nIndent-1)*iIndentScale)ex;'>
    }
    if( pPost==0 ) continue;
    if( pPost->zThreadTitle ){
      @ <h1>%h(pPost->zThreadTitle)</h1>
    }
    zDate = db_text(0, "SELECT datetime(%.17g)", pOPost->rDate);
    zDisplayName = display_name_from_login(pOPost->zUser);
    @ <h3 class='forumPostHdr'>\
    @ (%d(p->sid)) By %h(zDisplayName) on %h(zDate)
    fossil_free(zDisplayName);
    fossil_free(zDate);
    if( g.perm.Debug ){
      @ <span class="debug">\
      @ <a href="%R/artifact/%h(p->zUuid)">(artifact-%d(p->fpid))</a></span>
    }
    if( p->pLeaf ){
      zDate = db_text(0, "SELECT datetime(%.17g)", pPost->rDate);
      if( fossil_strcmp(pOPost->zUser,pPost->zUser)==0 ){
        @ and edited on %h(zDate)
      }else{
        @ as edited by %h(pPost->zUser) on %h(zDate)
      }
      fossil_free(zDate);
      if( g.perm.Debug ){
        @ <span class="debug">\
        @ <a href="%R/artifact/%h(p->pLeaf->zUuid)">\
        @ (artifact-%d(p->pLeaf->fpid))</a></span>
      }
      @ %z(href("%R/forumpost/%S?t=y",p->zUuid))[history]</a>
      manifest_destroy(pOPost);
    }
    if( fpid!=target ){
      @ %z(href("%R/forumpost/%S",zUuid))[link]</a>
    }
    @ %z(href("%R/forumpost/%S?raw",zUuid))[source]</a>
    if( p->firt ){
      ForumEntry *pIrt = p->pPrev;
      while( pIrt && pIrt->fpid!=p->mfirt ) pIrt = pIrt->pPrev;
      if( pIrt ){
        @ in reply to %z(href("%R/forumpost/%S?t=h",pIrt->zUuid))\
        @ %d(pIrt->sid)</a>
      }
    }
    @ </h3>
    isPrivate = content_is_private(fpid);
    sameUser = notAnon && fossil_strcmp(pPost->zUser, g.zLogin)==0;
    if( isPrivate && !g.perm.ModForum && !sameUser ){
      @ <p><span class="modpending">Awaiting Moderator Approval</span></p>
    }else{
      forum_render(0, pPost->zMimetype, pPost->zWiki, 0, 1);
    }
    if( g.perm.WrForum ){
      @ <div><form action="%R/forumedit" method="POST">
      @ <input type="hidden" name="fpid" value="%s(zUuid)">
      if( !isPrivate ){
        /* Reply and Edit are only available if the post has already
        ** been approved */
        @ <input type="submit" name="reply" value="Reply">
        if( g.perm.Admin || sameUser ){
          @ <input type="submit" name="edit" value="Edit">
          @ <input type="submit" name="nullout" value="Delete">
        }
      }else if( g.perm.ModForum ){
        /* Provide moderators with moderation buttons for posts that
        ** are pending moderation */
        @ <input type="submit" name="approve" value="Approve">
        @ <input type="submit" name="reject" value="Reject">
        generateTrustControls(pPost);
      }else if( sameUser ){
        /* A post that is pending moderation can be deleted by the
        ** person who originally submitted the post */
        @ <input type="submit" name="reject" value="Delete">
      }
      @ </form></div>
    }
    manifest_destroy(pPost);
    @ </div>
  }
  forumthread_delete(pThread);
  return target;
}

/*
** Emits all JS code required by /forumpost.



*/
static void forumpost_emit_page_js(){
  static int once = 0;
  if(0==once){
    once = 1;
    style_emit_script_fossil_bootstrap(1);
    builtin_request_js("forum.js");
    builtin_request_js("fossil.dom.js");

    builtin_request_js("fossil.page.forumpost.js");
  }
}

/*
** WEBPAGE: forumpost
**
** Show a single forum posting. The posting is shown in context with
** it's entire thread.  The selected posting is enclosed within
** <div class='forumSel'>...</div>.  Javascript is used to move the
** selected posting into view after the page loads.
**
** Query parameters:
**
**   name=X        REQUIRED.  The hash of the post to display
**   t=MODE        Display mode.
**                   'c' for chronological
**                   'h' for hierarchical
**                   'a' for automatic
**                   'r' for raw
**                   'y' for history of post X only
**   raw           If present, show only the post specified and

**                 show its original unformatted source text.




*/
void forumpost_page(void){
  forumthread_page();
}

/*
** Add an appropriate style_header() to include title of the
** given forum post.
*/
static int forumthread_page_header(int froot, int fpid){
  char *zThreadTitle = 0;

  zThreadTitle = db_text("",
    "SELECT"
    " substr(event.comment,instr(event.comment,':')+2)"
    " FROM forumpost, event"
    " WHERE event.objid=forumpost.fpid"
    "   AND forumpost.fpid=%d;",
    fpid
  );
  style_header("%s%s", zThreadTitle, zThreadTitle[0] ? "" : "Forum");
  fossil_free(zThreadTitle);
  return 0;
}

/*
** WEBPAGE: forumthread
**
** Show all forum messages associated with a particular message thread.
** The result is basically the same as /forumpost except that none of
** the postings in the thread are selected.
**
** Query parameters:
**
**   name=X        REQUIRED.  The hash of any post of the thread.
**   t=MODE        Display mode. MODE is...
**                   'c' for chronological, or
**                   'h' for hierarchical, or
**                   'a' for automatic, or
**                   'r' for raw.
**   raw           Show only the post given by name= and show it unformatted
**   hist          Show only the edit history for the name= post
*/
void forumthread_page(void){
  int fpid;
  int froot;

  const char *zName = P("name");
  const char *zMode = PD("t","a");
  int bRaw = PB("raw");



  login_check_credentials();
  if( !g.perm.RdForum ){
    login_needed(g.anon.RdForum);
    return;
  }
  if( zName==0 ){
    webpage_error("Missing \"name=\" query parameter");
................................................................................
    webpage_error("Unknown or ambiguous forum id: \"%s\"", zName);
  }
  froot = db_int(0, "SELECT froot FROM forumpost WHERE fpid=%d", fpid);
  if( froot==0 ){
    webpage_error("Not a forum post: \"%s\"", zName);
  }
  if( fossil_strcmp(g.zPath,"forumthread")==0 ) fpid = 0;
  if( zMode[0]=='a' ){

    if( cgi_from_mobile() ){
      zMode = "c";  /* Default to chronological on mobile */






    }else{
      zMode = "h";







    }






  }
  if( zMode[0]!='y' ){
    forumthread_page_header(froot, fpid);
  }
  if( bRaw && fpid ){
    Manifest *pPost;
    pPost = manifest_get(fpid, CFTYPE_FORUM, 0);
    if( pPost==0 ){
      @ <p>No such forum post: %h(zName)
    }else{
      int isPrivate = content_is_private(fpid);
      int notAnon = login_is_individual();
      int sameUser = notAnon && fossil_strcmp(pPost->zUser, g.zLogin)==0;
      if( isPrivate && !g.perm.ModForum && !sameUser ){
        @ <p><span class="modpending">Awaiting Moderator Approval</span></p>
      }else{
        forum_render(0, "text/plain", pPost->zWiki, 0, 0);
      }
      manifest_destroy(pPost);














    }
  }else if( zMode[0]=='c' ){

    style_submenu_element("Hierarchical", "%R/%s/%s?t=h", g.zPath, zName);
    style_submenu_element("Unformatted", "%R/%s/%s?t=r", g.zPath, zName);
    forum_display_chronological(froot, fpid, 0);
  }else if( zMode[0]=='r' ){
    style_submenu_element("Chronological", "%R/%s/%s?t=c", g.zPath, zName);
    style_submenu_element("Hierarchical", "%R/%s/%s?t=h", g.zPath, zName);
    forum_display_chronological(froot, fpid, 1);
  }else if( zMode[0]=='y' ){
    style_header("Edit History Of A Forum Post");
    style_submenu_element("Complete Thread", "%R/%s/%s?t=a", g.zPath, zName);
    forum_display_history(froot, fpid, 1);
  }else{
    style_submenu_element("Chronological", "%R/%s/%s?t=c", g.zPath, zName);
    style_submenu_element("Unformatted", "%R/%s/%s?t=r", g.zPath, zName);
    forum_display_hierarchical(froot, fpid);

  }
  forumpost_emit_page_js();











  style_footer();
}

/*
** Return true if a forum post should be moderated.
*/
static int forum_need_moderation(void){
................................................................................
    iBasis = iInReplyTo;
  }
  webpage_assert( (zTitle==0)+(iInReplyTo==0)==1 );
  blob_init(&x, 0, 0);
  zDate = date_in_standard_format("now");
  blob_appendf(&x, "D %s\n", zDate);
  fossil_free(zDate);
  zG = db_text(0, 
     "SELECT uuid FROM blob, forumpost"
     " WHERE blob.rid==forumpost.froot"
     "   AND forumpost.fpid=%d", iBasis);
  if( zG ){
    blob_appendf(&x, "G %s\n", zG);
    fossil_free(zG);
  }
................................................................................
    return 1;
  }
}

/*
** Paint the form elements for entering a Forum post
*/
static void forum_entry_widget(
  const char *zTitle,
  const char *zMimetype,
  const char *zContent
){
  if( zTitle ){
    @ Title: <input type="input" name="title" value="%h(zTitle)" size="50"
    @ maxlength="125"><br>
................................................................................
  @ <form action="%R/login" method="POST">
  @ <input type="hidden" name="g" value="%s(zGoto)">
  @ <input type="hidden" name="noanon" value="1">
  @ <input type="submit" value="Login">
  @ </form>
  @ <td>Log into an existing account
  @ </table>

  style_footer();
  fossil_free(zGoto);
}

/*
** Write the "From: USER" line on the webpage.
*/
................................................................................
    @ <h1>Preview:</h1>
    forum_render(zTitle, zMimetype, zContent, "forumEdit", 1);
  }
  style_header("New Forum Thread");
  @ <form action="%R/forume1" method="POST">
  @ <h1>New Thread:</h1>
  forum_from_line();
  forum_entry_widget(zTitle, zMimetype, zContent);
  @ <input type="submit" name="preview" value="Preview">
  if( P("preview") && !whitespace_only(zContent) ){
    @ <input type="submit" name="submit" value="Submit">
  }else{
    @ <input type="submit" name="submit" value="Submit" disabled>
  }
  if( g.perm.Debug ){
................................................................................
    @ <br><label><input type="checkbox" name="domod" %s(PCK("domod"))> \
    @ Require moderator approval</label>
    @ <br><label><input type="checkbox" name="showqp" %s(PCK("showqp"))> \
    @ Show query parameters</label>
    @ </div>
  }
  @ </form>

  style_footer();
}

/*
** WEBPAGE: forume2
**
** Edit an existing forum message.
** Query parameters:
**
**   fpid=X        Hash of the post to be editted.  REQUIRED
*/
void forumedit_page(void){
  int fpid;
  int froot;
  Manifest *pPost = 0;
  Manifest *pRootPost = 0;
  const char *zMimetype = 0;
................................................................................
    if( P("approve") ){
      const char *zUserToTrust;
      moderation_approve('f', fpid);
      if( g.perm.AdminForum
       && PB("trust")
       && (zUserToTrust = P("trustuser"))!=0
      ){

        db_multi_exec("UPDATE user SET cap=cap||'4' "
                      "WHERE login=%Q AND cap NOT GLOB '*4*'",
                      zUserToTrust);

      }
      cgi_redirectf("%R/forumpost/%S",P("fpid"));
      return;
    }
    if( P("reject") ){
      char *zParent = 
        db_text(0,
          "SELECT uuid FROM forumpost, blob"
          " WHERE forumpost.fpid=%d AND blob.rid=forumpost.firt",
          fpid
        );
      moderation_disapprove(fpid);
      if( zParent ){
................................................................................
      forum_render(zTitle, zMimetype, zContent,"forumEdit", 1);
    }
    @ <h2>Revised Message:</h2>
    @ <form action="%R/forume2" method="POST">
    @ <input type="hidden" name="fpid" value="%h(P("fpid"))">
    @ <input type="hidden" name="edit" value="1">
    forum_from_line();
    forum_entry_widget(zTitle, zMimetype, zContent);
  }else{
    /* Reply */
    char *zDisplayName;
    zMimetype = PD("mimetype",DEFAULT_FORUM_MIMETYPE);
    zContent = PDT("content","");
    style_header("Reply");
    if( pRootPost->zThreadTitle ){
................................................................................
      forum_render(0, zMimetype,zContent, "forumEdit", 1);
    }
    @ <h2>Enter Reply:</h2>
    @ <form action="%R/forume2" method="POST">
    @ <input type="hidden" name="fpid" value="%h(P("fpid"))">
    @ <input type="hidden" name="reply" value="1">
    forum_from_line();
    forum_entry_widget(0, zMimetype, zContent);
  }
  if( !isDelete ){
    @ <input type="submit" name="preview" value="Preview">
  }
  @ <input type="submit" name="cancel" value="Cancel">
  if( (P("preview") && !whitespace_only(zContent)) || isDelete ){
    @ <input type="submit" name="submit" value="Submit">
................................................................................
    @ <br><label><input type="checkbox" name="domod" %s(PCK("domod"))> \
    @ Require moderator approval</label>
    @ <br><label><input type="checkbox" name="showqp" %s(PCK("showqp"))> \
    @ Show query parameters</label>
    @ </div>
  }
  @ </form>

  style_footer();
}

/*
** WEBPAGE: forummain
** WEBPAGE: forum
**







|



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






|
|
|
|





|







 







|
|
|
|
>
|




<

|

<
>



<


|

<
>





|

|










|
|



|

|
|
>

<
>
>
>
|
|
|
|
|
<
|
>





|









|
>


<
>



|





|
|
|
|
|
|
|
|
|
|
<

|

|

<
<
<
>
|
>
>
>
|
>
>
>
>
|
<
<
|
<
<
<
<
>
>
|
|
|
<
|
>
|
|
|
|
<
>
|
|



>



|
|

|
|







 







|







 







|

|
|
|
>




|
|







 







>
>








>
>
>
>
>
>
>
>

>
>
>










<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<











|







 







|
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
<
<
<
>
>
>
>
>
>
>
>
>
>
|
<
>
>
|
|
>
|
<
<

>
|
<
<
<
<
<
>
>
>
>
>
>
>
>
>
>
>
>

<
>

>
>
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
>
>
>
>
|
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

<
<
<
|
>
>




>
>
|
<
<
<
|
|
>
>

>

<
>
>
|
|
|
<
>

<
>
>
>
|

>
>
|
|

>
>
>
>
|
>
|
<
>
>
|
|
|
<
<
>
|
<
<
|
|
|
|
|
>
>
>
>
>
|
<
<


|
|
<

|




|
|
>


<
>
>
>
>
>
>
>
|
<
<
>




<



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
<



<
>
>

|
<
<
>
>
>
>
>
>





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

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

<
>
>
>

|
<
<
<
<
<
<
>
|
|
|
<




|





|
|
|
|
|
|
<
|
>
|
>
>
>
>





<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










|
|
|
|
|
|
|




>



>
>
>







 







<
>
|
|
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>

>
>
>
>
>
>
|
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>

<
>
>
>
>
>
>
>
>
>
>
>







 







|







 







|







 







>







 







|







 







>









|







 







>



>





|







 







|







 







|







 







>







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
..
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
...
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
...
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
...
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
...
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
...
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
...
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
....
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
....
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
....
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
....
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
....
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
....
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
....
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
....
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
/*
** Default to using Markdown markup
*/
#define DEFAULT_FORUM_MIMETYPE  "text/x-markdown"

#if INTERFACE
/*
** Each instance of the following object represents a single message -
** either the initial post, an edit to a post, a reply, or an edit to
** a reply.
*/
struct ForumPost {
  int fpid;              /* rid for this post */
  int sid;               /* Serial ID number */
  int rev;               /* Revision number */
  char *zUuid;           /* Artifact hash */
  char *zDisplayName;    /* Name of user who wrote this post */
  double rDate;          /* Date for this post */
  ForumPost *pIrt;       /* This post replies to pIrt */
  ForumPost *pEditHead;  /* Original, unedited post */
  ForumPost *pEditTail;  /* Most recent edit for this post */
  ForumPost *pEditNext;  /* This post is edited by pEditNext */
  ForumPost *pEditPrev;  /* This post is an edit of pEditPrev */
  ForumPost *pNext;      /* Next in chronological order */
  ForumPost *pPrev;      /* Previous in chronological order */
  ForumPost *pDisplay;   /* Next in display order */
  int nEdit;             /* Number of edits to this post */
  int nIndent;           /* Number of levels of indentation for this post */
};

/*
** A single instance of the following tracks all entries for a thread.
*/
struct ForumThread {
  ForumPost *pFirst;     /* First post in chronological order */
  ForumPost *pLast;      /* Last post in chronological order */
  ForumPost *pDisplay;   /* Entries in display order */
  ForumPost *pTail;      /* Last on the display list */
  int mxIndent;          /* Maximum indentation level */
};
#endif /* INTERFACE */

/*
** Return true if the forum post with the given rid has been
** subsequently edited.
*/
int forum_rid_has_been_edited(int rid){
  static Stmt q;
  int res;
  db_static_prepare(&q,
     "SELECT 1 FROM forumpost A, forumpost B"
................................................................................
  return res;
}

/*
** Delete a complete ForumThread and all its entries.
*/
static void forumthread_delete(ForumThread *pThread){
  ForumPost *pPost, *pNext;
  for(pPost=pThread->pFirst; pPost; pPost = pNext){
    pNext = pPost->pNext;
    fossil_free(pPost->zUuid);
    fossil_free(pPost->zDisplayName);
    fossil_free(pPost);
  }
  fossil_free(pThread);
}


/*
** Search a ForumPost list forwards looking for the post with fpid
*/

static ForumPost *forumpost_forward(ForumPost *p, int fpid){
  while( p && p->fpid!=fpid ) p = p->pNext;
  return p;
}


/*
** Search backwards for a ForumPost
*/

static ForumPost *forumpost_backward(ForumPost *p, int fpid){
  while( p && p->fpid!=fpid ) p = p->pPrev;
  return p;
}

/*
** Add a post to the display list
*/
static void forumpost_add_to_display(ForumThread *pThread, ForumPost *p){
  if( pThread->pDisplay==0 ){
    pThread->pDisplay = p;
  }else{
    pThread->pTail->pDisplay = p;
  }
  pThread->pTail = p;
}

/*
** Extend the display list for pThread by adding all entries that
** reference fpid.  The first such post will be no earlier then
** post "p".
*/
static void forumthread_display_order(
  ForumThread *pThread,    /* The complete thread */
  ForumPost *pBase         /* Add replies to this post */
){
  ForumPost *p;
  ForumPost *pPrev = 0;
  ForumPost *pBaseIrt;
  for(p=pBase->pNext; p; p=p->pNext){

    if( !p->pEditPrev && p->pIrt ){
      pBaseIrt = p->pIrt->pEditHead ? p->pIrt->pEditHead : p->pIrt;
      if( pBaseIrt==pBase ){
        if( pPrev ){
          pPrev->nIndent = pBase->nIndent + 1;
          forumpost_add_to_display(pThread, pPrev);
          forumthread_display_order(pThread, pPrev);
        }

        pPrev = p;
      }
    }
  }
  if( pPrev ){
    pPrev->nIndent = pBase->nIndent + 1;
    if( pPrev->nIndent>pThread->mxIndent ) pThread->mxIndent = pPrev->nIndent;
    forumpost_add_to_display(pThread, pPrev);
    forumthread_display_order(pThread, pPrev);
  }
}

/*
** Construct a ForumThread object given the root record id.
*/
static ForumThread *forumthread_create(int froot, int computeHierarchy){
  ForumThread *pThread;
  ForumPost *pPost;
  ForumPost *p;
  Stmt q;
  int sid = 1;

  int firt, fprev;
  pThread = fossil_malloc( sizeof(*pThread) );
  memset(pThread, 0, sizeof(*pThread));
  db_prepare(&q,
     "SELECT fpid, firt, fprev, (SELECT uuid FROM blob WHERE rid=fpid), fmtime"
     "  FROM forumpost"
     " WHERE froot=%d ORDER BY fmtime",
     froot
  );
  while( db_step(&q)==SQLITE_ROW ){
    pPost = fossil_malloc( sizeof(*pPost) );
    memset(pPost, 0, sizeof(*pPost));
    pPost->fpid = db_column_int(&q, 0);
    firt = db_column_int(&q, 1);
    fprev = db_column_int(&q, 2);
    pPost->zUuid = fossil_strdup(db_column_text(&q,3));
    pPost->rDate = db_column_double(&q,4);
    if( !fprev ) pPost->sid = sid++;
    pPost->pPrev = pThread->pLast;
    pPost->pNext = 0;

    if( pThread->pLast==0 ){
      pThread->pFirst = pPost;
    }else{
      pThread->pLast->pNext = pPost;
    }



    pThread->pLast = pPost;

    /* Find the in-reply-to post.  Default to the topic post if the replied-to
    ** post cannot be found. */
    if( firt ){
      pPost->pIrt = pThread->pFirst;
      for(p=pThread->pFirst; p; p=p->pNext){
        if( p->fpid==firt ){
          pPost->pIrt = p;
          break;
        }


      }




    }

    /* Maintain the linked list of post edits. */
    if( fprev ){
      p = forumpost_backward(pPost->pPrev, fprev);

      p->pEditNext = pPost;
      pPost->sid = p->sid;
      pPost->rev = p->rev+1;
      pPost->nEdit = p->nEdit+1;
      pPost->pEditPrev = p;
      pPost->pEditHead = p->pEditHead ? p->pEditHead : p;

      for(; p; p=p->pEditPrev ){
        p->nEdit = pPost->nEdit;
        p->pEditTail = pPost;
      }
    }
  }
  db_finalize(&q);

  if( computeHierarchy ){
    /* Compute the hierarchical display order */
    pPost = pThread->pFirst;
    pPost->nIndent = 1;
    pThread->mxIndent = 1;
    forumpost_add_to_display(pThread, pPost);
    forumthread_display_order(pThread, pPost);
  }

  /* Return the result */
  return pThread;
}

/*
................................................................................
** This command is intended for testing an analysis only.
*/
void forumthread_cmd(void){
  int fpid;
  int froot;
  const char *zName;
  ForumThread *pThread;
  ForumPost *p;

  db_find_and_open_repository(0,0);
  verify_all_options();
  if( g.argc==2 ){
    forum_thread_list();
    return;
  }
................................................................................
  fossil_print("fpid  = %d\n", fpid);
  fossil_print("froot = %d\n", froot);
  pThread = forumthread_create(froot, 1);
  fossil_print("Chronological:\n");
  fossil_print(
/* 0         1         2         3         4         5         6         7    */
/*  123456789 123456789 123456789 123456789 123456789 123456789 123456789 123 */
  " sid  rev      fpid      pIrt pEditPrev pEditTail hash\n");
  for(p=pThread->pFirst; p; p=p->pNext){
    fossil_print("%4d %4d %9d %9d %9d %9d %8.8s\n", p->sid, p->rev,
       p->fpid, p->pIrt ? p->pIrt->fpid : 0,
       p->pEditPrev ? p->pEditPrev->fpid : 0,
       p->pEditTail ? p->pEditTail->fpid : 0, p->zUuid);
  }
  fossil_print("\nDisplay\n");
  for(p=pThread->pDisplay; p; p=p->pDisplay){
    fossil_print("%*s", (p->nIndent-1)*3, "");
    if( p->pEditTail ){
      fossil_print("%d->%d\n", p->fpid, p->pEditTail->fpid);
    }else{
      fossil_print("%d\n", p->fpid);
    }
  }
  forumthread_delete(pThread);
}

................................................................................
      @ <h1>%h(zTitle)</h1>
    }else{
      @ <h1><i>Deleted</i></h1>
    }
  }
  if( zContent && zContent[0] ){
    Blob x;
    const int isFossilWiki = zMimetype==0
      || fossil_strcmp(zMimetype, "text/x-fossil-wiki")==0;
    if( bScroll ){
      @ <div class='forumPostBody'>
    }else{
      @ <div class='forumPostFullBody'>
    }
    blob_init(&x, 0, 0);
    blob_append(&x, zContent, -1);
    safe_html_context(DOCSRC_FORUM);
    if( isFossilWiki ){
      /* Markdown and plain-text rendering add a wrapper DIV resp. PRE
      ** element around the post, and some CSS relies on its existence
      ** in order to handle expansion/collapse of the post. Fossil
      ** Wiki rendering does not do so, so we must wrap those manually
      ** here. */
      @ <div class='fossilWiki'>
    }
    wiki_render_by_mimetype(&x, zMimetype);
    if( isFossilWiki ){
      @ </div>
    }
    blob_reset(&x);
    @ </div>
  }else{
    @ <i>Deleted</i>
  }
  if( zClass ){
    @ </div>
  }
}



















/*
** Compute a display name from a login name.
**
** If the input login is found in the USER table, then check the USER.INFO
** field to see if it has display-name followed by an email address.
** If it does, that becomes the new display name.  If not, let the display
** name just be the login.
**
** Space to hold the returned name is obtained from fossil_strdup() or
** mprintf() and should be freed by the caller.
*/
static char *display_name_from_login(const char *zLogin){
  static Stmt q;
  char *zResult;
  db_static_prepare(&q,
     "SELECT display_name(info) FROM user WHERE login=$login"
  );
  db_bind_text(&q, "$login", zLogin);
  if( db_step(&q)==SQLITE_ROW && db_column_type(&q,0)==SQLITE_TEXT ){
................................................................................
    zResult = fossil_strdup(zLogin);
  }
  db_reset(&q);
  return zResult;
}

/*
** Compute and return the display name for a ForumPost.  If
** pManifest is not NULL, then it is a Manifest object for the post.
** if pManifest is NULL, this routine has to fetch and parse the
** Manifest object for itself.
**
** Memory to hold the display name is attached to p->zDisplayName
** and will be freed together with the ForumPost object p when it
** is freed.
*/
static char *forum_post_display_name(ForumPost *p, Manifest *pManifest){
  Manifest *pToFree = 0;
  if( p->zDisplayName ) return p->zDisplayName;
  if( pManifest==0 ){
    pManifest = pToFree = manifest_get(p->fpid, CFTYPE_FORUM, 0);
    if( pManifest==0 ) return "(unknown)";
  }
  p->zDisplayName = display_name_from_login(pManifest->zUser);
  if( pToFree ) manifest_destroy(pToFree);
  if( p->zDisplayName==0 ) return "(unknown)";
  return p->zDisplayName;
}


/*
** Display a single post in a forum thread.
*/
static void forum_display_post(





  ForumPost *p,         /* Forum post to display */
  int iIndentScale,     /* Indent scale factor */
  int bRaw,             /* True to omit the border */
  int bUnf,             /* True to leave the post unformatted */
  int bHist,            /* True if showing edit history */
  int bSelect,          /* True if this is the selected post */
  char *zQuery          /* Common query string */
){
  char *zPosterName;    /* Name of user who originally made this post */
  char *zEditorName;    /* Name of user who provided the current edit */
  char *zDate;          /* The time/date string */

  char *zHist;          /* History query string */
  Manifest *pManifest;  /* Manifest comprising the current post */
  int bPrivate;         /* True for posts awaiting moderation */
  int bSameUser;        /* True if author is also the reader */
  int iIndent;          /* Indent level */
  const char *zMimetype;/* Formatting MIME type */



  /* Get the manifest for the post.  Abort if not found (e.g. shunned). */
  pManifest = manifest_get(p->fpid, CFTYPE_FORUM, 0);





  if( !pManifest ) return;

  /* When not in raw mode, create the border around the post. */
  if( !bRaw ){
    /* Open the <div> enclosing the post.  Set the class string to mark the post
    ** as selected and/or obsolete. */
    iIndent = (p->pEditHead ? p->pEditHead->nIndent : p->nIndent)-1;
    @ <div id='forum%d(p->fpid)' class='forumTime\
    @ %s(bSelect ? " forumSel" : "")\
    @ %s(p->pEditTail ? " forumObs" : "")' \
    if( iIndent && iIndentScale ){
      @ style='margin-left:%d(iIndent*iIndentScale)ex;'>
    }else{

      @ >
    }

    /* If this is the first post (or an edit thereof), emit the thread title. */
    if( pManifest->zThreadTitle ){
      @ <h1>%h(pManifest->zThreadTitle)</h1>
    }

    /* Begin emitting the header line.  The forum of the title
    ** varies depending on whether:
    **    *  The post is unedited
    **    *  The post was last edited by the original author
    **    *  The post was last edited by a different person
    */
    if( p->pEditHead ){
      zDate = db_text(0, "SELECT datetime(%.17g)", p->pEditHead->rDate);
    }else{
      zPosterName = forum_post_display_name(p, pManifest);
      zEditorName = zPosterName;
    }
    zDate = db_text(0, "SELECT datetime(%.17g)", p->rDate);


    if( p->pEditPrev ){
      zPosterName = forum_post_display_name(p->pEditHead, 0);
      zEditorName = forum_post_display_name(p, pManifest);
      zHist = bHist ? "" : "&hist";
      @ <h3 class='forumPostHdr'>(%d(p->sid)\

      @ .%0*d(fossil_num_digits(p->nEdit))(p->rev)) \
      if( fossil_strcmp(zPosterName, zEditorName)==0 ){
        @ By %h(zPosterName) on %h(zDate) edited from \
        @ %z(href("%R/forumpost/%S?%s%s",p->pEditPrev->zUuid,zQuery,zHist))\
        @ %d(p->sid).%0*d(fossil_num_digits(p->nEdit))(p->pEditPrev->rev)</a>
      }else{
        @ Originally by %h(zPosterName) \
        @ with edits by %h(zEditorName) on %h(zDate) from \
        @ %z(href("%R/forumpost/%S?%s%s",p->pEditPrev->zUuid,zQuery,zHist))\
        @ %d(p->sid).%0*d(fossil_num_digits(p->nEdit))(p->pEditPrev->rev)</a>
      }
    }else{
      zPosterName = forum_post_display_name(p, pManifest);
      @ <h3 class='forumPostHdr'>(%d(p->sid)) \
      @ By %h(zPosterName) on %h(zDate)
    }
    fossil_free(zDate);





    /* If debugging is enabled, link to the artifact page. */
    if( g.perm.Debug ){
      @ <span class="debug">\
      @ <a href="%R/artifact/%h(p->zUuid)">(artifact-%d(p->fpid))</a></span>
    }

    /* If this is a reply, refer back to the parent post. */
    if( p->pIrt ){



      @ in reply to %z(href("%R/forumpost/%S?%s",p->pIrt->zUuid,zQuery))\
      @ %d(p->pIrt->sid)\
      if( p->pIrt->nEdit ){
        @ .%0*d(fossil_num_digits(p->pIrt->nEdit))(p->pIrt->rev)\
      }
      @ </a>
    }


    /* If this post was later edited, refer forward to the next edit. */
    if( p->pEditNext ){
      @ updated by %z(href("%R/forumpost/%S?%s",p->pEditNext->zUuid,zQuery))\
      @ %d(p->pEditNext->sid)\

      @ .%0*d(fossil_num_digits(p->nEdit))(p->pEditNext->rev)</a>
    }


    /* Provide a link to select the individual post. */
    if( !bSelect ){
      @ %z(href("%R/forumpost/%S?%s",p->zUuid,zQuery))[link]</a>
    }

    /* Provide a link to the raw source code. */
    if( !bUnf ){
      @ %z(href("%R/forumpost/%S?raw",p->zUuid))[source]</a>
    }
    @ </h3>
  }

  /* Check if this post is approved, also if it's by the current user. */
  bPrivate = content_is_private(p->fpid);
  bSameUser = login_is_individual()
           && fossil_strcmp(pManifest->zUser, g.zLogin)==0;


  /* Render the post if the user is able to see it. */
  if( bPrivate && !g.perm.ModForum && !bSameUser ){
    @ <p><span class="modpending">Awaiting Moderator Approval</span></p>
  }else{


    if( bRaw || bUnf || p->pEditTail ){
      zMimetype = "text/plain";


    }else{
      zMimetype = pManifest->zMimetype;
    }
    forum_render(0, zMimetype, pManifest->zWiki, 0, !bRaw);
  }

  /* When not in raw mode, finish creating the border around the post. */
  if( !bRaw ){
    /* If the user is able to write to the forum and if this post has not been
    ** edited, create a form with various interaction buttons. */
    if( g.perm.WrForum && !p->pEditTail ){


      @ <div><form action="%R/forumedit" method="POST">
      @ <input type="hidden" name="fpid" value="%s(p->zUuid)">
      if( !bPrivate ){
        /* Reply and Edit are only available if the post has been approved. */

        @ <input type="submit" name="reply" value="Reply">
        if( g.perm.Admin || bSameUser ){
          @ <input type="submit" name="edit" value="Edit">
          @ <input type="submit" name="nullout" value="Delete">
        }
      }else if( g.perm.ModForum ){
        /* Allow moderators to approve or reject pending posts.  Also allow
        ** forum supervisors to mark non-special users as trusted and therefore
        ** able to post unmoderated. */
        @ <input type="submit" name="approve" value="Approve">
        @ <input type="submit" name="reject" value="Reject">

        if( g.perm.AdminForum && !login_is_special(pManifest->zUser) ){
          @ <br><label><input type="checkbox" name="trust">
          @ Trust user "%h(pManifest->zUser)" so that future posts by \
          @ "%h(pManifest->zUser)" do not require moderation.
          @ </label>
          @ <input type="hidden" name="trustuser" value="%h(pManifest->zUser)">
        }
      }else if( bSameUser ){


        /* Allow users to delete (reject) their own pending posts. */
        @ <input type="submit" name="reject" value="Delete">
      }
      @ </form></div>
    }

    @ </div>
  }

  /* Clean up. */
  manifest_destroy(pManifest);
}

/*
** Possible display modes for forum_display_thread().
*/
enum {
  FD_RAW,     /* Like FD_SINGLE, but additionally omit the border, force
              ** unformatted mode, and inhibit history mode */
  FD_SINGLE,  /* Render a single post and (optionally) its edit history */
  FD_CHRONO,  /* Render all posts in chronological order */
  FD_HIER,    /* Render all posts in an indented hierarchy */
};

/*
** Display a forum thread.  If mode is FD_RAW or FD_SINGLE, display only a
** single post from the thread and (optionally) its edit history.
*/
static void forum_display_thread(
  int froot,            /* Forum thread root post ID */
  int fpid,             /* Selected forum post ID, or 0 if none selected */
  int mode,             /* Forum display mode, one of the FD_* enumerations */
  int bUnf,             /* True if rendering unformatted */
  int bHist             /* True if showing edit history, ignored for FD_RAW */
){
  ForumThread *pThread; /* Thread structure */
  ForumPost *pSelect;   /* Currently selected post, or NULL if none */
  ForumPost *p;         /* Post iterator pointer */
  char *zQuery;         /* Common query string */
  int iIndentScale = 4; /* Indent scale factor, measured in "ex" units */
  int sid;              /* Comparison serial ID */

  /* In raw mode, force unformatted display and disable history. */
  if( mode == FD_RAW ){
    bUnf = 1;
    bHist = 0;
  }

  /* Thread together the posts and (optionally) compute the hierarchy. */
  pThread = forumthread_create(froot, mode==FD_HIER);

  /* Compute the appropriate indent scaling. */
  if( mode==FD_HIER ){
    iIndentScale = 4;
    while( iIndentScale>1 && iIndentScale*pThread->mxIndent>25 ){
      iIndentScale--;
    }
  }else{
    iIndentScale = 0;
  }

  /* Find the selected post, or (depending on parameters) its latest edit. */
  pSelect = fpid ? forumpost_forward(pThread->pFirst, fpid) : 0;
  if( !bHist && mode!=FD_RAW && pSelect && pSelect->pEditTail ){
    pSelect = pSelect->pEditTail;
  }

  /* When displaying only a single post, abort if no post was selected or the
  ** selected forum post does not exist in the thread.  Otherwise proceed to
  ** display the entire thread without marking any posts as selected. */
  if( !pSelect && (mode==FD_RAW || mode==FD_SINGLE) ){
    return;
  }

  /* Create the common query string to append to nearly all post links. */
  zQuery = mode==FD_RAW ? 0 : mprintf("t=%c%s%s",
      mode==FD_SINGLE ? 's' : mode==FD_CHRONO ? 'c' : 'h',
      bUnf ? "&unf" : "", bHist ? "&hist" : "");

  /* Identify which post to display first.  If history is shown, start with the
  ** original, unedited post.  Otherwise advance to the post's latest edit.  */
  if( mode==FD_RAW || mode==FD_SINGLE ){
    p = pSelect;
    if( bHist && p->pEditHead ) p = p->pEditHead;
  }else{
    p = mode==FD_CHRONO ? pThread->pFirst : pThread->pDisplay;
    if( !bHist && p->pEditTail ) p = p->pEditTail;
  }

  /* Display the appropriate subset of posts in sequence. */
  while( p ){
    /* Display the post. */
    forum_display_post(p, iIndentScale, mode==FD_RAW,
        bUnf, bHist, p==pSelect, zQuery);

    /* Advance to the next post in the thread. */
    if( mode==FD_CHRONO ){
      /* Chronological mode: display posts (optionally including edits) in their
      ** original commit order. */
      if( bHist ){
        p = p->pNext;
      }else{
        sid = p->sid;
        if( p->pEditHead ) p = p->pEditHead;
        do p = p->pNext; while( p && p->sid<=sid );
        if( p && p->pEditTail ) p = p->pEditTail;
      }
    }else if( bHist && p->pEditNext ){
      /* Hierarchical and single mode: display each post's edits in sequence. */
      p = p->pEditNext;
    }else if( mode==FD_HIER ){
      /* Hierarchical mode: after displaying with each post (optionally
      ** including edits), go to the next post in computed display order. */
      p = p->pEditHead ? p->pEditHead->pDisplay : p->pDisplay;
      if( !bHist && p && p->pEditTail ) p = p->pEditTail;
    }else{
      /* Single and raw mode: terminate after displaying the selected post and
      ** (optionally) its edits. */
      break;
    }
  }

  /* Undocumented "threadtable" query parameter causes thread table to be
  ** displayed for debugging purposes. */

  if( PB("threadtable") ){
    @ <hr>
    @ <table border="1" cellpadding="3" cellspacing="0">

    @ <tr><th>sid<th>rev<th>fpid<th>pIrt<th>pEditHead<th>pEditTail\
    @ <th>pEditNext<th>pEditPrev<th>pDisplay<th>hash
    for(p=pThread->pFirst; p; p=p->pNext){
      @ <tr><td>%d(p->sid)<td>%d(p->rev)<td>%d(p->fpid)\


      @ <td>%d(p->pIrt ? p->pIrt->fpid : 0)\
      @ <td>%d(p->pEditHead ? p->pEditHead->fpid : 0)\
      @ <td>%d(p->pEditTail ? p->pEditTail->fpid : 0)\
      @ <td>%d(p->pEditNext ? p->pEditNext->fpid : 0)\
      @ <td>%d(p->pEditPrev ? p->pEditPrev->fpid : 0)\
      @ <td>%d(p->pDisplay ? p->pDisplay->fpid : 0)\
      @ <td>%S(p->zUuid)</tr>
    }
    @ </table>
  }

  /* Clean up. */


























































































  forumthread_delete(pThread);

























































  fossil_free(zQuery);



}



































































/*

** Emit Forum Javascript which applies (or optionally can apply)
** to all forum-related pages. It does not include page-specific
** code (e.g. "forum.js").
*/
static void forum_emit_js(void){






  builtin_fossil_js_bundle_or("copybutton", "pikchr", 0);
  builtin_request_js("fossil.page.forumpost.js");
}


/*
** WEBPAGE: forumpost
**
** Show a single forum posting. The posting is shown in context with
** its entire thread.  The selected posting is enclosed within
** <div class='forumSel'>...</div>.  Javascript is used to move the
** selected posting into view after the page loads.
**
** Query parameters:
**
**   name=X        REQUIRED.  The hash of the post to display.
**   t=a           Automatic display mode, i.e. hierarchical for
**                 desktop and chronological for mobile.  This is the
**                 default if the "t" query parameter is omitted.
**   t=c           Show posts in the order they were written.
**   t=h           Show posts usin hierarchical indenting.

**   t=s           Show only the post specified by "name=X".
**   t=r           Alias for "t=c&unf&hist".
**   t=y           Alias for "t=s&unf&hist".
**   raw           Alias for "t=s&unf".  Additionally, omit the border
**                 around the post, and ignore "t" and "hist".
**   unf           Show the original, unformatted source text.
**   hist          Show edit history in addition to current posts.
*/
void forumpost_page(void){
  forumthread_page();
}





















/*
** WEBPAGE: forumthread
**
** Show all forum messages associated with a particular message thread.
** The result is basically the same as /forumpost except that none of
** the postings in the thread are selected.
**
** Query parameters:
**
**   name=X        REQUIRED.  The hash of any post of the thread.
**   t=a           Automatic display mode, i.e. hierarchical for
**                 desktop and chronological for mobile.  This is the
**                 default if the "t" query parameter is omitted.
**   t=c           Show posts in the order they were written.
**   t=h           Show posts using hierarchical indenting.
**   unf           Show the original, unformatted source text.
**   hist          Show edit history in addition to current posts.
*/
void forumthread_page(void){
  int fpid;
  int froot;
  char *zThreadTitle;
  const char *zName = P("name");
  const char *zMode = PD("t","a");
  int bRaw = PB("raw");
  int bUnf = PB("unf");
  int bHist = PB("hist");
  int mode = 0;
  login_check_credentials();
  if( !g.perm.RdForum ){
    login_needed(g.anon.RdForum);
    return;
  }
  if( zName==0 ){
    webpage_error("Missing \"name=\" query parameter");
................................................................................
    webpage_error("Unknown or ambiguous forum id: \"%s\"", zName);
  }
  froot = db_int(0, "SELECT froot FROM forumpost WHERE fpid=%d", fpid);
  if( froot==0 ){
    webpage_error("Not a forum post: \"%s\"", zName);
  }
  if( fossil_strcmp(g.zPath,"forumthread")==0 ) fpid = 0;


  /* Decode the mode parameters. */
  if( bRaw ){
    mode = FD_RAW;
    bUnf = 1;
    bHist = 0;
    cgi_replace_query_parameter("unf", "on");
    cgi_delete_query_parameter("hist");
    cgi_delete_query_parameter("raw");
  }else{
    switch( *zMode ){
      case 'a': mode = cgi_from_mobile() ? FD_CHRONO : FD_HIER; break;
      case 'c': mode = FD_CHRONO; break;
      case 'h': mode = FD_HIER; break;
      case 's': mode = FD_SINGLE; break;
      case 'r': mode = FD_CHRONO; break;
      case 'y': mode = FD_SINGLE; break;
      default: webpage_error("Invalid thread mode: \"%s\"", zMode);
    }
    if( *zMode=='r' || *zMode=='y') {
      bUnf = 1;
      bHist = 1;
      cgi_replace_query_parameter("t", mode==FD_CHRONO ? "c" : "s");
      cgi_replace_query_parameter("unf", "on");
      cgi_replace_query_parameter("hist", "on");
    }


  }















  /* Define the page header. */
  zThreadTitle = db_text("",
    "SELECT"
    " substr(event.comment,instr(event.comment,':')+2)"
    " FROM forumpost, event"
    " WHERE event.objid=forumpost.fpid"
    "   AND forumpost.fpid=%d;",
    fpid
  );
  style_header("%s%s", zThreadTitle, *zThreadTitle ? "" : "Forum");
  fossil_free(zThreadTitle);
  if( mode!=FD_CHRONO ){
    style_submenu_element("Chronological", "%R/%s/%s?t=c%s%s", g.zPath, zName,
        bUnf ? "&unf" : "", bHist ? "&hist" : "");
  }

  if( mode!=FD_HIER ){
    style_submenu_element("Hierarchical", "%R/%s/%s?t=h%s%s", g.zPath, zName,














        bUnf ? "&unf" : "", bHist ? "&hist" : "");
  }

  style_submenu_checkbox("unf", "Unformatted", 0, 0);
  style_submenu_checkbox("hist", "History", 0, 0);

  /* Display the thread. */
  forum_display_thread(froot, fpid, mode, bUnf, bHist);

  /* Emit Forum Javascript. */
  builtin_request_js("forum.js");
  forum_emit_js();

  /* Emit the page style. */
  style_footer();
}

/*
** Return true if a forum post should be moderated.
*/
static int forum_need_moderation(void){
................................................................................
    iBasis = iInReplyTo;
  }
  webpage_assert( (zTitle==0)+(iInReplyTo==0)==1 );
  blob_init(&x, 0, 0);
  zDate = date_in_standard_format("now");
  blob_appendf(&x, "D %s\n", zDate);
  fossil_free(zDate);
  zG = db_text(0,
     "SELECT uuid FROM blob, forumpost"
     " WHERE blob.rid==forumpost.froot"
     "   AND forumpost.fpid=%d", iBasis);
  if( zG ){
    blob_appendf(&x, "G %s\n", zG);
    fossil_free(zG);
  }
................................................................................
    return 1;
  }
}

/*
** Paint the form elements for entering a Forum post
*/
static void forum_post_widget(
  const char *zTitle,
  const char *zMimetype,
  const char *zContent
){
  if( zTitle ){
    @ Title: <input type="input" name="title" value="%h(zTitle)" size="50"
    @ maxlength="125"><br>
................................................................................
  @ <form action="%R/login" method="POST">
  @ <input type="hidden" name="g" value="%s(zGoto)">
  @ <input type="hidden" name="noanon" value="1">
  @ <input type="submit" value="Login">
  @ </form>
  @ <td>Log into an existing account
  @ </table>
  forum_emit_js();
  style_footer();
  fossil_free(zGoto);
}

/*
** Write the "From: USER" line on the webpage.
*/
................................................................................
    @ <h1>Preview:</h1>
    forum_render(zTitle, zMimetype, zContent, "forumEdit", 1);
  }
  style_header("New Forum Thread");
  @ <form action="%R/forume1" method="POST">
  @ <h1>New Thread:</h1>
  forum_from_line();
  forum_post_widget(zTitle, zMimetype, zContent);
  @ <input type="submit" name="preview" value="Preview">
  if( P("preview") && !whitespace_only(zContent) ){
    @ <input type="submit" name="submit" value="Submit">
  }else{
    @ <input type="submit" name="submit" value="Submit" disabled>
  }
  if( g.perm.Debug ){
................................................................................
    @ <br><label><input type="checkbox" name="domod" %s(PCK("domod"))> \
    @ Require moderator approval</label>
    @ <br><label><input type="checkbox" name="showqp" %s(PCK("showqp"))> \
    @ Show query parameters</label>
    @ </div>
  }
  @ </form>
  forum_emit_js();
  style_footer();
}

/*
** WEBPAGE: forume2
**
** Edit an existing forum message.
** Query parameters:
**
**   fpid=X        Hash of the post to be edited.  REQUIRED
*/
void forumedit_page(void){
  int fpid;
  int froot;
  Manifest *pPost = 0;
  Manifest *pRootPost = 0;
  const char *zMimetype = 0;
................................................................................
    if( P("approve") ){
      const char *zUserToTrust;
      moderation_approve('f', fpid);
      if( g.perm.AdminForum
       && PB("trust")
       && (zUserToTrust = P("trustuser"))!=0
      ){
        db_unprotect(PROTECT_USER);
        db_multi_exec("UPDATE user SET cap=cap||'4' "
                      "WHERE login=%Q AND cap NOT GLOB '*4*'",
                      zUserToTrust);
        db_protect_pop();
      }
      cgi_redirectf("%R/forumpost/%S",P("fpid"));
      return;
    }
    if( P("reject") ){
      char *zParent =
        db_text(0,
          "SELECT uuid FROM forumpost, blob"
          " WHERE forumpost.fpid=%d AND blob.rid=forumpost.firt",
          fpid
        );
      moderation_disapprove(fpid);
      if( zParent ){
................................................................................
      forum_render(zTitle, zMimetype, zContent,"forumEdit", 1);
    }
    @ <h2>Revised Message:</h2>
    @ <form action="%R/forume2" method="POST">
    @ <input type="hidden" name="fpid" value="%h(P("fpid"))">
    @ <input type="hidden" name="edit" value="1">
    forum_from_line();
    forum_post_widget(zTitle, zMimetype, zContent);
  }else{
    /* Reply */
    char *zDisplayName;
    zMimetype = PD("mimetype",DEFAULT_FORUM_MIMETYPE);
    zContent = PDT("content","");
    style_header("Reply");
    if( pRootPost->zThreadTitle ){
................................................................................
      forum_render(0, zMimetype,zContent, "forumEdit", 1);
    }
    @ <h2>Enter Reply:</h2>
    @ <form action="%R/forume2" method="POST">
    @ <input type="hidden" name="fpid" value="%h(P("fpid"))">
    @ <input type="hidden" name="reply" value="1">
    forum_from_line();
    forum_post_widget(0, zMimetype, zContent);
  }
  if( !isDelete ){
    @ <input type="submit" name="preview" value="Preview">
  }
  @ <input type="submit" name="cancel" value="Cancel">
  if( (P("preview") && !whitespace_only(zContent)) || isDelete ){
    @ <input type="submit" name="submit" value="Submit">
................................................................................
    @ <br><label><input type="checkbox" name="domod" %s(PCK("domod"))> \
    @ Require moderator approval</label>
    @ <br><label><input type="checkbox" name="showqp" %s(PCK("showqp"))> \
    @ Show query parameters</label>
    @ </div>
  }
  @ </form>
  forum_emit_js();
  style_footer();
}

/*
** WEBPAGE: forummain
** WEBPAGE: forum
**

Changes to src/fossil.bootstrap.js.

1












2
3
4

5
6
7
8
9
10
11
12
...
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
"use strict";












(function(global){
  /* Bootstrapping bits for the global.fossil object. Must be
     loaded after style.c:style_emit_script_tag() has initialized

     that object.
  */

  const F = global.fossil;

  /**
     Returns the current time in something approximating
     ISO-8601 format.
................................................................................
    const n = ('number'===typeof forUrl)
          ? forUrl : F.config[forUrl ? 'hashDigitsUrl' : 'hashDigits'];
    return ('string'==typeof hash ? hash.substr(
      0, n
    ) : hash);
  };

  /**
     Sets up pseudo-automatic content preview handling between a
     source element (typically a TEXTAREA) and a target rendering
     element (typically a DIV). The selector argument must be one of:

     - A single DOM element
     - A collection of DOM elements with a forEach method.
     - A CSS selector

     Each element in the collection must have the following data
     attributes:

     - data-f-preview-from: is either a DOM element id, WITH a leading
     '#' prefix, or the name of a method (see below). If it's an ID,
     the DOM element must support .value to get the content.

     - data-f-preview-to: the DOM element id of the target "previewer"
       element, WITH a leading '#', or the name of a method (see below).

     - data-f-preview-via: the name of a method (see below).

     - OPTIONAL data-f-preview-as-text: a numeric value. Explained below.

     Each element gets a click handler added to it which does the
     following:

     1) Reads the content from its data-f-preview-from element or, if
     that property refers to a method, calls the method without
     arguments and uses its result as the content.

     2) Passes the content to
     methodNamespace[f-data-post-via](content,callback). f-data-post-via
     is responsible for submitting the preview HTTP request, including
     any parameters the request might require. When the response
     arrives, it must pass the content of the response to its 2nd
     argument, an auto-generated callback installed by this mechanism
     which...

     3) Assigns the response text to the data-f-preview-to element or
     passes it to the function methodNamespace[f-data-preview-to](content), as
     appropriate. If data-f-preview-to is a DOM element and
     data-f-preview-as-text is '0' (the default) then the content is
     assigned to the target element's innerHTML property, else it is
     assigned to the element's textContent property.

     The methodNamespace (2nd argument) defaults to fossil.page, and
     any method-name data properties, e.g. data-f-preview-via and
     potentially data-f-preview-from/to, must be a single method name,
     not a property-access-style string. e.g. "myPreview" is legal but
     "foo.myPreview" is not (unless, of course, the method is actually
     named "foo.myPreview" (which is legal but would be
     unconventional)).

     An example...

     First an input button:

     <button id='test-preview-connector'
       data-f-preview-from='#fileedit-content-editor' // elem ID or method name
       data-f-preview-via='myPreview' // method name
       data-f-preview-to='#fileedit-tab-preview-wrapper' // elem ID or method name
     >Preview update</button>

     And a sample data-f-preview-via method:

     fossil.page.myPreview = function(content,callback){
       const fd = new FormData();
       fd.append('foo', ...);
       fossil.fetch('preview_forumpost',{
         payload: fd,
         onload: callback,
         onerror: (e)=>{ // only if app-specific handling is needed
           fossil.fetch.onerror(e); // default impl
           ... any app-specific error reporting ...
         }
       });
     };

     Then connect the parts with:

     fossil.connectPagePreviewers('#test-preview-connector');

     Note that the data-f-preview-from, data-f-preview-via, and
     data-f-preview-to selector are not resolved until the button is
     actually clicked, so they need not exist in the DOM at the
     instant when the connection is set up, so long as they can be
     resolved when the preview-refreshing element is clicked.
  */
  F.connectPagePreviewers = function f(selector,methodNamespace){
    if('string'===typeof selector){
      selector = document.querySelectorAll(selector);
    }else if(!selector.forEach){
      selector = [selector];
    }
    if(!methodNamespace){
      methodNamespace = F.page;
    }
    selector.forEach(function(e){

      e.addEventListener(
        'click', function(r){
          const eTo = '#'===e.dataset.fPreviewTo[0]
                ? document.querySelector(e.dataset.fPreviewTo)
                : methodNamespace[e.dataset.fPreviewTo],
                eFrom = '#'===e.dataset.fPreviewFrom[0]
                ? document.querySelector(e.dataset.fPreviewFrom)
                : methodNamespace[e.dataset.fPreviewFrom],
                asText = +(e.dataset.fPreviewAsText || 0);
          eTo.textContent = "Fetching preview...";
          methodNamespace[e.dataset.fPreviewVia](
            (eFrom instanceof Function ? eFrom() : eFrom.value),
            (r)=>{
              if(eTo instanceof Function) eTo(r||'');
              else eTo[asText ? 'textContent' : 'innerHTML'] = r||'';
            }
          );
        }, false
      );
    });
    return this;
  };

  /**
     Convenience wrapper which adds an onload event listener to the
     window object. Returns this.
  */
  F.onPageLoad = function(callback){
    window.addEventListener('load', callback, false);
    return this;
  };

  /**
     Assuming name is a repo-style filename, this function returns
     a shortened form of that name:

     .../LastDirectoryPart/FilenamePart


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

|
<
>
|







 








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

<
<
<
<
<
<
<
<
<
<
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




|
|

|
|









1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
23
24
...
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
"use strict";
(function () {
  /* CustomEvent polyfill, courtesy of Mozilla:
     https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
  */
  if(typeof window.CustomEvent === "function") return false;
  window.CustomEvent = function(event, params) {
    if(!params) params = {bubbles: false, cancelable: false, detail: null};
    const evt = document.createEvent('CustomEvent');
    evt.initCustomEvent( event, !!params.bubbles, !!params.cancelable, params.detail );
    return evt;
  };
})();
(function(global){
  /* Bootstrapping bits for the global.fossil object. Must be loaded

     after style.c:builtin_emit_script_fossil_bootstrap() has
     initialized that object.
  */

  const F = global.fossil;

  /**
     Returns the current time in something approximating
     ISO-8601 format.
................................................................................
    const n = ('number'===typeof forUrl)
          ? forUrl : F.config[forUrl ? 'hashDigitsUrl' : 'hashDigits'];
    return ('string'==typeof hash ? hash.substr(
      0, n
    ) : hash);
  };

  /**
     Convenience wrapper which adds an onload event listener to the
     window object. Returns this.




















































































  */










  F.onPageLoad = function(callback){
    window.addEventListener('load', callback, false);



















    return this;
  };

  /**
     Convenience wrapper which adds a DOMContentLoadedevent listener
     to the window object. Returns this.
  */
  F.onDOMContentLoaded = function(callback){
    window.addEventListener('DOMContentLoaded', callback, false);
    return this;
  };

  /**
     Assuming name is a repo-style filename, this function returns
     a shortened form of that name:

     .../LastDirectoryPart/FilenamePart

Changes to src/fossil.confirmer.js.

116
117
118
119
120
121
122

123
124
125
126
127
128
129
130
131
...
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

- Add an invert option which activates if the timeout is reached and
"times out" if the element is clicked again. e.g. a button which says
"Saving..." and cancels the op if it's clicked again, else it saves
after X time/ticks.

- Internally we save/restore the initial text of non-INPUT elements

using innerHTML. We should instead move their child nodes aside (into
an internal out-of-DOM element) and restore them as needed.

Terse Change history:

- 20200811
  - Added pinSize option.

- 20200507:
................................................................................
        this.target = target;
        this.opt = opt;
        this.timerID = undefined;
        this.state = this.states.initial;
        const isInput = f.isInput(target);
        const updateText = function(msg){
          if(isInput) target.value = msg;





          else target.innerHTML = msg;


        }
        const formatCountdown = (txt, number) => txt + " ["+number+"]";
        if(opt.pinSize && opt.confirmText){
          /* Try to pin the element's width the the greater of its
             current width or its waiting-on-confirmation width
             to avoid layout reflow when it's activated. */
          const digits = (''+(opt.timeout/1000 || opt.ticks)).length;
          const lblLong = formatCountdown(opt.confirmText, "00000000".substr(0,digits));
          const w1 = parseFloat(window.getComputedStyle(target).width);
          updateText(lblLong);
          const w2 = parseFloat(window.getComputedStyle(target).width);


          target.style.minWidth = target.style.maxWidth = (w1>w2 ? w1 : w2)+"px";

        }
        updateText(this.opt.initialText);
        if(this.opt.ticks && !this.opt.ontick){
          this.opt.ontick = function(tick){
            updateText(formatCountdown(self.opt.confirmText,tick));
          };
        }







>
|
|







 







>
>
>
>
>
|
>
>







|
|

|
>
>
|
>







116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
...
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

- Add an invert option which activates if the timeout is reached and
"times out" if the element is clicked again. e.g. a button which says
"Saving..." and cancels the op if it's clicked again, else it saves
after X time/ticks.

- Internally we save/restore the initial text of non-INPUT elements
using a relatively expensive bit of DOMParser hoop-jumping. We
"should" instead move their child nodes aside (into an internal
out-of-DOM element) and restore them as needed.

Terse Change history:

- 20200811
  - Added pinSize option.

- 20200507:
................................................................................
        this.target = target;
        this.opt = opt;
        this.timerID = undefined;
        this.state = this.states.initial;
        const isInput = f.isInput(target);
        const updateText = function(msg){
          if(isInput) target.value = msg;
          else{
            /* Jump through some hoops to avoid assigning to innerHTML... */
            const newNode = new DOMParser().parseFromString(msg, 'text/html');
            let childs = newNode.documentElement.querySelector('body');
            childs = childs ? Array.prototype.slice.call(childs.childNodes, 0) : [];
            target.innerText = '';
            childs.forEach((e)=>target.appendChild(e));
          }
        }
        const formatCountdown = (txt, number) => txt + " ["+number+"]";
        if(opt.pinSize && opt.confirmText){
          /* Try to pin the element's width the the greater of its
             current width or its waiting-on-confirmation width
             to avoid layout reflow when it's activated. */
          const digits = (''+(opt.timeout/1000 || opt.ticks)).length;
          const lblLong = formatCountdown(opt.confirmText, "00000000".substr(0,digits+1));
          const w1 = parseInt(target.getBoundingClientRect().width);
          updateText(lblLong);
          const w2 = parseInt(target.getBoundingClientRect().width);
          if(w1 || w2){
            /* If target is not in visible part of the DOM, those values may be 0. */
            target.style.minWidth = target.style.maxWidth = (w1>w2 ? w1 : w2)+"px";
          }
        }
        updateText(this.opt.initialText);
        if(this.opt.ticks && !this.opt.ontick){
          this.opt.ontick = function(tick){
            updateText(formatCountdown(self.opt.confirmText,tick));
          };
        }

Added src/fossil.copybutton.js.

































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function(F/*fossil object*/){
  /**
     A basic API for creating and managing a copy-to-clipboard button.

     Requires: fossil.bootstrap, fossil.dom
  */
  const D = F.dom;

  /**
     Initializes element e as a copy button using the given options
     object.

     The first argument may be a DOM element or a string (CSS selector
     suitable for use with document.querySelector()).

     Options:

     .copyFromElement: DOM element

     .copyFromId: DOM element ID

     One of copyFromElement or copyFromId must be provided, but copyFromId
     may optionally be provided via e.dataset.copyFromId.

     .extractText: optional callback which is triggered when the copy
     button is clicked. I tmust return the text to copy to the
     clipboard. The default is to extract it from the copy-from
     element, using its [value] member, if it has one, else its
     [innerText]. A client-provided callback may use any data source
     it likes, so long as it's synchronous. If this function returns a
     falsy value then the clipboard is not modified. This function is
     called with the fully expanded/resolved options object as its
     "this" (that's a different instance than the one passed to this
     function!).

     .cssClass: optional CSS class, or list of classes, to apply to e.

     .style: optional object of properties to copy directly into
     e.style.

     .oncopy: an optional callback function which is added as an event
     listener for the 'text-copied' event (see below). There is
     functionally no difference from setting this option or adding a
     'text-copied' event listener to the element, and this option is
     considered to be a convenience form of that. For the sake of
     framework-level consistency, the default value is a callback
     which passes the copy button to fossil.dom.flashOnce().

     Note that this function's own defaultOptions object holds default
     values for some options. Any changes made to that object affect
     any future calls to this function.

     Be aware that clipboard functionality might or might not be
     available in any given environment. If this button appears to
     have no effect, that may be because it is not enabled/available
     in the current platform.

     The copy button emits custom event 'text-copied' after it has
     successfully copied text to the clipboard. The event's "detail"
     member is an object with a "text" property holding the copied
     text. Other properties may be added in the future. The event is
     not fired if copying to the clipboard fails (e.g. is not
     available in the current environment).

     As a special case, the copy button's click handler is suppressed
     (becomes a no-op) for as long as the element has the CSS class
     "disabled". This allows elements which cannot be disabled via
     HTML attributes, e.g. a SPAN, to act as a copy button while still
     providing a way to disable them.

     Returns the copy-initialized element.

     Example:

     const button = fossil.copyButton('#my-copy-button', {
       copyFromId: 'some-other-element-id'
     });
     button.addEventListener('text-copied',function(ev){
       fossil.dom.flashOnce(ev.target);
       console.debug("Copied text:",ev.detail.text);
     });
  */
  F.copyButton = function f(e, opt){
    if('string'===typeof e){
      e = document.querySelector(e);
    }    
    opt = F.mergeLastWins(f.defaultOptions, opt);
    if(opt.cssClass){
      D.addClass(e, opt.cssClass);
    }
    var srcId, srcElem;
    if(opt.copyFromElement){
      srcElem = opt.copyFromElement;
    }else if((srcId = opt.copyFromId || e.dataset.copyFromId)){
      srcElem = document.querySelector('#'+srcId);
    }
    const extract = opt.extractText || (
      undefined===srcElem.value ? ()=>srcElem.innerText : ()=>srcElem.value
    );
    D.copyStyle(e, opt.style);
    e.addEventListener(
      'click',
      function(ev){
        ev.preventDefault();
        ev.stopPropagation();
        if(e.classList.contains('disabled')) return;
        const txt = extract.call(opt);
        if(txt && D.copyTextToClipboard(txt)){
          e.dispatchEvent(new CustomEvent('text-copied',{
            detail: {text: txt}
          }));
        }
      },
      false
    );
    if('function' === typeof opt.oncopy){
      e.addEventListener('text-copied', opt.oncopy, false);
    }
    return e;
  };

  F.copyButton.defaultOptions = {
    cssClass: 'copy-button',
    oncopy: D.flashOnce.eventHandler,
    style: {/*properties copied as-is into element.style*/}
  };
  
})(window.fossil);

Changes to src/fossil.dom.js.

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
...
135
136
137
138
139
140
141


142
143
144
145
146
147
148
...
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
...
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
...
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
...
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
...
467
468
469
470
471
472
473





















































































































































































































































































474
475
  dom.pre = dom.createElemFactory('pre');
  dom.header = dom.createElemFactory('header');
  dom.footer = dom.createElemFactory('footer');
  dom.section = dom.createElemFactory('section');
  dom.span = dom.createElemFactory('span');
  dom.strong = dom.createElemFactory('strong');
  dom.em = dom.createElemFactory('em');
  dom.label = dom.createElemFactory('label');






















  dom.img = function(src){
    const e = dom.create('img');
    if(src) e.setAttribute('src',src);
    return e;
  };
  /**
     Creates and returns a new anchor element with the given
     optional href and label. If label===true then href is used
     as the label.
  */
  dom.a = function(href,label){
    const e = dom.create('a');
    if(href) e.setAttribute('href',href);
    if(label) e.appendChild(dom.text(true===label ? href : label));
    return e;
  };
  dom.hr = dom.createElemFactory('hr');
  dom.br = dom.createElemFactory('br');
  dom.text = (t)=>document.createTextNode(t||'');
  dom.button = function(label){
    const b = this.create('button');
    if(label) b.appendChild(this.text(label));
    return b;
  };


































  dom.select = dom.createElemFactory('select');

  /**
     Returns an OPTION element with the given value and label
     text (which defaults to the value).

     May be called as (value), (selectElement), (selectElement,
     value), (value, label) or (selectElement, value,
     label). The latter appends the new element to the given






     SELECT element.





     If the value has the undefined value then it is NOT
     assigned as the option element's value.

  */
  dom.option = function(value,label){
    const a = arguments;
    var sel;
    if(1==a.length){
      if(a[0] instanceof HTMLElement){
        sel = a[0];
................................................................................
      value = a[1];
      label = a[2];
    }
    const o = this.create('option');
    if(undefined !== value){
      o.value = value;
      this.append(o, this.text(label || value));


    }
    if(sel) this.append(sel, o);
    return o;
  };
  dom.h = function(level){
    return this.create('h'+level);
  };
................................................................................
  dom.thead = dom.createElemFactoryWithOptionalParent('thead');
  dom.tbody = dom.createElemFactoryWithOptionalParent('tbody');
  dom.tfoot = dom.createElemFactoryWithOptionalParent('tfoot');
  dom.tr = dom.createElemFactoryWithOptionalParent('tr');
  dom.td = dom.createElemFactoryWithOptionalParent('td');
  dom.th = dom.createElemFactoryWithOptionalParent('th');

  
  /**
     Creates and returns a FIELDSET element, optionaly with a
     LEGEND element added to it.


  */
  dom.fieldset = function(legendText){
    const fs = this.create('fieldset');
    if(legendText){
      this.append(
        fs,
        this.append(
          this.create('legend'),
          legendText
        )

      );
    }
    return fs;
  };

  /**
     Appends each argument after the first to the first argument
................................................................................
  */
  dom.append = function f(parent/*,...*/){
    const a = argsToArray(arguments);
    a.shift();
    for(let i in a) {
      var e = a[i];
      if(isArray(e) || e.forEach){
        e.forEach((x)=>f.call(this, parent,e));
        continue;
      }


      if('string'===typeof e || 'number'===typeof e) e = this.text(e);
      parent.appendChild(e);
    }
    return parent;
  };

  dom.input = function(type){
    return this.attr(this.create('input'), 'type', type);
  };


  















































  /**
     Internal impl for addClass(), removeClass().
  */
  const domAddRemoveClass = function f(action,e){
    if(!f.rxSPlus){
      f.rxSPlus = /\s+/;
      f.applyAction = function(e,a,v){
................................................................................
  */
  dom.removeClass = function(e,c){
    const a = argsToArray(arguments);
    a.unshift('remove');
    return domAddRemoveClass.apply(this, a);
  };


















  dom.hasClass = function(e,c){
    return (e && e.classList) ? e.classList.contains(c) : false;
  };

  /**
     Each argument after the first may be a single DOM element
     or a container of them with a forEach() method. All such
     elements are appended, in the given order, to the dest
     element.


     Returns dest.
  */
  dom.moveTo = function(dest,e){
    const n = arguments.length;
    var i = 1;

    for( ; i < n; ++i ){
      e = arguments[i];
      if(e.forEach){
        e.forEach((x)=>dest.appendChild(x));
      }else{
        dest.appendChild(e);
      }
    }
    return dest;
  };
  /**
     Each argument after the first may be a single DOM element
     or a container of them with a forEach() method. For each
     DOM element argument, all children of that DOM element
................................................................................
      old.parentNode.removeChild(old);
    }
  };
  dom.replaceNode.counter = 0;        
  /**
     Two args == getter: (e,key), returns value

     Three == setter: (e,key,val), returns e. If val===null
     or val===undefined then the attribute is removed. If (e)
     has a forEach method then this routine is applied to each
     element of that collection via that method.           


  */
  dom.attr = function f(e){
    if(2===arguments.length) return e.getAttribute(arguments[1]);


    if(e.forEach){
      e.forEach((x)=>f(x,arguments[1],arguments[2]));



      return e;
    }            
    const key = arguments[1], val = arguments[2];



    if(null===val || undefined===val){
      e.removeAttribute(key);
    }else{
      e.setAttribute(key,val);

    }
    return e;
  };

  const enableDisable = function f(enable){
    var i = 1, n = arguments.length;
    for( ; i < n; ++i ){
................................................................................
      e = new Error("Cannot find DOM element: "+x);
      console.error(e, src);
      throw e;
    }
    return e;
  };






















































































































































































































































































  return F.dom = dom;
})(window.fossil);







<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|









|












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

>

|
|

<
<
<
>
>
>
>
>
>
|

>
>
>
>
|
|
>







 







>
>







 







<

|
|
>
>






|
<
|
<
>







 







|


>
>
|








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







 







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





|
|
|
|
>






>


<
|
<
<
<







 







|
|
|
|
>
>



>
>
|
<
>
>
>

|
<
>
>
>
|
|
|
|
>







 







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


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
...
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
...
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
...
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
...
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
...
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
...
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
  dom.pre = dom.createElemFactory('pre');
  dom.header = dom.createElemFactory('header');
  dom.footer = dom.createElemFactory('footer');
  dom.section = dom.createElemFactory('section');
  dom.span = dom.createElemFactory('span');
  dom.strong = dom.createElemFactory('strong');
  dom.em = dom.createElemFactory('em');

  /**
     Returns a LABEL element. If passed an argument,
     it must be an id or an HTMLElement with an id,
     and that id is set as the 'for' attribute of the
     label. If passed 2 arguments, the 2nd is text or
     a DOM element to append to the label.
  */
  dom.label = function(forElem, text){
    const rc = document.createElement('label');
    if(forElem){
      if(forElem instanceof HTMLElement){
        forElem = this.attr(forElem, 'id');
      }
      dom.attr(rc, 'for', forElem);
    }
    if(text) this.append(rc, text);
    return rc;
  };
  /**
     Returns an IMG element with an optional src
     attribute value.
  */
  dom.img = function(src){
    const e = this.create('img');
    if(src) e.setAttribute('src',src);
    return e;
  };
  /**
     Creates and returns a new anchor element with the given
     optional href and label. If label===true then href is used
     as the label.
  */
  dom.a = function(href,label){
    const e = this.create('a');
    if(href) e.setAttribute('href',href);
    if(label) e.appendChild(dom.text(true===label ? href : label));
    return e;
  };
  dom.hr = dom.createElemFactory('hr');
  dom.br = dom.createElemFactory('br');
  dom.text = (t)=>document.createTextNode(t||'');
  dom.button = function(label){
    const b = this.create('button');
    if(label) b.appendChild(this.text(label));
    return b;
  };
  /**
     Returns a TEXTAREA element.

     Usages:

     ([boolean readonly = false])
     (non-boolean rows[,cols[,readonly=false]])

     Each of the rows/cols/readonly attributes is only set if it is
     truthy.
  */
  dom.textarea = function(){
    const rc = this.create('textarea');
    let rows, cols, readonly;
    if(1===arguments.length){
      if('boolean'===typeof arguments[0]){
        readonly = !!arguments[0];
      }else{
        rows = arguments[0];
      }
    }else if(arguments.length){
      rows = arguments[0];
      cols = arguments[1];
      readonly = arguments[2];
    }
    if(rows) rc.setAttribute('rows',rows);
    if(cols) rc.setAttribute('cols', cols);
    if(readonly) rc.setAttribute('readonly', true);
    return rc;
  };

  /**
     Returns a new SELECT element.
  */
  dom.select = dom.createElemFactory('select');

  /**
     Returns an OPTION element with the given value and label text
     (which defaults to the value).




     Usage:

     (value[, label])
     (selectElement [,value [,label = value]])

     Any forms taking a SELECT element append the new element to the
     given SELECT element.

     If any label is falsy and the value is not then the value is used
     as the label. A non-falsy label value may have any type suitable
     for passing as the 2nd argument to dom.append().

     If the value has the undefined value then it is NOT assigned as
     the option element's value and no label is set unless it has a
     non-undefined value.
  */
  dom.option = function(value,label){
    const a = arguments;
    var sel;
    if(1==a.length){
      if(a[0] instanceof HTMLElement){
        sel = a[0];
................................................................................
      value = a[1];
      label = a[2];
    }
    const o = this.create('option');
    if(undefined !== value){
      o.value = value;
      this.append(o, this.text(label || value));
    }else if(undefined !== label){
      this.append(o, label);
    }
    if(sel) this.append(sel, o);
    return o;
  };
  dom.h = function(level){
    return this.create('h'+level);
  };
................................................................................
  dom.thead = dom.createElemFactoryWithOptionalParent('thead');
  dom.tbody = dom.createElemFactoryWithOptionalParent('tbody');
  dom.tfoot = dom.createElemFactoryWithOptionalParent('tfoot');
  dom.tr = dom.createElemFactoryWithOptionalParent('tr');
  dom.td = dom.createElemFactoryWithOptionalParent('td');
  dom.th = dom.createElemFactoryWithOptionalParent('th');


  /**
     Creates and returns a FIELDSET element, optionaly with a LEGEND
     element added to it. If legendText is an HTMLElement then it is
     appended as-is, else it is assume (if truthy) to be a value
     suitable for passing to dom.append(aLegendElement,...).
  */
  dom.fieldset = function(legendText){
    const fs = this.create('fieldset');
    if(legendText){
      this.append(
        fs,
        (legendText instanceof HTMLElement)

          ? legendText

          : this.append(this.create('legend'),legendText)
      );
    }
    return fs;
  };

  /**
     Appends each argument after the first to the first argument
................................................................................
  */
  dom.append = function f(parent/*,...*/){
    const a = argsToArray(arguments);
    a.shift();
    for(let i in a) {
      var e = a[i];
      if(isArray(e) || e.forEach){
        e.forEach((x)=>f.call(this, parent,x));
        continue;
      }
      if('string'===typeof e
         || 'number'===typeof e
         || 'boolean'===typeof e) e = this.text(e);
      parent.appendChild(e);
    }
    return parent;
  };

  dom.input = function(type){
    return this.attr(this.create('input'), 'type', type);
  };
  /**
     Returns a new CHECKBOX input element.

     Usages:

     ([boolean checked = false])
     (non-boolean value [,boolean checked])
  */
  dom.checkbox = function(value, checked){
    const rc = this.input('checkbox');
    if(1===arguments.length && 'boolean'===typeof value){
      checked = !!value;
      value = undefined;
    }
    if(undefined !== value) rc.value = value;
    if(!!checked) rc.checked = true;
    return rc;
  };
  /**
     Returns a new RADIO input element.

     ([boolean checked = false])
     (string name [,boolean checked])
     (string name, non-boolean value [,boolean checked])
  */
  dom.radio = function(){
    const rc = this.input('radio');
    let name, value, checked;
    if(1===arguments.length && 'boolean'===typeof name){
      checked = arguments[0];
      name = value = undefined;
    }else if(2===arguments.length){
      name = arguments[0];
      if('boolean'===typeof arguments[1]){
        checked = arguments[1];
      }else{
        value = arguments[1];
        checked = undefined;
      }
    }else if(arguments.length){
      name = arguments[0];
      value = arguments[1];
      checked = arguments[2];
    }
    if(name) this.attr(rc, 'name', name);
    if(undefined!==value) rc.value = value;
    if(!!checked) rc.checked = true;
    return rc;
  };

  /**
     Internal impl for addClass(), removeClass().
  */
  const domAddRemoveClass = function f(action,e){
    if(!f.rxSPlus){
      f.rxSPlus = /\s+/;
      f.applyAction = function(e,a,v){
................................................................................
  */
  dom.removeClass = function(e,c){
    const a = argsToArray(arguments);
    a.unshift('remove');
    return domAddRemoveClass.apply(this, a);
  };

  /**
     Toggles CSS class c on e (a single element for forEach-capable
     collection of elements. Returns its first argument.
  */
  dom.toggleClass = function f(e,c){
    if(e.forEach){
      e.forEach((x)=>x.classList.toggle(c));
    }else{
      e.classList.toggle(c);
    }
    return e;
  };

  /**
     Returns true if DOM element e contains CSS class c, else
     false.
  */
  dom.hasClass = function(e,c){
    return (e && e.classList) ? e.classList.contains(c) : false;
  };

  /**
     Each argument after the first may be a single DOM element or a
     container of them with a forEach() method. All such elements are
     appended, in the given order, to the dest element using
     dom.append(dest,theElement). Thus the 2nd and susequent arguments
     may be any type supported as the 2nd argument to that function.

     Returns dest.
  */
  dom.moveTo = function(dest,e){
    const n = arguments.length;
    var i = 1;
    const self = this;
    for( ; i < n; ++i ){
      e = arguments[i];

      this.append(dest, e);



    }
    return dest;
  };
  /**
     Each argument after the first may be a single DOM element
     or a container of them with a forEach() method. For each
     DOM element argument, all children of that DOM element
................................................................................
      old.parentNode.removeChild(old);
    }
  };
  dom.replaceNode.counter = 0;        
  /**
     Two args == getter: (e,key), returns value

     Three or more == setter: (e,key,val[...,keyN,valN]), returns
     e. If val===null or val===undefined then the attribute is
     removed. If (e) has a forEach method then this routine is applied
     to each element of that collection via that method. Each pair of
     keys/values is applied to all elements designated by the first
     argument.
  */
  dom.attr = function f(e){
    if(2===arguments.length) return e.getAttribute(arguments[1]);
    const a = argsToArray(arguments);
    if(e.forEach){ /* Apply to all elements in the collection */
      e.forEach(function(x){

        a[0] = x;
        f.apply(f,a);
      });
      return e;
    }

    a.shift(/*element(s)*/);
    while(a.length){
      const key = a.shift(), val = a.shift();
      if(null===val || undefined===val){
        e.removeAttribute(key);
      }else{
        e.setAttribute(key,val);
      }
    }
    return e;
  };

  const enableDisable = function f(enable){
    var i = 1, n = arguments.length;
    for( ; i < n; ++i ){
................................................................................
      e = new Error("Cannot find DOM element: "+x);
      console.error(e, src);
      throw e;
    }
    return e;
  };

  /**
     "Blinks" the given element a single time for the given number of
     milliseconds, defaulting (if the 2nd argument is falsy or not a
     number) to flashOnce.defaultTimeMs. If a 3rd argument is passed
     in, it must be a function, and it gets callback back at the end
     of the asynchronous flashing processes.

     This will only activate once per element during that timeframe -
     further calls will become no-ops until the blink is
     completed. This routine adds a dataset member to the element for
     the duration of the blink, to allow it to block multiple blinks.

     If passed 2 arguments and the 2nd is a function, it behaves as if
     it were called as (arg1, undefined, arg2).

     Returns e, noting that the flash itself is asynchronous and may
     still be running, or not yet started, when this function returns.
  */
  dom.flashOnce = function f(e,howLongMs,afterFlashCallback){
    if(e.dataset.isBlinking){
      return;
    }
    if(2===arguments.length && 'function' ===typeof howLongMs){
      afterFlashCallback = howLongMs;
      howLongMs = f.defaultTimeMs;
    }
    if(!howLongMs || 'number'!==typeof howLongMs){
      howLongMs = f.defaultTimeMs;
    }
    e.dataset.isBlinking = true;
    const transition = e.style.transition;
    e.style.transition = "opacity "+howLongMs+"ms ease-in-out";
    const opacity = e.style.opacity;
    e.style.opacity = 0;
    setTimeout(function(){
      e.style.transition = transition;
      e.style.opacity = opacity;
      delete e.dataset.isBlinking;
      if(afterFlashCallback) afterFlashCallback();
    }, howLongMs);
    return e;
  };
  dom.flashOnce.defaultTimeMs = 400;
  /**
     A DOM event handler which simply passes event.target
     to dom.flashOnce().
  */
  dom.flashOnce.eventHandler = (event)=>dom.flashOnce(event.target)

  /**
     Attempts to copy the given text to the system clipboard. Returns
     true if it succeeds, else false.
  */
  dom.copyTextToClipboard = function(text){
    if( window.clipboardData && window.clipboardData.setData ){
      window.clipboardData.setData('Text',text);
      return true;
    }else{
      const x = document.createElement("textarea");
      x.style.position = 'fixed';
      x.value = text;
      document.body.appendChild(x);
      x.select();
      var rc;
      try{
        document.execCommand('copy');
        rc = true;
      }catch(err){
        rc = false;
      }finally{
        document.body.removeChild(x);
      }
      return rc;
    }
  };

  /**
     Copies all properties from the 2nd argument (a plain object) into
     the style member of the first argument (DOM element or a
     forEach-capable list of elements). If the 2nd argument is falsy
     or empty, this is a no-op.

     Returns its first argument.
  */
  dom.copyStyle = function f(e, style){
    if(e.forEach){
      e.forEach((x)=>f(x, style));
      return e;
    }
    if(style){
      let k;
      for(k in style){
        if(style.hasOwnProperty(k)) e.style[k] = style[k];
      }
    }
    return e;
  };

  /**
     Parses a string as HTML.

     Usages:

     Array (htmlString)
     DOMElement (DOMElement target, htmlString)

     The first form parses the string as HTML and returns an Array of
     all elements parsed from it. If string is falsy then it returns
     an empty array.

     The second form parses the HTML string and appends all elements
     to the given target element using dom.append(), then returns the
     first argument.

     Caveats:

     - It expects a partial HTML document as input, not a full HTML
     document with a HEAD and BODY tags. Because of how DOMParser
     works, only children of the parsed document's (virtual) body are
     acknowledged by this routine.
  */
  dom.parseHtml = function(){
    let childs, string, tgt;
    if(1===arguments.length){
      string = arguments[0];
    }else if(2==arguments.length){
      tgt = arguments[0];
      string  = arguments[1];
    }
    if(string){
      const newNode = new DOMParser().parseFromString(string, 'text/html');
      childs = newNode.documentElement.querySelector('body');
      childs = childs ? Array.prototype.slice.call(childs.childNodes, 0) : [];
      /* ^^^ we need a clone of the list because reparenting them
         modifies a NodeList they're in. */
    }else{
      childs = [];
    }
    return tgt ? this.moveTo(tgt, childs) : childs;
  };

  /**
     Sets up pseudo-automatic content preview handling between a
     source element (typically a TEXTAREA) and a target rendering
     element (typically a DIV). The selector argument must be one of:

     - A single DOM element
     - A collection of DOM elements with a forEach method.
     - A CSS selector

     Each element in the collection must have the following data
     attributes:

     - data-f-preview-from: is either a DOM element id, WITH a leading
     '#' prefix, or the name of a method (see below). If it's an ID,
     the DOM element must support .value to get the content.

     - data-f-preview-to: the DOM element id of the target "previewer"
       element, WITH a leading '#', or the name of a method (see below).

     - data-f-preview-via: the name of a method (see below).

     - OPTIONAL data-f-preview-as-text: a numeric value. Explained below.

     Each element gets a click handler added to it which does the
     following:

     1) Reads the content from its data-f-preview-from element or, if
     that property refers to a method, calls the method without
     arguments and uses its result as the content.

     2) Passes the content to
     methodNamespace[f-data-post-via](content,callback). f-data-post-via
     is responsible for submitting the preview HTTP request, including
     any parameters the request might require. When the response
     arrives, it must pass the content of the response to its 2nd
     argument, an auto-generated callback installed by this mechanism
     which...

     3) Assigns the response text to the data-f-preview-to element or
     passes it to the function
     methodNamespace[f-data-preview-to](content), as appropriate. If
     data-f-preview-to is a DOM element and data-f-preview-as-text is
     '0' (the default) then the target elements contents are replaced
     with the given content as HTML, else the content is assigned to
     the target's textContent property. (Note that this routine uses
     DOMParser, rather than assignment to innerHTML, to apply
     HTML-format content.)

     The methodNamespace (2nd argument) defaults to fossil.page, and
     any method-name data properties, e.g. data-f-preview-via and
     potentially data-f-preview-from/to, must be a single method name,
     not a property-access-style string. e.g. "myPreview" is legal but
     "foo.myPreview" is not (unless, of course, the method is actually
     named "foo.myPreview" (which is legal but would be
     unconventional)). All such methods are called with
     methodNamespace as their "this".

     An example...

     First an input button:

     <button id='test-preview-connector'
       data-f-preview-from='#fileedit-content-editor' // elem ID or method name
       data-f-preview-via='myPreview' // method name
       data-f-preview-to='#fileedit-tab-preview-wrapper' // elem ID or method name
     >Preview update</button>

     And a sample data-f-preview-via method:

     fossil.page.myPreview = function(content,callback){
       const fd = new FormData();
       fd.append('foo', ...);
       fossil.fetch('preview_forumpost',{
         payload: fd,
         onload: callback,
         onerror: (e)=>{ // only if app-specific handling is needed
           fossil.fetch.onerror(e); // default impl
           ... any app-specific error reporting ...
         }
       });
     };

     Then connect the parts with:

     fossil.connectPagePreviewers('#test-preview-connector');

     Note that the data-f-preview-from, data-f-preview-via, and
     data-f-preview-to selector are not resolved until the button is
     actually clicked, so they need not exist in the DOM at the
     instant when the connection is set up, so long as they can be
     resolved when the preview-refreshing element is clicked.

     Maintenance reminder: this method is not strictly part of
     fossil.dom, but is in its file because it needs access to
     dom.parseHtml() to avoid an innerHTML assignment and all code
     which uses this routine also needs fossil.dom.
  */
  F.connectPagePreviewers = function f(selector,methodNamespace){
    if('string'===typeof selector){
      selector = document.querySelectorAll(selector);
    }else if(!selector.forEach){
      selector = [selector];
    }
    if(!methodNamespace){
      methodNamespace = F.page;
    }
    selector.forEach(function(e){
      e.addEventListener(
        'click', function(r){
          const eTo = '#'===e.dataset.fPreviewTo[0]
                ? document.querySelector(e.dataset.fPreviewTo)
                : methodNamespace[e.dataset.fPreviewTo],
                eFrom = '#'===e.dataset.fPreviewFrom[0]
                ? document.querySelector(e.dataset.fPreviewFrom)
                : methodNamespace[e.dataset.fPreviewFrom],
                asText = +(e.dataset.fPreviewAsText || 0);
          eTo.textContent = "Fetching preview...";
          methodNamespace[e.dataset.fPreviewVia](
            (eFrom instanceof Function ? eFrom.call(methodNamespace) : eFrom.value),
            function(r){
              if(eTo instanceof Function) eTo.call(methodNamespace, r||'');
              else if(!r){
                dom.clearElement(eTo);
              }else if(asText){
                eTo.textContent = r;
              }else{
                dom.parseHtml(dom.clearElement(eTo), r);
              }
            }
          );
        }, false
      );
    });
    return this;
  }/*F.connectPagePreviewers()*/;

  return F.dom = dom;
})(window.fossil);

Added src/fossil.numbered-lines.js.































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function callee(arg){
  /*
    JS counterpart of info.c:output_text_with_line_numbers()
    which ties an event handler to the line numbers to allow
    selection of individual lines or ranges.

    Requires: fossil.bootstrap, fossil.dom, fossil.popupwidget,
    fossil.copybutton
  */
  var tbl = arg || document.querySelectorAll('table.numbered-lines');
  if(tbl && !arg){
    if(tbl.length>1){ /* multiple query results: recurse */
      tbl.forEach( (t)=>callee(t) );
      return;
    }else{/* single query result */
      tbl = tbl[0];
    }
  }
  if(!tbl) return /* no matching elements */;
  const F = window.fossil, D = F.dom;
  const tdLn = tbl.querySelector('td.line-numbers');
  const lineState = {
    urlArgs: (window.location.search||'?')
      .replace(/&?\budc=[^&]*/,'') /* "update display prefs cookie" */
      .replace(/&?\bln=[^&]*/,'') /* inbound line number/range */
      .replace('?&','?'),
    start: 0, end: 0
  };

  const lineTip = new F.PopupWidget({
    style: {
      cursor: 'pointer'
    },
    refresh: function(){
      const link = this.state.link;
      D.clearElement(link);
      if(lineState.start){
        const ls = [lineState.start];
        if(lineState.end) ls.push(lineState.end);
        link.dataset.url = (
          window.location.toString().split('?')[0]
            + lineState.urlArgs + '&ln='+ls.join('-')
        );
        D.append(
          D.clearElement(link),
          ' Copy link to '+(
            ls.length===1 ? 'line ' : 'lines '
          )+ls.join('-')
        );
      }else{
        D.append(link, "No lines selected.");
      }
    },
    init: function(){
      const e = this.e;
      const btnCopy = D.span(),
            link = D.span();
      this.state = {link};
      F.copyButton(btnCopy,{
        copyFromElement: link,
        extractText: ()=>link.dataset.url,
        oncopy: (ev)=>{
          D.flashOnce(ev.target, undefined, ()=>lineTip.hide());
          // arguably too snazzy: F.toast.message("Copied link to clipboard.");
        }
      });
      this.e.addEventListener('click', ()=>btnCopy.click(), false);
      D.append(this.e, btnCopy, link)
    }
  });

  tbl.addEventListener('click', ()=>lineTip.hide(), true);
  
  tdLn.addEventListener('click', function f(ev){
    if('SPAN'!==ev.target.tagName) return;
    else if('number' !== typeof f.mode){
      f.mode = 0 /*0=none selected, 1=1 selected, 2=2 selected*/;
      f.spans = tdLn.querySelectorAll('span');
      f.selected = tdLn.querySelectorAll('span.selected-line');
      f.unselect = (e)=>D.removeClass(e, 'selected-line','start','end');
    }
    ev.stopPropagation();
    const ln = +ev.target.innerText;
    if(2===f.mode){/*Reset selection*/
      f.mode = 0;
    }
    if(0===f.mode){/*Select single line*/
      lineState.end = 0;
      lineState.start = ln;
      f.mode = 1;
    }else if(1===f.mode){
      if(ln === lineState.start){/*Unselect line*/
        lineState.start = 0;
        f.mode = 0;
      }else{/*Select range*/
        if(ln<lineState.start){
          lineState.end = lineState.start;
          lineState.start = ln;
        }else{
          lineState.end = ln;
        }
        f.mode = 2;
      }
    }
    if(f.selected){/*Unmark previously-selected lines.*/
      f.selected.forEach(f.unselect);
      f.selected = undefined;
    }
    if(0===f.mode){
      lineTip.hide();
    }else{/*Mark selected lines*/
      const rect = ev.target.getBoundingClientRect();
      f.selected = [];
      if(f.spans.length>=lineState.start){
        let i = lineState.start, end = lineState.end || lineState.start, span = f.spans[i-1];
        for( ; i<=end && span; span = f.spans[i++] ){
          span.classList.add('selected-line');
          f.selected.push(span);
          if(i===lineState.start) span.classList.add('start');
          if(i===end) span.classList.add('end');
        }
      }
      lineTip.refresh().show(rect.right+3, rect.top-4);
    }
  }, false);
  
})();

Changes to src/fossil.page.fileedit.js.

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
...
507
508
509
510
511
512
513

514
515
516
517
518
519
520
...
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
...
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
...
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
...
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
...
718
719
720
721
722
723
724



























725
726
727
728
729
730
731
...
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
...
848
849
850
851
852
853
854

















855
856
857
858
859
860
861
....
1096
1097
1098
1099
1100
1101
1102











1103
1104
1105
1106
1107
1108



1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
....
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
....
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
....
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232



1233
1234
1235
1236
1237
1238
1239
1240
1241
    e:{/*DOM element(s)*/},
    init: function(domInsertPoint/*insert widget BEFORE this element*/){
      const wrapper = D.addClass(
        D.attr(D.div(),'id','fileedit-stash-selector'),
        'input-with-label'
      );
      const sel = this.e.select = D.select();
      const btnClear = this.e.btnClear
            = D.button("Discard Edits");








      D.append(wrapper, "Local edits (",
               D.append(D.code(),
                        F.storage.storageImplName()),
               "):",
               sel, btnClear);
      D.attr(wrapper, "title", [
        'Locally-edited files. Timestamps are the last local edit time.',
        'Only the',P.config.defaultMaxStashSize,'most recent checkin/file',
        'combinations are retained.',
        'Committing or reloading a file removes it from this list.'
      ].join(' '));
      D.option(D.disable(sel), "(empty)");
      F.page.addEventListener('fileedit-stash-updated',(e)=>this.updateList(e.detail));
      F.page.addEventListener('fileedit-file-loaded',(e)=>this.updateList($stash, e.detail));
      sel.addEventListener('change',function(e){
        const opt = this.selectedOptions[0];
        if(opt && opt._finfo) P.loadFile(opt._finfo);
      });
      if(F.storage.isTransient()){/*Warn if our storage is particularly transient...*/
................................................................................
        D.append(wrapper, D.append(
          D.addClass(D.span(),'warning'),
          "Warning: persistent storage is not available, "+
            "so uncomitted edits will not survive a page reload."
        ));
      }
      domInsertPoint.parentNode.insertBefore(wrapper, domInsertPoint);

      F.confirmer(btnClear, {
        /* must come after insertion into the DOM for the pinSize option to work. */
        pinSize: true,
        confirmText: "DISCARD all local edits?",
        onconfirm: function(e){
          if(P.finfo){
            const stashed = P.getStashedFinfo(P.finfo);
................................................................................
            P.clearStash();
          }
        },
        ticks: F.config.confirmerButtonTicks
      });
      D.addClass(this.e.btnClear,'hidden' /* must not be set until after confirmer is set up!*/);
      $stash._fireStashEvent(/*read the page-load-time stash*/);

      delete this.init;
    },
    /**
       Regenerates the edit selection list.
     */
    updateList: function f(stasher,theFinfo){
      if(!f.compare){
................................................................................
      Object.keys(index).forEach((finfo)=>{
        ilist.push(index[finfo]);
      });
      const self = this;
      D.clearElement(this.e.select);
      if(0===ilist.length){
        D.addClass(this.e.btnClear, 'hidden');
        D.option(D.disable(this.e.select),"No local edits");
        return;
      }
      D.enable(this.e.select);
      D.removeClass(this.e.btnClear, 'hidden');
      D.disable(D.option(this.e.select,0,"Select a local edit..."));
      const currentFinfo = theFinfo || P.finfo || {filename:''};
      ilist.sort(f.compare).forEach(function(finfo,n){
................................................................................
      D.enable(ajaxState.toDisable);
    }
  };

  F.onPageLoad(function() {
    P.base = {tag: E('base')};
    P.base.originalHref = P.base.tag.href;
    P.tabs = new fossil.TabManager('#fileedit-tabs');
    P.e = { /* various DOM elements we work with... */
      taEditor: E('#fileedit-content-editor'),
      taCommentSmall: E('#fileedit-comment'),
      taCommentBig: E('#fileedit-comment-big'),
      taComment: undefined/*gets set to one of taComment{Big,Small}*/,
      ajaxContentTarget: E('#ajax-target'),
      btnCommit: E("#fileedit-btn-commit"),
................................................................................
      selectPreviewMode: E('#select-preview-mode select'),
      selectHtmlEmsWrap: E('#select-preview-html-ems'),
      selectEolWrap:  E('#select-eol-style'),
      selectEol:  E('#select-eol-style select[name=eol]'),
      selectFontSizeWrap: E('#select-font-size'),
      selectDiffWS:  E('select[name=diff_ws]'),
      cbLineNumbersWrap: E('#cb-line-numbers'),
      cbAutoPreview: E('#cb-preview-autoupdate > input[type=checkbox]'),
      previewTarget: E('#fileedit-tab-preview-wrapper'),
      manifestTarget: E('#fileedit-manifest'),
      diffTarget: E('#fileedit-tab-diff-wrapper'),
      cbIsExe: E('input[type=checkbox][name=exec_bit]'),
      cbManifest: E('input[type=checkbox][name=include_manifest]'),
      editStatus: E('#fileedit-edit-status'),
      tabs:{
................................................................................
    }else if(D.hasClass(P.e.taCommentBig,'hidden')){
      P.e.taComment = P.e.taCommentSmall;
    }else{
      P.e.taComment = P.e.taCommentSmall;
      D.addClass(P.e.taCommentBig, 'hidden');
    }
    D.removeClass(P.e.taComment, 'hidden');
    P.tabs.e.container.insertBefore(
      /* Move the status bar between the tab buttons and
         tab panels. Seems to be the best fit in terms of
         functionality and visibility. */
      E('#fossil-status-bar'), P.tabs.e.tabs
    );
    P.tabs.e.container.insertBefore(P.e.editStatus, P.tabs.e.tabs);


    P.tabs.addEventListener(
      /* Set up auto-refresh of the preview tab... */
      'before-switch-to', function(ev){

        if(ev.detail===P.e.tabs.preview){
          P.baseHrefForFile();
          if(P.previewNeedsUpdate && P.e.cbAutoPreview.checked) P.preview();
        }else if(ev.detail===P.e.tabs.diff){
          /* Work around a weird bug where the page gets wider than
             the window when the diff tab is NOT in view and the
             current SBS diff widget is wider than the window. When
................................................................................
          P.baseHrefRestore();
        }else if(ev.detail===P.e.tabs.diff){
          /* See notes in the before-switch-to handler. */
          D.addClass(P.e.diffTarget, 'hidden');
        }
      }
    );




























    F.connectPagePreviewers(
      P.e.tabs.preview.querySelector(
        '#btn-preview-refresh'
      )
    );

................................................................................
    );
    diffButtons.querySelector('button.unified').addEventListener(
      "click",(e)=>P.diff(false), false
    );
    P.e.btnCommit.addEventListener(
      "click",(e)=>P.commit(), false
    );

    F.confirmer(P.e.btnReload, {
      pinSize: true,
      confirmText: "Really reload, losing edits?",
      onconfirm: (e)=>P.unstashContent().loadFile(),
      ticks: F.config.confirmerButtonTicks
    });
    E('#comment-toggle').addEventListener(
      "click",(e)=>P.toggleCommentMode(), false
    );

    P.e.taEditor.addEventListener(
      'change', ()=>P.stashContentChange(), false
    );
    P.e.cbIsExe.addEventListener(
      'change', ()=>P.stashContentChange(true), false
    );
    
    /**
       Cosmetic: jump through some hoops to enable/disable
       certain preview options depending on the current
................................................................................
     P.fileContent(). Returns this object.
  */
  P.setContentMethods = function(getter, setter){
    this.fileContent.get = getter;
    this.fileContent.set = setter;
    return this;
  };


















  /**
     Removes the default editor widget (and any dependent elements)
     from the DOM, adds the given element in its place, removes this
     method from this object, and returns this object.
  */
  P.replaceEditorElement = function(newEditor){
................................................................................
     this page's input fields, and updates the UI with with the
     preview.

     Returns this object, noting that the operation is async.
  */
  P.preview = function f(switchToTab){
    if(!affirmHasFile()) return this;











    const target = this.e.previewTarget,
          self = this;
    const updateView = function(c){
      D.clearElement(target);
      if('string'===typeof c) target.innerHTML = c;
      if(switchToTab) self.tabs.switchToTab(self.e.tabs.preview);



    };
    return this._postPreview(this.fileContent(), updateView);
  };

  /**
     Callback for use with F.connectPagePreviewers()
  */
  P._postPreview = function(content,callback){
    if(!affirmHasFile()) return this;
    if(!content){
      callback(content);
................................................................................
        P.dispatchEvent('fileedit-preview-updated',{
          previewMode: P.previewModes.current,
          mimetype: P.finfo.mimetype,
          element: P.e.previewTarget
        });
      },
      onerror: (e)=>{
        fossil.fetch.onerror(e);
        callback("Error fetching preview: "+e);
      }
    });
    return this;
  };

  /**
................................................................................
    fd.append('content',content);
    if(this.e.selectDiffWS) fd.append('ws',this.e.selectDiffWS.value);
    F.message(
      "Fetching diff..."
    ).fetch('fileedit/diff',{
      payload: fd,
      onload: function(c){
        target.innerHTML = [
          "<div>Diff <code>[",
          self.finfo.checkin,
          "]</code> &rarr; Local Edits</div>",
          c||'No changes.'
        ].join('');
        if(sbs) P.tweakSbsDiffs2();
        F.message('Updated diff.');
        self.tabs.switchToTab(self.e.tabs.diff);
      }
    });
    return this;
  };
................................................................................
          cbDryRun = E('[name=dry_run]'),
          isDryRun = cbDryRun.checked,
          filename = this.finfo.filename;
    if(!f.onload){
      f.onload = function(c){
        const oldFinfo = JSON.parse(JSON.stringify(self.finfo))
        if(c.manifest){
          target.innerHTML = [
            "<h3>Manifest",
            (c.dryRun?" (dry run)":""),
            ": ", F.hashDigits(c.checkin),"</h3>",
            "<code class='fileedit-manifest'>",
            c.manifest,



            "</code></pre>"
          ].join('');
          delete c.manifest/*so we don't stash this with finfo*/;
        }
        const msg = [
          'Committed',
          c.dryRun ? '(dry run)' : '',
          '[', F.hashDigits(c.checkin) ,'].'
        ];







|
|
>
>
>
>
>
>
>
>




|
|
<
<
<
<
<
|







 







>







 







>







 







|







 







|







 







|







 







<
<
<
<
|
<
<
<
>



>







 







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







 







>










|
<
<







 







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







 







>
>
>
>
>
>
>
>
>
>
>
|
<
<
|
|
<
>
>
>
|
<
<
|







 







|







 







|




|







 







|



|
|
>
>
>

|







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
...
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
...
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
...
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
...
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
...
685
686
687
688
689
690
691




692



693
694
695
696
697
698
699
700
701
702
703
704
...
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
...
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
...
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
....
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
....
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
....
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
....
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
    e:{/*DOM element(s)*/},
    init: function(domInsertPoint/*insert widget BEFORE this element*/){
      const wrapper = D.addClass(
        D.attr(D.div(),'id','fileedit-stash-selector'),
        'input-with-label'
      );
      const sel = this.e.select = D.select();
      const btnClear = this.e.btnClear = D.button("Discard Edits"),
            btnHelp = D.append(
              D.addClass(D.div(), "help-buttonlet"),
              'Locally-edited files. Timestamps are the last local edit time. ',
              'Only the ',P.config.defaultMaxStashSize,' most recent files ',
              'are retained. Saving or reloading a file removes it from this list. ',
              D.append(D.code(),F.storage.storageImplName()),
              ' = ',F.storage.storageHelpDescription()
            );

      D.append(wrapper, "Local edits (",
               D.append(D.code(),
                        F.storage.storageImplName()),
               "):",
               btnHelp, sel, btnClear);
      F.helpButtonlets.setup(btnHelp);





      D.option(D.disable(sel), undefined, "(empty)");
      F.page.addEventListener('fileedit-stash-updated',(e)=>this.updateList(e.detail));
      F.page.addEventListener('fileedit-file-loaded',(e)=>this.updateList($stash, e.detail));
      sel.addEventListener('change',function(e){
        const opt = this.selectedOptions[0];
        if(opt && opt._finfo) P.loadFile(opt._finfo);
      });
      if(F.storage.isTransient()){/*Warn if our storage is particularly transient...*/
................................................................................
        D.append(wrapper, D.append(
          D.addClass(D.span(),'warning'),
          "Warning: persistent storage is not available, "+
            "so uncomitted edits will not survive a page reload."
        ));
      }
      domInsertPoint.parentNode.insertBefore(wrapper, domInsertPoint);
      P.tabs.switchToTab(1/*DOM visibility workaround*/);
      F.confirmer(btnClear, {
        /* must come after insertion into the DOM for the pinSize option to work. */
        pinSize: true,
        confirmText: "DISCARD all local edits?",
        onconfirm: function(e){
          if(P.finfo){
            const stashed = P.getStashedFinfo(P.finfo);
................................................................................
            P.clearStash();
          }
        },
        ticks: F.config.confirmerButtonTicks
      });
      D.addClass(this.e.btnClear,'hidden' /* must not be set until after confirmer is set up!*/);
      $stash._fireStashEvent(/*read the page-load-time stash*/);
      P.tabs.switchToTab(0/*DOM visibility workaround*/);
      delete this.init;
    },
    /**
       Regenerates the edit selection list.
     */
    updateList: function f(stasher,theFinfo){
      if(!f.compare){
................................................................................
      Object.keys(index).forEach((finfo)=>{
        ilist.push(index[finfo]);
      });
      const self = this;
      D.clearElement(this.e.select);
      if(0===ilist.length){
        D.addClass(this.e.btnClear, 'hidden');
        D.option(D.disable(this.e.select),undefined,"No local edits");
        return;
      }
      D.enable(this.e.select);
      D.removeClass(this.e.btnClear, 'hidden');
      D.disable(D.option(this.e.select,0,"Select a local edit..."));
      const currentFinfo = theFinfo || P.finfo || {filename:''};
      ilist.sort(f.compare).forEach(function(finfo,n){
................................................................................
      D.enable(ajaxState.toDisable);
    }
  };

  F.onPageLoad(function() {
    P.base = {tag: E('base')};
    P.base.originalHref = P.base.tag.href;
    P.tabs = new F.TabManager('#fileedit-tabs');
    P.e = { /* various DOM elements we work with... */
      taEditor: E('#fileedit-content-editor'),
      taCommentSmall: E('#fileedit-comment'),
      taCommentBig: E('#fileedit-comment-big'),
      taComment: undefined/*gets set to one of taComment{Big,Small}*/,
      ajaxContentTarget: E('#ajax-target'),
      btnCommit: E("#fileedit-btn-commit"),
................................................................................
      selectPreviewMode: E('#select-preview-mode select'),
      selectHtmlEmsWrap: E('#select-preview-html-ems'),
      selectEolWrap:  E('#select-eol-style'),
      selectEol:  E('#select-eol-style select[name=eol]'),
      selectFontSizeWrap: E('#select-font-size'),
      selectDiffWS:  E('select[name=diff_ws]'),
      cbLineNumbersWrap: E('#cb-line-numbers'),
      cbAutoPreview: E('#cb-preview-autorefresh'),
      previewTarget: E('#fileedit-tab-preview-wrapper'),
      manifestTarget: E('#fileedit-manifest'),
      diffTarget: E('#fileedit-tab-diff-wrapper'),
      cbIsExe: E('input[type=checkbox][name=exec_bit]'),
      cbManifest: E('input[type=checkbox][name=include_manifest]'),
      editStatus: E('#fileedit-edit-status'),
      tabs:{
................................................................................
    }else if(D.hasClass(P.e.taCommentBig,'hidden')){
      P.e.taComment = P.e.taCommentSmall;
    }else{
      P.e.taComment = P.e.taCommentSmall;
      D.addClass(P.e.taCommentBig, 'hidden');
    }
    D.removeClass(P.e.taComment, 'hidden');




    P.tabs.addCustomWidget( E('#fossil-status-bar') ).addCustomWidget(P.e.editStatus);



    let currentTab/*used for ctrl-enter switch between editor and preview*/;
    P.tabs.addEventListener(
      /* Set up auto-refresh of the preview tab... */
      'before-switch-to', function(ev){
        currentTab = ev.detail;
        if(ev.detail===P.e.tabs.preview){
          P.baseHrefForFile();
          if(P.previewNeedsUpdate && P.e.cbAutoPreview.checked) P.preview();
        }else if(ev.detail===P.e.tabs.diff){
          /* Work around a weird bug where the page gets wider than
             the window when the diff tab is NOT in view and the
             current SBS diff widget is wider than the window. When
................................................................................
          P.baseHrefRestore();
        }else if(ev.detail===P.e.tabs.diff){
          /* See notes in the before-switch-to handler. */
          D.addClass(P.e.diffTarget, 'hidden');
        }
      }
    );
    ////////////////////////////////////////////////////////////
    // Trigger preview on Ctrl-Enter. This only works on the built-in
    // editor widget, not a client-provided one.
    P.e.taEditor.addEventListener('keydown',function(ev){
      if(ev.ctrlKey && 13 === ev.keyCode){
        ev.preventDefault();
        ev.stopPropagation();
        P.e.taEditor.blur(/*force change event, if needed*/);
        P.tabs.switchToTab(P.e.tabs.preview);
        if(!P.e.cbAutoPreview.checked){/* If NOT in auto-preview mode, trigger an update. */
          P.preview();
        }
      }
    }, false);
    // If we're in the preview tab, have ctrl-enter switch back to the editor.
    document.body.addEventListener('keydown',function(ev){
      if(ev.ctrlKey && 13 === ev.keyCode){
        if(currentTab === P.e.tabs.preview){
          //ev.preventDefault();
          //ev.stopPropagation();
          P.tabs.switchToTab(P.e.tabs.content);
          P.e.taEditor.focus(/*doesn't work for client-supplied editor widget!
                              And it's slow as molasses for long docs, as focus()
                              forces a document reflow.*/);
        }
      }
    }, true);

    F.connectPagePreviewers(
      P.e.tabs.preview.querySelector(
        '#btn-preview-refresh'
      )
    );

................................................................................
    );
    diffButtons.querySelector('button.unified').addEventListener(
      "click",(e)=>P.diff(false), false
    );
    P.e.btnCommit.addEventListener(
      "click",(e)=>P.commit(), false
    );
    P.tabs.switchToTab(1/*DOM visibility workaround*/);
    F.confirmer(P.e.btnReload, {
      pinSize: true,
      confirmText: "Really reload, losing edits?",
      onconfirm: (e)=>P.unstashContent().loadFile(),
      ticks: F.config.confirmerButtonTicks
    });
    E('#comment-toggle').addEventListener(
      "click",(e)=>P.toggleCommentMode(), false
    );

    P.e.taEditor.addEventListener('change', ()=>P.notifyOfChange(), false);


    P.e.cbIsExe.addEventListener(
      'change', ()=>P.stashContentChange(true), false
    );
    
    /**
       Cosmetic: jump through some hoops to enable/disable
       certain preview options depending on the current
................................................................................
     P.fileContent(). Returns this object.
  */
  P.setContentMethods = function(getter, setter){
    this.fileContent.get = getter;
    this.fileContent.set = setter;
    return this;
  };

  /**
     Alerts the editor app that a "change" has happened in the editor.
     When connecting 3rd-party editor widgets to this app, it is (or
     may be) necessary to call this for any "change" events the widget
     emits.  Whether or not "change" means that there were "really"
     edits is irrelevant.

     This function may perform an arbitrary amount of work, so it
     should not be called for every keypress within the editor
     widget. Calling it for "blur" events is generally sufficient, and
     calling it for each Enter keypress is generally reasonable but
     also computationally costly.
  */
  P.notifyOfChange = function(){
    P.stashContentChange();
  };

  /**
     Removes the default editor widget (and any dependent elements)
     from the DOM, adds the given element in its place, removes this
     method from this object, and returns this object.
  */
  P.replaceEditorElement = function(newEditor){
................................................................................
     this page's input fields, and updates the UI with with the
     preview.

     Returns this object, noting that the operation is async.
  */
  P.preview = function f(switchToTab){
    if(!affirmHasFile()) return this;
    return this._postPreview(this.fileContent(), function(c){
      P._previewTo(c);
      if(switchToTab) self.tabs.switchToTab(self.e.tabs.preview);
    });
  };

    /**
     Callback for use with F.connectPagePreviewers(). Gets passed
     the preview content.
  */
  P._previewTo = function(c){
    const target = this.e.previewTarget;


    D.clearElement(target);
    if('string'===typeof c) D.parseHtml(target,c);

    if(F.pikchr){
      F.pikchr.addSrcView(target.querySelectorAll('svg.pikchr'));
    }
  };


  
  /**
     Callback for use with F.connectPagePreviewers()
  */
  P._postPreview = function(content,callback){
    if(!affirmHasFile()) return this;
    if(!content){
      callback(content);
................................................................................
        P.dispatchEvent('fileedit-preview-updated',{
          previewMode: P.previewModes.current,
          mimetype: P.finfo.mimetype,
          element: P.e.previewTarget
        });
      },
      onerror: (e)=>{
        F.fetch.onerror(e);
        callback("Error fetching preview: "+e);
      }
    });
    return this;
  };

  /**
................................................................................
    fd.append('content',content);
    if(this.e.selectDiffWS) fd.append('ws',this.e.selectDiffWS.value);
    F.message(
      "Fetching diff..."
    ).fetch('fileedit/diff',{
      payload: fd,
      onload: function(c){
        D.parseHtml(D.clearElement(target),[
          "<div>Diff <code>[",
          self.finfo.checkin,
          "]</code> &rarr; Local Edits</div>",
          c||'No changes.'
        ].join(''));
        if(sbs) P.tweakSbsDiffs2();
        F.message('Updated diff.');
        self.tabs.switchToTab(self.e.tabs.diff);
      }
    });
    return this;
  };
................................................................................
          cbDryRun = E('[name=dry_run]'),
          isDryRun = cbDryRun.checked,
          filename = this.finfo.filename;
    if(!f.onload){
      f.onload = function(c){
        const oldFinfo = JSON.parse(JSON.stringify(self.finfo))
        if(c.manifest){
          D.parseHtml(D.clearElement(target), [
            "<h3>Manifest",
            (c.dryRun?" (dry run)":""),
            ": ", F.hashDigits(c.checkin),"</h3>",
            "<pre><code class='fileedit-manifest'>",
            c.manifest.replace(/</g,'&lt;'),
            /* ^^^ replace() necessary or this breaks if the manifest
               comment contains an unclosed HTML tags,
               e.g. <script> */
            "</code></pre>"
          ].join(''));
          delete c.manifest/*so we don't stash this with finfo*/;
        }
        const msg = [
          'Committed',
          c.dryRun ? '(dry run)' : '',
          '[', F.hashDigits(c.checkin) ,'].'
        ];

Changes to src/fossil.page.forumpost.js.

1
2
3
4

5














6
7
8
9
10
11
12
..
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
77
78
79
80
81
82
83
84




85
86
87
(function(F/*the fossil object*/){
  "use strict";
  /* JS code for /forumpage and friends. Requires fossil.dom. */
  const P = fossil.page, D = fossil.dom;
















  F.onPageLoad(function(){
    const scrollbarIsVisible = (e)=>e.scrollHeight > e.clientHeight;
    /* Returns an event handler which implements the post expand/collapse toggle
       on contentElem when the given widget is activated. */
    const getWidgetHandler = function(widget, contentElem){
      return function(ev){
        if(ev) ev.preventDefault();
................................................................................
    };

    /* Adds an Expand/Collapse toggle to all div.forumPostBody
       elements which are deemed "too large" (those for which
       scrolling is currently activated because they are taller than
       their max-height). */
    document.querySelectorAll(
      'div.forumHier, div.forumTime, div.forumHierRoot'
    ).forEach(function f(forumPostWrapper){
      const content = forumPostWrapper.querySelector('div.forumPostBody');
      if(!content || !scrollbarIsVisible(content)) return;
      const parent = content.parentElement,
            widget =  D.addClass(
              D.div(),
              'forum-post-collapser','bottom'
................................................................................
        forumPostWrapper.insertBefore(widget, content.nextSibling);
      }else{
        forumPostWrapper.appendChild(widget);
      }
      content.appendChild(rightTapZone);
      rightTapZone.addEventListener('click', widgetEventHandler, false);
      refillTapZone();
    });




  })/*onload callback*/;
  
})(window.fossil);


|
|
>

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







 







|







 







|
>
>
>
>



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
..
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
..
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
(function(F/*the fossil object*/){
  "use strict";
  /* JS code for /forumpage and friends. Requires fossil.dom
     and can optionally use fossil.pikchr. */
  const P = F.page, D = F.dom;

  /**
     When the page is loaded, this handler does the following:

     - Installs expand/collapse UI elements on "long" posts and collapses
     them.
  
     - Any pikchr-generated SVGs get a source-toggle button added to them
     which activates when the mouse is over the image or it is tapped.

     This is a harmless no-op if the current page has neither forum
     post constructs for (1) nor any pikchr images for (2), nor will
     NOT running this code cause any breakage for clients with no JS
     support: this is all "nice-to-have", not required functionality.
  */
  F.onPageLoad(function(){
    const scrollbarIsVisible = (e)=>e.scrollHeight > e.clientHeight;
    /* Returns an event handler which implements the post expand/collapse toggle
       on contentElem when the given widget is activated. */
    const getWidgetHandler = function(widget, contentElem){
      return function(ev){
        if(ev) ev.preventDefault();
................................................................................
    };

    /* Adds an Expand/Collapse toggle to all div.forumPostBody
       elements which are deemed "too large" (those for which
       scrolling is currently activated because they are taller than
       their max-height). */
    document.querySelectorAll(
      'div.forumHier, div.forumTime, div.forumHierRoot, div.forumEdit'
    ).forEach(function f(forumPostWrapper){
      const content = forumPostWrapper.querySelector('div.forumPostBody');
      if(!content || !scrollbarIsVisible(content)) return;
      const parent = content.parentElement,
            widget =  D.addClass(
              D.div(),
              'forum-post-collapser','bottom'
................................................................................
        forumPostWrapper.insertBefore(widget, content.nextSibling);
      }else{
        forumPostWrapper.appendChild(widget);
      }
      content.appendChild(rightTapZone);
      rightTapZone.addEventListener('click', widgetEventHandler, false);
      refillTapZone();
    })/*F.onPageLoad()*/;

    if(F.pikchr){
      F.pikchr.addSrcView();
    }
  })/*onload callback*/;
  
})(window.fossil);

Added src/fossil.page.pikchrshow.js.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function(F/*the fossil object*/){
  "use strict";
  /**
     Client-side implementation of the /pikchrshow app. Requires that
     the fossil JS bootstrapping is complete and that these fossil JS
     APIs have been installed: fossil.fetch, fossil.dom,
     fossil.copybutton, fossil.popupwidget, fossil.storage
  */
  const E = (s)=>document.querySelector(s),
        D = F.dom,
        P = F.page;

  P.previewMode = 0 /*0==rendered SVG, 1==pikchr text markdown,
                      2==pikchr text fossil, 3==raw SVG. */
  P.response = {/*stashed state for the server's preview response*/
    isError: false,
    inputText: undefined /* value of the editor field at render-time */,
    raw: undefined /* raw response text/HTML from server */,
    rawSvg: undefined /* plain-text SVG part of responses. Required
                         because the browser will convert \u00a0 to
                         &nbsp; if we extract the SVG from the DOM,
                         resulting in illegal SVG. */
  };

  /**
     If string r contains an SVG element, this returns that section
     of the string, else it returns falsy.
   */
  const getResponseSvg = function(r){
    const i0 = r.indexOf("<svg");
    if(i0>=0){
      const i1 = r.indexOf("</svg");
      return r.substring(i0,i1+6);
    }
    return '';
  };

  F.onPageLoad(function() {
    document.body.classList.add('pikchrshow');
    P.e = { /* various DOM elements we work with... */
      previewTarget: E('#pikchrshow-output'),
      previewLegend: E('#pikchrshow-output-wrapper > legend'),
      previewCopyButton: D.attr(
        D.addClass(D.span(),'copy-button'),
        'id','preview-copy-button' 
      ),
      previewModeLabel: D.label('preview-copy-button'),
      btnSubmit: E('#pikchr-submit-preview'),
      btnStash: E('#pikchr-stash'),
      btnUnstash: E('#pikchr-unstash'),
      btnClearStash: E('#pikchr-clear-stash'),
      cbDarkMode: E('#flipcolors-wrapper > input[type=checkbox]'),
      taContent: E('#content'),
      taPreviewText: D.textarea(20,0,true),
      uiControls: E('#pikchrshow-controls'),
      previewModeToggle: D.button("Preview mode"),
      markupAlignDefault: D.attr(D.radio('markup-align','',true),
                                 'id','markup-align-default'),
      markupAlignCenter: D.attr(D.radio('markup-align','center'),
                                'id','markup-align-center'),
      markupAlignIndent: D.attr(D.radio('markup-align','indent'),
                                'id','markup-align-indent'),
      markupAlignWrapper: D.addClass(D.span(), 'input-with-label')
    };

    ////////////////////////////////////////////////////////////
    // Setup markup alignment selection...
    const alignEvent = function(ev){
      /* Update markdown/fossil wiki preview if it's active */
      if(P.previewMode==1 || P.previewMode==2){
        P.renderPreview();
      }
    };
    P.e.markupAlignRadios = [
      P.e.markupAlignDefault,
      P.e.markupAlignCenter,
      P.e.markupAlignIndent
    ];
    D.append(P.e.markupAlignWrapper,
             D.addClass(D.append(D.span(),"align:"),
                        'v-align-middle'));
    P.e.markupAlignRadios.forEach(
      function(e){
        e.addEventListener('change', alignEvent, false);
        D.append(P.e.markupAlignWrapper,
                 D.addClass([
                   e,
                   D.label(e, e.value || "left")
                 ], 'v-align-middle'));
      }
    );

    ////////////////////////////////////////////////////////////
    // Setup the preview fieldset's LEGEND element...
    D.append( P.e.previewLegend,
              P.e.previewModeToggle,
              '\u00a0',
              P.e.previewCopyButton,
              P.e.previewModeLabel,
              P.e.markupAlignWrapper );

    ////////////////////////////////////////////////////////////
    // Trigger preview on Ctrl-Enter.
    P.e.taContent.addEventListener('keydown',function(ev){
      if(ev.ctrlKey && 13 === ev.keyCode) P.preview();
    }, false);

    ////////////////////////////////////////////////////////////
    // Setup clipboard-copy of markup/SVG...
    F.copyButton(P.e.previewCopyButton, {copyFromElement: P.e.taPreviewText});
    P.e.previewModeLabel.addEventListener('click', ()=>P.e.previewCopyButton.click(), false);

    ////////////////////////////////////////////////////////////
    // Set up dark mode simulator...
    P.e.cbDarkMode.addEventListener('change', function(ev){
      if(ev.target.checked) D.addClass(P.e.previewTarget, 'dark-mode');
      else D.removeClass(P.e.previewTarget, 'dark-mode');
    }, false);
    if(P.e.cbDarkMode.checked) D.addClass(P.e.previewTarget, 'dark-mode');

    ////////////////////////////////////////////////////////////
    // Set up preview update and preview mode toggle...
    P.e.btnSubmit.addEventListener('click', ()=>P.preview(), false);
    P.e.previewModeToggle.addEventListener('click', function(){
      /* Rotate through the 4 available preview modes */
      P.previewMode = ++P.previewMode % 4;
      P.renderPreview();
    }, false);

    ////////////////////////////////////////////////////////////
    // Set up selection list of predefined scripts...
    if(true){
      const selectScript = P.e.selectScript = D.select(),
            cbAutoPreview = P.e.cbAutoPreview =
            D.attr(D.checkbox(true),'id', 'cb-auto-preview'),
            cbWrap = D.addClass(D.div(),'input-with-label')
      ;
      D.append(
        cbWrap,
        selectScript,
        cbAutoPreview,
        D.label(cbAutoPreview,"Auto-preview?"),
        F.helpButtonlets.create(
          D.append(D.div(),
                   'Auto-preview automatically previews selected ',
                   'built-in pikchr scripts by sending them to ',
                   'the server for rendering. Not recommended on a ',
                   'slow connection/server.',
                   D.br(),D.br(),
                   'Pikchr scripts may also be dragged/dropped from ',
                   'the local filesystem into the text area, if the ',
                   'environment supports it, but the auto-preview ',
                   'option does not apply to them.'
                  )
        )
      )/*.childNodes.forEach(function(ch){
        ch.style.margin = "0 0.25em";
      })*/;
      D.append(P.e.uiControls, cbWrap);
      P.predefinedPiks.forEach(function(script,ndx){
        const opt = D.option(script.code ? script.code.trim() :'', script.name);
        D.append(selectScript, opt);
        opt.$_sampleScript = script /* for response caching purposes */;
        if(!ndx) selectScript.selectedIndex = 0 /*timing/ordering workaround*/;
        if(!script.code) D.disable(opt);
      });
      delete P.predefinedPiks;
      selectScript.addEventListener('change', function(ev){
        const val = ev.target.value;
        if(!val) return;
        const opt = ev.target.selectedOptions[0];
        P.e.taContent.value = val;
        if(cbAutoPreview.checked){
          P.preview.$_sampleScript = opt.$_sampleScript;
          P.preview();
        }
      }, false);
    }
    
    ////////////////////////////////////////////////////////////
    // Move dark mode checkbox to the end and add a help buttonlet
    D.append(
      P.e.uiControls,
      D.append(
        P.e.cbDarkMode.parentNode/*the .input-with-label element*/,
        F.helpButtonlets.create(
          D.div(),
          'Dark mode changes the colors of rendered SVG to ',
          'make them more visible in dark-themed skins. ',
          'This only changes (using CSS) how they are rendered, ',
          'not any actual colors written in the script.',
          D.br(), D.br(),
          'In some color combinations, certain browsers might ',
          'cause the SVG image to blur considerably with this ',
          'setting enabled!'
        )
      )
    );

    ////////////////////////////////////////////////////////////
    // File drag/drop pikchr scripts into P.e.taContent.
    // Adapted from: https://stackoverflow.com/a/58677161
    const dropHighlight = P.e.taContent;
    const dropEvents = {
      drop: function(ev){
        //ev.stopPropagation();
        ev.preventDefault();
        D.removeClass(dropHighlight, 'dragover');
        const file = ev.dataTransfer.files[0];
        if(file) {
          const reader = new FileReader();
          reader.addEventListener(
            'load', function(e) {P.e.taContent.value = e.target.result}, false
          );
          reader.readAsText(file, "UTF-8");
        }
      },
      dragenter: function(ev){
        //ev.stopPropagation();
        ev.preventDefault();
        ev.dataTransfer.dropEffect = "copy";
        D.addClass(dropHighlight, 'dragover');
        //console.debug("dragenter");
      },
      dragover: function(ev){
        //ev.stopPropagation();
        ev.preventDefault();
        //console.debug("dragover");
      },
      dragend: function(ev){
        //ev.stopPropagation();
        ev.preventDefault();
        //console.debug("dragend");
      },
      dragleave: function(ev){
        //ev.stopPropagation();
        ev.preventDefault();
        D.removeClass(dropHighlight, 'dragover');
        //console.debug("dragleave");
      }
    };
    /*
      The idea here is to accept drops at multiple points or, ideally,
      document.body, and apply them to P.e.taContent, but the precise
      combination of event handling needed to pull this off is eluding
      me.
    */
    [P.e.taContent
     //P.e.previewTarget,// works only until we drag over the SVG element!
     //document.body
     /* ideally we'd link only to document.body, but the events seem to
        get out of whack, with dropleave being triggered
        at unexpected points. */
    ].forEach(function(e){
        Object.keys(dropEvents).forEach(
          (k)=>e.addEventListener(k, dropEvents[k], true)
        );
    });

    ////////////////////////////////////////////////////////////
    // Setup stash/unstash
    const stashKey = 'pikchrshow-stash';
    P.e.btnStash.addEventListener('click', function(){
      const val = P.e.taContent.value;
      if(val){
        F.storage.set(stashKey, val);
        D.enable(P.e.btnUnstash);
        F.toast.message("Stashed pikchr.");
      }
    }, false);
    P.e.btnUnstash.addEventListener('click', function(){
      const val = F.storage.get(stashKey);
      P.e.taContent.value = val || '';
    }, false);
    P.e.btnClearStash.addEventListener('click', function(){
      F.storage.remove(stashKey);
      D.disable(P.e.btnUnstash);
      F.toast.message("Cleared pikchr stash.");
    }, false);
    F.helpButtonlets.create(P.e.btnClearStash.nextElementSibling);
    // If we have stashed contents, enable Unstash, else disable it:
    if(F.storage.contains(stashKey)) D.enable(P.e.btnUnstash);
    else D.disable(P.e.btnUnstash);

    ////////////////////////////////////////////////////////////
    // If we start with content, get it in sync with the state
    // generated by P.preview(). Normally the server pre-populates it
    // with an example.
    let needsPreview;
    if(!P.e.taContent.value){
      P.e.taContent.value = F.storage.get(stashKey,'');
      needsPreview = true;
    }
    if(P.e.taContent.value){
      /* Fill our "response" state so that renderPreview() can work */
      P.response.inputText = P.e.taContent.value;
      P.response.raw = P.e.previewTarget.innerHTML;
      P.response.rawSvg = getResponseSvg(
        P.response.raw /*note that this is already in the DOM,
                         which means that the browser has already mangled
                         \u00a0 to &nbsp;, so...*/.split('&nbsp;').join('\u00a0'));
      if(needsPreview) P.preview();
      else{
        /*If it's from the server, it's already rendered, but this
          gets all labels/headers in sync.*/
        P.renderPreview();
      }
    }    
  }/*F.onPageLoad()*/);

  /**
     Updates the preview view based on the current preview mode and
     error state.
  */
  P.renderPreview = function f(){
    if(!f.hasOwnProperty('rxNonce')){
      f.rxNonce = /<!--.+-->\r?\n?/g /*pikchr nonce comments*/;
      f.showMarkupAlignment = function(showIt){
        P.e.markupAlignWrapper.classList[showIt ? 'remove' : 'add']('hidden');
      };
      f.getMarkupAlignmentClass = function(){
        if(P.e.markupAlignCenter.checked) return ' center';
        else if(P.e.markupAlignIndent.checked) return ' indent';
        return '';
      };
      f.getSvgNode = function(txt){
        const childs = D.parseHtml(txt);
        const wrapper = childs.filter((e)=>'DIV'===e.tagName)[0];
        return wrapper ? wrapper.querySelector('svg.pikchr') : undefined;
      };
    }
    const preTgt = this.e.previewTarget;
    if(this.response.isError){
      D.append(D.clearElement(preTgt), D.parseHtml(P.response.raw));
      D.addClass(preTgt, 'error');
      this.e.previewModeLabel.innerText = "Error";
      return;
    }
    D.removeClass(preTgt, 'error');
    D.removeClass(this.e.previewCopyButton, 'disabled');
    D.removeClass(this.e.markupAlignWrapper, 'hidden');
    D.enable(this.e.previewModeToggle, this.e.markupAlignRadios);
    let label, svg;
    switch(this.previewMode){
    case 0:
      label = "SVG";
      f.showMarkupAlignment(false);
      D.parseHtml(D.clearElement(preTgt), P.response.raw);
      svg = preTgt.querySelector('svg.pikchr');
      if(svg && P.response.rawSvg){ /*for copy button*/
        this.e.taPreviewText.value = P.response.rawSvg;
        F.pikchr.addSrcView(svg);
      }
      break;
    case 1:
      label = "Markdown";
      f.showMarkupAlignment(true);
      this.e.taPreviewText.value = [
        '```pikchr'+f.getMarkupAlignmentClass(),
        this.response.inputText.trim(), '```'
      ].join('\n');
      D.append(D.clearElement(preTgt), this.e.taPreviewText);
      break;
    case 2:
      label = "Fossil wiki";
      f.showMarkupAlignment(true);
      this.e.taPreviewText.value = [
        '<verbatim type="pikchr',
        f.getMarkupAlignmentClass(),
        '">', this.response.inputText.trim(), '</verbatim>'
      ].join('');
      D.append(D.clearElement(preTgt), this.e.taPreviewText);
      break;
    case 3:
      label = "Raw SVG";
      f.showMarkupAlignment(false);
      svg = f.getSvgNode(this.response.raw);
      if(svg){
        this.e.taPreviewText.value =
          P.response.rawSvg || "Error extracting SVG element.";
      }else{
        this.e.taPreviewText.value = "ERROR parsing response HTML:\n"+
          this.response.raw;
        console.error("svg parsed HTML nodes:",childs);
      }
      D.append(D.clearElement(preTgt), this.e.taPreviewText);
      break;
    }
    this.e.previewModeLabel.innerText = label;
  };

  /**
     Fetches the preview from the server and updates the preview to
     the rendered SVG content or error report.
  */
  P.preview = function fp(){
    if(!fp.hasOwnProperty('toDisable')){
      fp.toDisable = [
        /* input elements to disable during ajax operations */
        this.e.btnSubmit, this.e.taContent,
        this.e.cbAutoPreview, this.e.selectScript,
        this.e.btnStash, this.e.btnClearStash
        /* handled separately: previewModeToggle, previewCopyButton,
           markupAlignRadios */
      ];
      fp.target = this.e.previewTarget;
      fp.updateView = function(c,isError){
        P.previewMode = 0;
        P.response.raw = c;
        P.response.rawSvg = getResponseSvg(c);
        P.response.isError = isError;
        D.enable(fp.toDisable);
        P.renderPreview();
      };
    }
    D.disable(fp.toDisable, this.e.previewModeToggle, this.e.markupAlignRadios);
    D.addClass(this.e.markupAlignWrapper, 'hidden');
    D.addClass(this.e.previewCopyButton, 'disabled');
    const content = this.e.taContent.value.trim();
    this.response.raw = this.response.rawSvg = undefined;
    this.response.inputText = content;
    const sampleScript = fp.$_sampleScript;
    delete fp.$_sampleScript;
    if(sampleScript && sampleScript.cached){
      fp.updateView(sampleScript.cached, false);
      return this;
    }
    if(!content){
      fp.updateView("No pikchr content!",true);
      return this;
    }
    const self = this;
    const fd = new FormData();
    fd.append('ajax', true);
    fd.append('content',content);
    F.fetch('pikchrshow',{
      payload: fd,
      responseHeaders: 'x-pikchrshow-is-error',
      onload: (r,isErrHeader)=>{
        const isErr = +isErrHeader ? true : false;
        if(!isErr && sampleScript){
          sampleScript.cached = r;
        }
        fp.updateView(r,isErr);
      },
      onerror: (e)=>{
        F.fetch.onerror(e);
        fp.updateView("Error fetching preview: "+e, true);
      }
    });
    return this;
  }/*preview()*/;

  /**
     Predefined scripts. Each entry is an object:

     {
     name: required string,

     code: optional code string. An entry with no code
           is treated like a separator in the resulting
           SELECT element (a disabled OPTION).

     }
  */
  P.predefinedPiks = [
    {name: "-- Example Scripts --"},
/*
  The following were imported from the pikchr test scripts:

  https://fossil-scm.org/pikchr/dir/examples
*/
{name:"Cardinal headings",code:`   linerad = 5px
C: circle "Center" rad 150%
   circle "N"  at 1.0 n  of C; arrow from C to last chop ->
   circle "NE" at 1.0 ne of C; arrow from C to last chop <-
   circle "E"  at 1.0 e  of C; arrow from C to last chop <->
   circle "SE" at 1.0 se of C; arrow from C to last chop ->
   circle "S"  at 1.0 s  of C; arrow from C to last chop <-
   circle "SW" at 1.0 sw of C; arrow from C to last chop <->
   circle "W"  at 1.0 w  of C; arrow from C to last chop ->
   circle "NW" at 1.0 nw of C; arrow from C to last chop <-
   arrow from 2nd circle to 3rd circle chop
   arrow from 4th circle to 3rd circle chop
   arrow from SW to S chop <->
   circle "ESE" at 2.0 heading 112.5 from Center \
      thickness 150% fill lightblue radius 75%
   arrow from Center to ESE thickness 150% <-> chop
   arrow from ESE up 1.35 then to NE chop
   line dashed <- from E.e to (ESE.x,E.y)
   line dotted <-> thickness 50% from N to NW chop
`},{name:"Core object types",code:`AllObjects: [

# First row of objects
box "box"
box rad 10px "box (with" "rounded" "corners)" at 1in right of previous
circle "circle" at 1in right of previous
ellipse "ellipse" at 1in right of previous

# second row of objects
OVAL1: oval "oval" at 1in below first box
oval "(tall &amp;" "thin)" "oval" width OVAL1.height height OVAL1.width \
    at 1in right of previous
cylinder "cylinder" at 1in right of previous
file "file" at 1in right of previous

# third row shows line-type objects
dot "dot" above at 1in below first oval
line right from 1.8cm right of previous "lines" above
arrow right from 1.8cm right of previous "arrows" above
spline from 1.8cm right of previous \
   go right .15 then .3 heading 30 then .5 heading 160 then .4 heading 20 \
   then right .15
"splines" at 3rd vertex of previous

# The third vertex of the spline is not actually on the drawn
# curve.  The third vertex is a control point.  To see its actual
# position, uncomment the following line:
#dot color red at 3rd vertex of previous spline

# Draw various lines below the first line
line dashed right from 0.3cm below start of previous line
line dotted right from 0.3cm below start of previous
line thin   right from 0.3cm below start of previous
line thick  right from 0.3cm below start of previous


# Draw arrows with different arrowhead configurations below
# the first arrow
arrow <-  right from 0.4cm below start of previous arrow
arrow <-> right from 0.4cm below start of previous

# Draw splines with different arrowhead configurations below
# the first spline
spline same from .4cm below start of first spline ->
spline same from .4cm below start of previous <-
spline same from .4cm below start of previous <->

] # end of AllObjects

# Label the whole diagram
text "Examples Of Pikchr Objects" big bold  at .8cm above north of AllObjects
`},{name:"Swimlanes",code:`    $laneh = 0.75

    # Draw the lanes
    down
    box width 3.5in height $laneh fill 0xacc9e3
    box same fill 0xc5d8ef
    box same as first box
    box same as 2nd box
    line from 1st box.sw+(0.2,0) up until even with 1st box.n \
      "Alan" above aligned
    line from 2nd box.sw+(0.2,0) up until even with 2nd box.n \
      "Betty" above aligned
    line from 3rd box.sw+(0.2,0) up until even with 3rd box.n \
      "Charlie" above aligned
    line from 4th box.sw+(0.2,0) up until even with 4th box.n \
       "Darlene" above aligned

    # fill in content for the Alice lane
    right
A1: circle rad 0.1in at end of first line + (0.2,-0.2) \
       fill white thickness 1.5px "1" 
    arrow right 50%
    circle same "2"
    arrow right until even with first box.e - (0.65,0.0)
    ellipse "future" fit fill white height 0.2 width 0.5 thickness 1.5px
A3: circle same at A1+(0.8,-0.3) "3" fill 0xc0c0c0
    arrow from A1 to last circle chop "fork!" below aligned

    # content for the Betty lane
B1: circle same as A1 at A1-(0,$laneh) "1"
    arrow right 50%
    circle same "2"
    arrow right until even with first ellipse.w
    ellipse same "future"
B3: circle same at A3-(0,$laneh) "3"
    arrow right 50%
    circle same as A3 "4"
    arrow from B1 to 2nd last circle chop

    # content for the Charlie lane
C1: circle same as A1 at B1-(0,$laneh) "1"
    arrow 50%
    circle same "2"
    arrow right 0.8in "goes" "offline"
C5: circle same as A3 "5"
    arrow right until even with first ellipse.w \
      "back online" above "pushes 5" below "pulls 3 &amp; 4" below
    ellipse same "future"

    # content for the Darlene lane
D1: circle same as A1 at C1-(0,$laneh) "1"
    arrow 50%
    circle same "2"
    arrow right until even with C5.w
    circle same "5"
    arrow 50%
    circle same as A3 "6"
    arrow right until even with first ellipse.w
    ellipse same "future"
D3: circle same as B3 at B3-(0,2*$laneh) "3"
    arrow 50%
    circle same "4"
    arrow from D1 to D3 chop
`}

  ];
  
})(window.fossil);

Added src/fossil.page.wikiedit-wysiwyg-legacy.js.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/**
   A slight adaptation of fossil's legacy wysiwyg wiki editor which
   makes it usable with the newer editor's edit widget replacement
   API.

   Requires: window.fossil, fossil.dom, and that the current page is
   /wikiedit. If called from another page it returns without effect.
*/
(function(F/*fossil object*/){
  'use strict';
  if(!F || !F.page || F.page.name!=='wikiedit') return;

  const D = F.dom;

  ////////////////////////////////////////////////////////////////////////
  // Install an app-specific stylesheet...
  (function(){
    const head = document.head || document.querySelector('head'),
          styleTag = document.createElement('style'),
          styleCSS = `
.intLink { cursor: pointer; }
img.intLink { border: 0; }
#wysiwyg-container {
  display: flex;
  flex-direction: column;
  max-width: 100% /* w/o this, toolbars don't wrap properly! */
}
#wysiwygBox {
  border: 1px solid rgba(127,127,127,0.3);
  border-radius: 0.25em;
  padding: 0.25em 1em;
  margin: 0;
  overflow: auto;
  min-height: 20em;
  resize: vertical;
}
#wysiwygEditMode { /* wrapper for radio buttons */
  border: 1px solid rgba(127,127,127,0.3);
  border-radius: 0.25em;
  padding: 0 0.35em 0 0.35em
}
#wysiwygEditMode > * {
  vertical-align: text-top;
}
#wysiwygEditMode label { cursor: pointer; }
#wysiwyg-toolbars {
  margin: 0 0 0.25em 0;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  align-items: flex-start;
}
#wysiwyg-toolbars > * {
  margin: 0 0.5em 0.25em 0;
}
#wysiwyg-toolBar1, #wysiwyg-toolBar2 {
  margin: 0 0.2em 0.2em 0;
  display: flex;
  flex-flow: row wrap;
}
#wysiwyg-toolBar1 > * { /* formatting buttons */
  vertical-align: middle;
  margin: 0 0.25em 0.25em 0;
}
#wysiwyg-toolBar2 > * { /* icons */
  border: 1px solid rgba(127,127,127,0.3);
  vertical-align: baseline;
  margin: 0.1em;
}
`;
    head.appendChild(styleTag);
    /* Adapted from https://stackoverflow.com/a/524721 */
    styleTag.type = 'text/css';
    D.append(styleTag, styleCSS);
  })();

  const outerContainer = D.attr(D.div(), 'id', 'wysiwyg-container'),
        toolbars = D.attr(D.div(), 'id', 'wysiwyg-toolbars'),
        toolbar1 = D.attr(D.div(), 'id', 'wysiwyg-toolBar1'),
        // ^^^ formatting options
        toolbar2 = D.attr(D.div(), 'id', 'wysiwyg-toolBar2')
        // ^^^^ action icon buttons
  ;
  D.append(outerContainer, D.append(toolbars, toolbar1, toolbar2));

  /** Returns a function which simplifies adding a list of options
      to the given select element. See below for example usage. */
  const addOptions = function(select){
    return function ff(value, label){
      D.option(select, value, label || value);
      return ff;
    };
  };

  ////////////////////////////////////////////////////////////////////////
  // Edit mode selection (radio buttons).
  const radio0 =
        D.attr(
          D.input('radio'),
          'name','wysiwyg-mode',
          'id', 'wysiwyg-mode-0',
          'value',0,
          'checked',true),
        radio1 = D.attr(
          D.input('radio'),
          'id','wysiwyg-mode-1',
          'name','wysiwyg-mode',
          'value',1),
        radios = D.append(
          D.attr(D.span(), 'id', 'wysiwygEditMode'),
          radio0, D.append(
            D.attr(D.label(), 'for', 'wysiwyg-mode-0'),
            "WYSIWYG"
          ),
          radio1, D.append(
            D.attr(D.label(), 'for', 'wysiwyg-mode-1'),
            "Raw HTML"
          )
        );
  D.append(toolbar1, radios);
  const radioHandler = function(){setDocMode(+this.value)};
  radio0.addEventListener('change',radioHandler, false);
  radio1.addEventListener('change',radioHandler, false);


  ////////////////////////////////////////////////////////////////////////
  // Text formatting options...
  var select;
  select = D.addClass(D.select(), 'format');
  select.dataset.format = "formatblock";
  D.append(toolbar1, select);
  addOptions(select)(
    '', '- formatting -')(
    "h1", "Title 1 <h1>")(
    "h2", "Title 2 <h2>")(
    "h3", "Title 3 <h3>")(
    "h4", "Title 4 <h4>")(
    "h5", "Title 5 <h5>")(
    "h6", "Subtitle <h6>")(
    "p", "Paragraph <p>")(
    "pre", "Preformatted <pre>");

  select = D.addClass(D.select(), 'format');
  select.dataset.format = "fontname";
  D.append(toolbar1, select);
  D.addClass(
    D.option(select, '', '- font -'),
    "heading"
  );
  addOptions(select)(
    'Arial')(
    'Arial Black')(
    'Courier New')(
    'Times New Roman');

  select = D.addClass(D.select(), 'format');
  D.append(toolbar1, select);
  select.dataset.format = "fontsize";
  D.addClass(
    D.option(select, '', '- size -'),
    "heading"
  );
  addOptions(select)(
    "1", "Very small")(
    "2", "A bit small")(
    "3", "Normal")(
    "4", "Medium-large")(
    "5", "Big")(
    "6", "Very big")(
    "7", "Maximum");

  select = D.addClass(D.select(), 'format');
  D.append(toolbar1, select);
  select.dataset.format = 'forecolor';
  D.addClass(
    D.option(select, '', '- color -'),
    "heading"
  );
  addOptions(select)(
    "red", "Red")(
    "blue", "Blue")(
    "green", "Green")(
    "black", "Black")(
    "grey", "Grey")(
    "yellow", "Yellow")(
    "cyan", "Cyan")(
    "magenta", "Magenta");


  ////////////////////////////////////////////////////////////////////////
  // Icon-based toolbar...
  /**
     Inject the icons...

     mkbuiltins strips anything which looks like a C++-style comment,
     even if it's in a string literal, and thus the runs of "/"
     characters in the DOM element data attributes have been mangled
     to work around that: we simply use \x2f for every 2nd slash.
  */
  (function f(title,format,src){
    const img = D.img();
    D.append(toolbar2, img);
    D.addClass(img, 'intLink');
    D.attr(img, 'title', title);
    img.dataset.format = format;
    D.attr(img, 'src', 'string'===typeof src ? src : src.join(''));
    return f;
  })(
    'Undo', 'undo',
    ["data:image/gif;base64,R0lGODlhFgAWAOMKADljwliE33mOrpGjuYKl8aezxqPD+7",
     "/I19DV3NHa7P/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "/\x2f/\x2f/\x2f/yH5BAEKAA8ALAAAAAAWABYAAARR8MlJq704680",
     "7TkaYeJJBnES4EeUJvIGapWYAC0CsocQ7SDlWJkAkCA6ToMYWIARGQF3mRQVIEjkkSVLIbSfE",
     "whdRIH4fh/DZMICe3/C4nBQBADs="]
  )(
    'Redo','redo',
    ["data:image/gif;base64,R0lGODlhFgAWAMIHAB1ChDljwl9vj1iE34Kl8aPD+7/I1/",
     "/\x2f/yH5BAEKAAcALAAAAAAWABYAAANKeLrc/jDKSesyphi7SiEgsVXZEATDICqBVJjpqWZt9Na",
     "EDNbQK1wCQsxlYnxMAImhyDoFAElJasRRvAZVRqqQXUy7Cgx4TC6bswkAOw=="]
  )(
    "Remove formatting",
    "removeFormat",
    ["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AA",
     "AABGdBTUEAALGPC/xhBQAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwA",
     "AAAd0SU1FB9oECQMCKPI8CIIAAAAIdEVYdENvbW1lbnQA9syWvwAAAuhJREFUOMtjYBgFxAB5",
     "01ZWBvVaL2nHnlmk6mXCJbF69zU+Hz/9fB5O1lx+bg45qhl8/fYr5it3XrP/YWTUvvvk3VeqG",
     "Xz70TvbJy8+Wv39+2/Hz19/mGwjZzuTYjALuoBv9jImaXHeyD3H7kU8fPj2ICML8z92dlbtMz",
     "deiG3fco7J08foH1kurkm3E9iw54YvKwuTuom+LPt/BgbWf3/\x2fsf37/1/c02cCG1lB8f/\x2ff95",
     "DZx74MTMzshhoSm6szrQ/a6Ir/Z2RkfEjBxuLYFpDiDi6Af/\x2f/2ckaHBp7+7wmavP5n76+P2C",
     "lrLIYl8H9W36auJCbCxM4szMTJac7Kza/\x2f/\x2fR3H1w2cfWAgafPbqs5g7D95++/P1B4+ECK8tA",
     "wMDw/1H7159+/7r7ZcvPz4fOHbzEwMDwx8GBgaGnNatfHZx8zqrJ+4VJBh5CQEGOySEua/v3n",
     "7hXmqI8WUGBgYGL3vVG7fuPK3i5GD9/fja7ZsMDAzMG/Ze52mZeSj4yu1XEq/ff7W5dvfVAS1",
     "lsXc4Db7z8C3r8p7Qjf/\x2f/2dnZGxlqJuyr3rPqQd/Hhyu7oSpYWScylDQsd3kzvnH738wMDzj",
     "5GBN1VIWW4c3KDon7VOvm7S3paB9u5qsU5/x5KUnlY+eexQbkLNsErK61+++VnAJcfkyMTIwf",
     "fj0QwZbJDKjcETs1Y8evyd48toz8y/ffzv/\x2fvPP4veffxpX77z6l5JewHPu8MqTDAwMDLzyrj",
     "b/mZm0JcT5Lj+89+Ybm6zz95oMh7s4XbygN3Sluq4Mj5K8iKMgP4f0/\x2f/\x2ffv77/\x2f8nLy+7MCc",
     "XmyYDAwODS9jM9tcvPypd35pne3ljdjvj26+H2dhYpuENikgfvQeXNmSl3tqepxXsqhXPyc66",
     "6s+fv1fMdKR3TK72zpix8nTc7bdfhfkEeVbC9KhbK/9iYWHiErbu6MWbY/7/\x2f8/4/\x2f9/pgOnH",
     "6jGVazvFDRtq2VgiBIZrUTIBgCk+ivHvuEKwAAAAABJRU5ErkJggg=="]
  )(
    "Bold",
    "bold",
    ["data:image/gif;base64,R0lGODlhFgAWAID/AMDAwAAAACH5BAEAAAAALAAAAAAWAB",
     "YAQAInhI+pa+H9mJy0LhdgtrxzDG5WGFVk6aXqyk6Y9kXvKKNuLbb6zgMFADs="]
  )(
    "Italic",
    "italic",
    ["data:image/gif;base64,R0lGODlhFgAWAKEDAAAAAF9vj5WIbf/\x2f/yH5BAEAAAMALA",
     "AAAAAWABYAAAIjnI+py+0Po5x0gXvruEKHrF2BB1YiCWgbMFIYpsbyTNd2UwAAOw=="]
  )(
    "Underline",
    "underline",
    ["data:image/gif;base64,R0lGODlhFgAWAKECAAAAAF9vj/\x2f/\x2f/\x2f/\x2fyH5BAEAAAIALA",
     "AAAAAWABYAAAIrlI+py+0Po5zUgAsEzvEeL4Ea15EiJJ5PSqJmuwKBEKgxVuXWtun+DwxCCgA",
     "7"]
  )(
    "Left align",
    "justifyleft",
    ["data:image/gif;base64,R0lGODlhFgAWAID/AMDAwAAAACH5BAEAAAAALAAAAAAWAB",
     "YAQAIghI+py+0Po5y02ouz3jL4D4JMGELkGYxo+qzl4nKyXAAAOw=="]
  )(
    "Center align",
    "justifycenter",
    ["data:image/gif;base64,R0lGODlhFgAWAID/AMDAwAAAACH5BAEAAAAALAAAAAAWAB",
     "YAQAIfhI+py+0Po5y02ouz3jL4D4JOGI7kaZ5Bqn4sycVbAQA7"]
  )(
    "Right align",
    "justifyright",
    ["data:image/gif;base64,R0lGODlhFgAWAID/AMDAwAAAACH5BAEAAAAALAAAAAAWAB",
     "YAQAIghI+py+0Po5y02ouz3jL4D4JQGDLkGYxouqzl43JyVgAAOw=="]
  )(
    "Numbered list",
    "insertorderedlist",
    ["data:image/gif;base64,R0lGODlhFgAWAMIGAAAAADljwliE35GjuaezxtHa7P/\x2f/\x2f",
     "/\x2f/yH5BAEAAAcALAAAAAAWABYAAAM2eLrc/jDKSespwjoRFvggCBUBoTFBeq6QIAysQnRHaEO",
     "zyaZ07Lu9lUBnC0UGQU1K52s6n5oEADs="]
  )(
    "Dotted list",
    "insertunorderedlist",
    ["data:image/gif;base64,R0lGODlhFgAWAMIGAAAAAB1ChF9vj1iE33mOrqezxv/\x2f/\x2f",
     "/\x2f/yH5BAEAAAcALAAAAAAWABYAAAMyeLrc/jDKSesppNhGRlBAKIZRERBbqm6YtnbfMY7lud6",
     "4UwiuKnigGQliQuWOyKQykgAAOw=="]
  )(
    "Quote",
    "formatblock",
    ["data:image/gif;base64,R0lGODlhFgAWAIQXAC1NqjFRjkBgmT9nqUJnsk9xrFJ7u2",
     "R9qmKBt1iGzHmOrm6Sz4OXw3Odz4Cl2ZSnw6KxyqO306K63bG70bTB0rDI3bvI4P",
     "/\x2f/\x2f/\x2f/\x2f/",
     "/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "/\x2f/\x2f/\x2fyH5BAEKAB8ALAAAAAAWABYAAAVP4CeOZGmeaKqubEs2Cekk",
     "ErvEI1zZuOgYFlakECEZFi0GgTGKEBATFmJAVXweVOoKEQgABB9IQDCmrLpjETrQQlhHjINrT",
     "q/b7/i8fp8PAQA7"]
  )(
    "Delete indentation",
    "outdent",
    ["data:image/gif;base64,R0lGODlhFgAWAMIHAAAAADljwliE35GjuaezxtDV3NHa7P",
     "/\x2f/yH5BAEAAAcALAAAAAAWABYAAAM2eLrc/jDKCQG9F2i7u8agQgyK1z2EIBil+TWqEMxhMcz",
     "sYVJ3e4ahk+sFnAgtxSQDqWw6n5cEADs="]
  )(
    "Add indentation",
    "indent",
    ["data:image/gif;base64,R0lGODlhFgAWAOMIAAAAADljwl9vj1iE35GjuaezxtDV3N",
     "Ha7P/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "/\x2f/\x2f/yH5BAEAAAgALAAAAAAWABYAAAQ7EMlJq704650",
     "B/x8gemMpgugwHJNZXodKsO5oqUOgo5KhBwWESyMQsCRDHu9VOyk5TM9zSpFSr9gsJwIAOw=="
    ]
  )(
    "Hyperlink",
    "createlink",
    ["data:image/gif;base64,R0lGODlhFgAWAOMKAB1ChDRLY19vj3mOrpGjuaezxrCztb",
     "/I19Ha7Pv8/f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "/yH5BAEKAA8ALAAAAAAWABYAAARY8MlJq704682",
     "7/2BYIQVhHg9pEgVGIklyDEUBy/RlE4FQF4dCj2AQXAiJQDCWQCAEBwIioEMQBgSAFhDAGghG",
     "i9XgHAhMNoSZgJkJei33UESv2+/4vD4TAQA7"]
  )(
    "Cut",
    "cut",
    ["data:image/gif;base64,R0lGODlhFgAWAIQSAB1ChBFNsRJTySJYwjljwkxwl19vj1",
     "dusYODhl6MnHmOrpqbmpGjuaezxrCztcDCxL/I18rL1P/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/",
     "/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "yH5BAEAAB8ALAAAAAAWABYAAAVu4CeOZGmeaKqubDs6TNnE",
     "bGNApNG0kbGMi5trwcA9GArXh+FAfBAw5UexUDAQESkRsfhJPwaH4YsEGAAJGisRGAQY7UCC9",
     "ZAXBB+74LGCRxIEHwAHdWooDgGJcwpxDisQBQRjIgkDCVlfmZqbmiEAOw=="]
  )(
    "Copy",
    "copy",
    ["data:image/gif;base64,R0lGODlhFgAWAIQcAB1ChBFNsTRLYyJYwjljwl9vj1iE31",
     "iGzF6MnHWX9HOdz5GjuYCl2YKl8ZOt4qezxqK63aK/9KPD+7DI3b/I17LM/MrL1MLY9NHa7OP",
     "s++bx/Pv8/f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "/yH5BAEAAB8ALAAAAAAWABYAAAWG4CeOZGmeaKqubOum1SQ/",
     "kPVOW749BeVSus2CgrCxHptLBbOQxCSNCCaF1GUqwQbBd0JGJAyGJJiobE+LnCaDcXAaEoxhQ",
     "ACgNw0FQx9kP+wmaRgYFBQNeAoGihCAJQsCkJAKOhgXEw8BLQYciooHf5o7EA+kC40qBKkAAA",
     "Grpy+wsbKzIiEAOw=="]
  )(
    /* Paste, when activated via JS, has no effect in some (maybe all)
       environments. Activated externally, e.g. keyboard, it works. */
    "Paste (does not work in all environments)",
    "paste",
    ["data:image/gif;base64,R0lGODlhFgAWAIQUAD04KTRLY2tXQF9vj414WZWIbXmOrp",
     "qbmpGjudClFaezxsa0cb/I1+3YitHa7PrkIPHvbuPs+/fvrvv8/f/\x2f/\x2f/\x2f",
     "/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/",
     "/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f/\x2f",
     "yH5BAEAAB8ALAAAAAAWABYAAAWN4CeOZGmeaKqubGsusPvB",
     "SyFJjVDs6nJLB0khR4AkBCmfsCGBQAoCwjF5gwquVykSFbwZE+AwIBV0GhFog2EwIDchjwRiQ",
     "o9E2Fx4XD5R+B0DDAEnBXBhBhN2DgwDAQFjJYVhCQYRfgoIDGiQJAWTCQMRiwwMfgicnVcAAA",
     "MOaK+bLAOrtLUyt7i5uiUhADs="]
  );

  ////////////////////////////////////////////////////////////////////////
  // The main editor area...
  const oDoc = D.attr(D.div(), 'id', "wysiwygBox");
  D.attr(oDoc, 'contenteditable', 'true');
  D.append(outerContainer, oDoc);
  
  /* Initialize the document editor */
  function initDoc() {
    initEventHandlers();
    if (!isWysiwyg()) { setDocMode(true); }
  }

  function initEventHandlers() {
    //console.debug("initEventHandlers()");
    const handleDropDown = function() {
      formatDoc(this.dataset.format,this[this.selectedIndex].value);
      this.selectedIndex = 0;
    };
    
    const handleFormatButton = function() {
      var extra;
      switch (this.dataset.format) {
      case 'createlink':
        const sLnk = prompt('Target URL:','');
        if(sLnk) extra = sLnk;
        break;
      case 'formatblock':
        extra = 'blockquote';
        break;
      }
      formatDoc(this.dataset.format, extra);
    };

    var i, controls = outerContainer.querySelectorAll('select.format');
    for(i = 0; i < controls.length; i++) {
      controls[i].addEventListener('change', handleDropDown, false);;
    }
    controls = outerContainer.querySelectorAll('.intLink');
    for(i = 0; i < controls.length; i++) {
      controls[i].addEventListener('click', handleFormatButton, false);
    }
  }

  /* Return true if the document editor is in WYSIWYG mode.  Return
  ** false if it is in Markup mode */
  function isWysiwyg() {
    return radio0.checked;
  }

  /* Invoke this routine prior to submitting the HTML content back
  ** to the server */
  /*function wysiwygSubmit() {
    if(oDoc.style.whiteSpace=="pre-wrap"){setDocMode(0);}
    document.getElementById("wysiwygValue").value=oDoc.innerHTML;
  }*/

  /* Run the editing command if in WYSIWYG mode */
  function formatDoc(sCmd, sValue) {
    if (isWysiwyg()){
      try {
        // First, try the W3C draft standard way, which has
        // been working on all non-IE browsers for a while.
        // It is also supported by IE11 and higher.
        document.execCommand("styleWithCSS", false, false);
      } catch (e) {
        try {
          // For IE9 or IE10, this should work.
          document.execCommand("useCSS", 0, true);
        } catch (e) {
          // OK, that apparently did not work, do nothing.
        }
      }
      document.execCommand(sCmd, false, sValue);
      oDoc.focus();
    }
  }

  /* Change the editing mode.  Convert to markup if the argument
  ** is true and wysiwyg if the argument is false. */
  function setDocMode(bToMarkup, content) {
    if(undefined===content){
      content = bToMarkup ? oDoc.innerHTML : oDoc.innerText;
    }
    if(!setDocMode.linebreak){
      setDocMode.linebreak = new RegExp("</p><p>","ig");
    }
    if(!setDocMode.toHide){
      setDocMode.toHide = toolbars.querySelectorAll(
        '#wysiwyg-toolBar1 > *:not(#wysiwygEditMode), '
          +'#wysiwyg-toolBar2');
    }
    if (bToMarkup) {
      /* WYSIWYG -> Markup */
      // Legacy did this: content=content.replace(setDocMode.linebreak,"</p>\n\n<p>")
      D.append(D.clearElement(oDoc), content)
      oDoc.style.whiteSpace = "pre-wrap";
      D.addClass(setDocMode.toHide, 'hidden');
    } else {
      /* Markup -> WYSIWYG */
      D.parseHtml(D.clearElement(oDoc), content);
      oDoc.style.whiteSpace = "normal";
      D.removeClass(setDocMode.toHide, 'hidden');
    }
    oDoc.focus();
  }

  ////////////////////////////////////////////////////////////////////////
  // A hook which can be activated via a site skin to plug this editor
  // in to the wikiedit page.
  F.page.wysiwyg = {
    // only for debugging: oDoc: oDoc,
    /*
      Replaces wikiedit's default editor widget with this wysiwyg
      editor.

      Must either be called via an onPageLoad handler instead via the
      site skin's footer or else it can be called manually from the
      dev tools console. Calling it too early (e.g. in the page
      footer *without* outside of an an onPageLoad handler) will
      crash because wikiedit has not been initialized.
    */
    init: function(){
      initDoc();
      const content = F.page.wikiContent() || '';
      var isDirty = false /* keep from stashing too often */;
      F.page.setContentMethods(
        function(){
          const rc = isWysiwyg() ? oDoc.innerHTML : oDoc.innerText;
          return rc;
        },
        function(content){
          isDirty = false;
          setDocMode(radio0.checked ? 0 : 1, content);
        }
      );
      oDoc.addEventListener('blur', function(){
        if(isDirty) F.page.notifyOfChange();
      }, false);
      oDoc.addEventListener('input', function(){isDirty = true}, false);
      F.page.wikiContent(content)/*feed it back in to our widget*/;
      F.page.replaceEditorElement(outerContainer);
      F.message("Replaced wiki editor widget with legacy wysiwyg editor.");
    }
  };
})(window.fossil);

Changes to src/fossil.page.wikiedit.js.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
...
595
596
597
598
599
600
601
602


603

604


605
606
607
608
609
610
611
...
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
...
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
...
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
...
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
...
900
901
902
903
904
905
906




























907
908
909
910
911
912
913
...
956
957
958
959
960
961
962

963
964
965
966
967
968
969
970
971
972

973
974
975
976
977
978
979
...
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
....
1067
1068
1069
1070
1071
1072
1073
1074




1075

1076

1077
1078
1079
1080
1081
1082
1083
....
1178
1179
1180
1181
1182
1183
1184




















1185
1186
1187
1188
1189


1190
1191
1192
1193
1194
1195
1196
....
1282
1283
1284
1285
1286
1287
1288











1289
1290
1291
1292
1293
1294



1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
....
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
....
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
....
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
(function(F/*the fossil object*/){
  "use strict";
  /**
     Client-side implementation of the /wikiedit app. Requires that
     the fossil JS bootstrapping is complete and that several fossil
     JS APIs have been installed: fossil.fetch, fossil.dom,
     fossil.tabs, fossil.storage, fossil.confirmer.

     Custom events which can be listened for via
     fossil.page.addEventListener():

     - Event 'wiki-page-loaded': passes on information when it
     loads a wiki (whether from the network or its internal local-edit
     cache), in the form of an "winfo" object:
................................................................................
      D.clearElement(parentElem);
      D.append(
        parentElem,
        D.append(D.fieldset("Select a page to edit"),
                 sel)
      );
      D.attr(sel, 'size', 12);
      D.option(D.disable(D.clearElement(sel)), "Loading...");

      /** Set up filter checkboxes for the various types
          of wiki pages... */
      const fsFilter = D.fieldset("Page types"),
            fsFilterBody = D.div(),
            filters = ['normal', 'branch/...', 'tag/...', 'checkin/...']
      ;
      D.append(fsFilter, fsFilterBody);
      D.addClass(fsFilterBody, 'flex-container', 'flex-column', 'stretch');

      // Add filters by page type...
................................................................................
              lbl = D.attr(D.append(D.label(),
                                    getEditMarker(getEditMarker.DELETED,false),
                                    'deleted'),
                           'for', cbId),
              cb = D.attr(D.input('checkbox'), 'id', cbId);
        cb.checked = false;
        D.addClass(parentElem,'hide-deleted');
        D.attr(lbl, 'title',


               'Fossil considers empty pages to be "deleted" in some contexts.');

        D.append(fsFilterBody, D.append(D.span(), cb, lbl));


        cb.addEventListener(
          'change',
          function(ev){
            if(ev.target.checked) D.removeClass(parentElem,'hide-deleted');
            else D.addClass(parentElem,'hide-deleted');
          },
          false);
................................................................................
        /* Needed to handle the saved-an-empty-page case. */
        const page = ev.detail,
              opt = self.cache.optByName[page.name];
        if(opt){
          if(page.isEmpty) opt.dataset.isDeleted = true;
          else delete opt.dataset.isDeleted;
          self._refreshStashMarks(opt);
        }else{
          F.error("BUG: internal mis-handling of page object: missing OPTION for page "+page.name);
        }
      });
      delete this.init;
    }
  };

................................................................................
  P.stashWidget = {
    e:{/*DOM element(s)*/},
    init: function(domInsertPoint/*insert widget BEFORE this element*/){
      const wrapper = D.addClass(
        D.attr(D.div(),'id','wikiedit-stash-selector'),
        'input-with-label'
      );
      const sel = this.e.select = D.select();
      const btnClear = this.e.btnClear = D.button("Discard Edits");








      D.append(wrapper, "Local edits (",
               D.append(D.code(),
                        F.storage.storageImplName()),
               "):",
               sel, btnClear);
      D.attr(wrapper, "title", [
        'Locally-edited wiki pages. Timestamps are the last local edit time.',
        'Only the',P.config.defaultMaxStashSize,'most recent pages',
        'are retained. Saving or reloading a file removes it from this list.'
      ].join(' '));
      D.option(D.disable(sel), "(empty)");
      P.addEventListener('wiki-stash-updated',(e)=>this.updateList(e.detail));
      P.addEventListener('wiki-page-loaded',(e)=>this.updateList($stash, e.detail));
      sel.addEventListener('change',function(e){
        const opt = this.selectedOptions[0];
        if(opt && opt._winfo) P.loadPage(opt._winfo);
      });
      if(F.storage.isTransient()){/*Warn if our storage is particularly transient...*/
................................................................................
      Object.keys(index).forEach((winfo)=>{
        ilist.push(index[winfo]);
      });
      const self = this;
      D.clearElement(this.e.select);
      if(0===ilist.length){
        D.addClass(this.e.btnClear, 'hidden');
        D.option(D.disable(this.e.select),"No local edits");
        return;
      }
      D.enable(this.e.select);
      if(true){
        /* The problem with this Clear button is that it allows the
           user to nuke a non-empty newly-added page without the
           failsafe confirmation we have if they use
           P.e.btnReload. Not yet sure how best to resolve that. */
        D.removeClass(this.e.btnClear, 'hidden');
      }
      D.disable(D.option(this.e.select,0,"Select a local edit..."));
      const currentWinfo = theWinfo || P.winfo || {name:''};
      ilist.sort(f.compare).forEach(function(winfo,n){
        const key = stasher.indexKey(winfo),
              rev = winfo.version || '';
        const opt = D.option(
          self.e.select, n+1/*value is (almost) irrelevant*/,
          [winfo.name,
................................................................................
    document.body.classList.add('wikiedit');
    P.base = {tag: E('base'), wikiUrl: F.repoUrl('wiki')};
    P.base.originalHref = P.base.tag.href;
    P.e = { /* various DOM elements we work with... */
      taEditor: E('#wikiedit-content-editor'),
      btnReload: E("#wikiedit-tab-content button.wikiedit-content-reload"),
      btnSave: E("button.wikiedit-save"),
      btnSaveClose: D.attr(E("button.wikiedit-save-close"),
                           'title',
                           'Save changes and return to the wiki reader.'),
      selectMimetype: E('select[name=mimetype]'),
      selectFontSizeWrap: E('#select-font-size'),
//      selectDiffWS:  E('select[name=diff_ws]'),
      cbAutoPreview: E('#cb-preview-autoupdate > input[type=checkbox]'),
      previewTarget: E('#wikiedit-tab-preview-wrapper'),
      diffTarget: E('#wikiedit-tab-diff-wrapper'),
      editStatus: E('#wikiedit-edit-status'),
      tabContainer: E('#wikiedit-tabs'),
      tabs:{
        pageList: E('#wikiedit-tab-pages'),
        content: E('#wikiedit-tab-content'),
        preview: E('#wikiedit-tab-preview'),
        diff: E('#wikiedit-tab-diff'),
        misc: E('#wikiedit-tab-misc')
        //commit: E('#wikiedit-tab-commit')
      }
    };
    P.tabs = new fossil.TabManager(D.clearElement(P.e.tabContainer));
    P.tabs.e.container.insertBefore(
      /* Move the status bar between the tab buttons and
         tab panels. Seems to be the best fit in terms of
         functionality and visibility. */
      E('#fossil-status-bar'), P.tabs.e.tabs
    );
    P.tabs.e.container.insertBefore(P.e.editStatus, P.tabs.e.tabs);

    P.tabs.addEventListener(
      /* Set up some before-switch-to tab event tasks... */
      'before-switch-to', function(ev){
        const theTab = ev.detail, btnSlot = theTab.querySelector('.save-button-slot');
        if(btnSlot){
          /* Several places make sense for a save button, so we'll
             move that button around to those tabs where it makes sense. */
          btnSlot.parentNode.insertBefore( P.e.btnSave, btnSlot );
          btnSlot.parentNode.insertBefore( P.e.btnSaveClose, btnSlot );
          P.updateSaveButton();
        }
        if(theTab===P.e.tabs.preview){
          P.baseHrefForWiki();
          if(P.previewNeedsUpdate && P.e.cbAutoPreview.checked) P.preview();
        }else if(theTab===P.e.tabs.diff){
          /* Work around a weird bug where the page gets wider than
................................................................................
          P.baseHrefRestore();
        }else if(theTab===P.e.tabs.diff){
          /* See notes in the before-switch-to handler. */
          D.addClass(P.e.diffTarget, 'hidden');
        }
      }
    );





























    F.connectPagePreviewers(
      P.e.tabs.preview.querySelector(
        '#btn-preview-refresh'
      )
    );

................................................................................
        delete P.winfo;
        P.updatePageTitle();
        F.message("Discarded new page ["+w.name+"].");
      }
    };

    if(P.config.useConfirmerButtons.reload){

      F.confirmer(P.e.btnReload, {
        pinSize: true,
        confirmText: "Really reload, losing edits?",
        onconfirm: doReload,
        ticks: F.config.confirmerButtonTicks
      });
    }else{
      P.e.btnReload.addEventListener('click', doReload, false);
    }
    if(P.config.useConfirmerButtons.save){

      F.confirmer(P.e.btnSave, {
        pinSize: true,
        confirmText: "Really save changes?",
        onconfirm: ()=>doSave(),
        ticks: F.config.confirmerButtonTicks
      });
      F.confirmer(P.e.btnSaveClose, {
................................................................................
        ticks: F.config.confirmerButtonTicks
      });
    }else{
      P.e.btnSave.addEventListener('click', ()=>doSave(), false);
      P.e.btnSaveClose.addEventListener('click', ()=>doSave(true), false);
    }

    P.e.taEditor.addEventListener(
      'change', function(){
        P._isDirty = true;
        P.stashContentChange();
      }, false
    );
    
    P.selectMimetype(false, true);
    P.e.selectMimetype.addEventListener(
      'change',
      function(e){
        if(P.winfo && P.winfo.mimetype !== e.target.value){
          P.winfo.mimetype = e.target.value;
................................................................................
        if(!winfo.version && winfo.type!=='sandbox'){
          F.message('You are editing a new, unsaved page:',winfo.name);
        }
        P.updatePageTitle().updateSaveButton(/* b/c save() routes through here */);
      },
      false
    );
    /* These init()s need to come after P's event handlers are registered */




    WikiList.init( P.e.tabs.pageList.firstElementChild );

    P.stashWidget.init(P.e.tabs.content.lastElementChild);

    //P.$wikiList = WikiList/*only for testing/debugging*/;
  }/*F.onPageLoad()*/);

  /**
     Returns true if fossil.page.winfo is set, indicating that a page
     has been loaded, else it reports an error and returns false.

................................................................................
     P.wikiContent(). Returns this object.
  */
  P.setContentMethods = function(getter, setter){
    this.wikiContent.get = getter;
    this.wikiContent.set = setter;
    return this;
  };





















  /**
     Removes the default editor widget (and any dependent elements)
     from the DOM, adds the given element in its place, removes this
     method from this object, and returns this object.


  */
  P.replaceEditorElement = function(newEditor){
    P.e.taEditor.parentNode.insertBefore(newEditor, P.e.taEditor);
    P.e.taEditor.remove();
    P.e.selectFontSizeWrap.remove();
    delete this.replaceEditorElement;
    return P;
................................................................................
     this page's input fields, and updates the UI with with the
     preview.

     Returns this object, noting that the operation is async.
  */
  P.preview = function f(switchToTab){
    if(!affirmPageLoaded()) return this;











    const target = this.e.previewTarget,
          self = this;
    const updateView = function(c){
      D.clearElement(target);
      if('string'===typeof c) target.innerHTML = c;
      if(switchToTab) self.tabs.switchToTab(self.e.tabs.preview);



    };
    return this._postPreview(this.wikiContent(), updateView);
  };

  /**
     Callback for use with F.connectPagePreviewers()
  */
  P._postPreview = function(content,callback){
    if(!affirmPageLoaded()) return this;
    if(!content){
      callback(content);
................................................................................
        P.previewNeedsUpdate = false;
        P.dispatchEvent('wiki-preview-updated',{
          mimetype: mimetype,
          element: P.e.previewTarget
        });
      },
      onerror: (e)=>{
        fossil.fetch.onerror(e);
        callback("Error fetching preview: "+e);
      }
    });
    return this;
  };

  /**
................................................................................
    fd.append('content',content);
    if(this.e.selectDiffWS) fd.append('ws',this.e.selectDiffWS.value);
    F.message(
      "Fetching diff..."
    ).fetch('wikiajax/diff',{
      payload: fd,
      onload: function(c){
        target.innerHTML = [
          "<div>Diff <code>[",
          self.winfo.name,
          "]</code> &rarr; Local Edits</div>",
          c||'No changes.'
        ].join('');
        if(sbs) P.tweakSbsDiffs2();
        F.message('Updated diff.');
        self.tabs.switchToTab(self.e.tabs.diff);
      }
    });
    return this;
  };
................................................................................
      const wi = this.winfo;
      wi.mimetype = P.e.selectMimetype.value;
      if(onlyWinfo && $stash.hasStashedContent(wi)){
        $stash.updateWinfo(wi);
      }else{
        $stash.updateWinfo(wi, P.wikiContent());
      }
      F.message("Stashed change(s) to page ["+wi.name+"].");
      P.updatePageTitle();
      $stash.prune();
      this.previewNeedsUpdate = true;
    }
    return this;
  };







|







 







|



|







 







|
>
>
|
>
|
>
>







 







|







 







|
|
>
>
>
>
>
>
>
>




|
|
<
<
<
<
|







 







|










|







 







|
<
<



|













|
<
|
|
|
|
<
<
>



|



|
|







 







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







 







>










>







 







|
<
<
<
<
<







 







|
>
>
>
>

>

>







 







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




|
>
>







 







>
>
>
>
>
>
>
>
>
>
>
|
<
<
|
|
<
>
>
>
|
<
<
|







 







|







 







|




|







 







|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
...
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
...
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
...
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
...
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
...
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
...
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
...
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
....
1018
1019
1020
1021
1022
1023
1024
1025





1026
1027
1028
1029
1030
1031
1032
....
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
....
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
....
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
....
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
....
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
....
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
(function(F/*the fossil object*/){
  "use strict";
  /**
     Client-side implementation of the /wikiedit app. Requires that
     the fossil JS bootstrapping is complete and that several fossil
     JS APIs have been installed: fossil.fetch, fossil.dom,
     fossil.tabs, fossil.storage, fossil.confirmer, fossil.popupwidget.

     Custom events which can be listened for via
     fossil.page.addEventListener():

     - Event 'wiki-page-loaded': passes on information when it
     loads a wiki (whether from the network or its internal local-edit
     cache), in the form of an "winfo" object:
................................................................................
      D.clearElement(parentElem);
      D.append(
        parentElem,
        D.append(D.fieldset("Select a page to edit"),
                 sel)
      );
      D.attr(sel, 'size', 12);
      D.option(D.disable(D.clearElement(sel)), undefined, "Loading...");

      /** Set up filter checkboxes for the various types
          of wiki pages... */
      const fsFilter = D.addClass(D.fieldset("Page types"),"page-types-list"),
            fsFilterBody = D.div(),
            filters = ['normal', 'branch/...', 'tag/...', 'checkin/...']
      ;
      D.append(fsFilter, fsFilterBody);
      D.addClass(fsFilterBody, 'flex-container', 'flex-column', 'stretch');

      // Add filters by page type...
................................................................................
              lbl = D.attr(D.append(D.label(),
                                    getEditMarker(getEditMarker.DELETED,false),
                                    'deleted'),
                           'for', cbId),
              cb = D.attr(D.input('checkbox'), 'id', cbId);
        cb.checked = false;
        D.addClass(parentElem,'hide-deleted');
        D.attr(lbl);
        const deletedTip = F.helpButtonlets.create(
          D.span(),
          'Fossil considers empty pages to be "deleted" in some contexts.'
        );
        D.append(fsFilterBody, D.append(
          D.span(), cb, lbl, deletedTip
        ));
        cb.addEventListener(
          'change',
          function(ev){
            if(ev.target.checked) D.removeClass(parentElem,'hide-deleted');
            else D.addClass(parentElem,'hide-deleted');
          },
          false);
................................................................................
        /* Needed to handle the saved-an-empty-page case. */
        const page = ev.detail,
              opt = self.cache.optByName[page.name];
        if(opt){
          if(page.isEmpty) opt.dataset.isDeleted = true;
          else delete opt.dataset.isDeleted;
          self._refreshStashMarks(opt);
        }else if('sandbox'!==page.type){
          F.error("BUG: internal mis-handling of page object: missing OPTION for page "+page.name);
        }
      });
      delete this.init;
    }
  };

................................................................................
  P.stashWidget = {
    e:{/*DOM element(s)*/},
    init: function(domInsertPoint/*insert widget BEFORE this element*/){
      const wrapper = D.addClass(
        D.attr(D.div(),'id','wikiedit-stash-selector'),
        'input-with-label'
      );
      const sel = this.e.select = D.select(),
            btnClear = this.e.btnClear = D.button("Discard Edits"),
            btnHelp = D.append(
              D.addClass(D.div(), "help-buttonlet"),
              'Locally-edited wiki pages. Timestamps are the last local edit time. ',
              'Only the ',P.config.defaultMaxStashSize,' most recent pages ',
              'are retained. Saving or reloading a file removes it from this list. ',
              D.append(D.code(),F.storage.storageImplName()),
              ' = ',F.storage.storageHelpDescription()
            );
      D.append(wrapper, "Local edits (",
               D.append(D.code(),
                        F.storage.storageImplName()),
               "):",
               btnHelp, sel, btnClear);
      F.helpButtonlets.setup(btnHelp);




      D.option(D.disable(sel), undefined, "(empty)");
      P.addEventListener('wiki-stash-updated',(e)=>this.updateList(e.detail));
      P.addEventListener('wiki-page-loaded',(e)=>this.updateList($stash, e.detail));
      sel.addEventListener('change',function(e){
        const opt = this.selectedOptions[0];
        if(opt && opt._winfo) P.loadPage(opt._winfo);
      });
      if(F.storage.isTransient()){/*Warn if our storage is particularly transient...*/
................................................................................
      Object.keys(index).forEach((winfo)=>{
        ilist.push(index[winfo]);
      });
      const self = this;
      D.clearElement(this.e.select);
      if(0===ilist.length){
        D.addClass(this.e.btnClear, 'hidden');
        D.option(D.disable(this.e.select),undefined,"No local edits");
        return;
      }
      D.enable(this.e.select);
      if(true){
        /* The problem with this Clear button is that it allows the
           user to nuke a non-empty newly-added page without the
           failsafe confirmation we have if they use
           P.e.btnReload. Not yet sure how best to resolve that. */
        D.removeClass(this.e.btnClear, 'hidden');
      }
      D.disable(D.option(this.e.select,undefined,"Select a local edit..."));
      const currentWinfo = theWinfo || P.winfo || {name:''};
      ilist.sort(f.compare).forEach(function(winfo,n){
        const key = stasher.indexKey(winfo),
              rev = winfo.version || '';
        const opt = D.option(
          self.e.select, n+1/*value is (almost) irrelevant*/,
          [winfo.name,
................................................................................
    document.body.classList.add('wikiedit');
    P.base = {tag: E('base'), wikiUrl: F.repoUrl('wiki')};
    P.base.originalHref = P.base.tag.href;
    P.e = { /* various DOM elements we work with... */
      taEditor: E('#wikiedit-content-editor'),
      btnReload: E("#wikiedit-tab-content button.wikiedit-content-reload"),
      btnSave: E("button.wikiedit-save"),
      btnSaveClose: E("button.wikiedit-save-close"),


      selectMimetype: E('select[name=mimetype]'),
      selectFontSizeWrap: E('#select-font-size'),
//      selectDiffWS:  E('select[name=diff_ws]'),
      cbAutoPreview: E('#cb-preview-autorefresh'),
      previewTarget: E('#wikiedit-tab-preview-wrapper'),
      diffTarget: E('#wikiedit-tab-diff-wrapper'),
      editStatus: E('#wikiedit-edit-status'),
      tabContainer: E('#wikiedit-tabs'),
      tabs:{
        pageList: E('#wikiedit-tab-pages'),
        content: E('#wikiedit-tab-content'),
        preview: E('#wikiedit-tab-preview'),
        diff: E('#wikiedit-tab-diff'),
        misc: E('#wikiedit-tab-misc')
        //commit: E('#wikiedit-tab-commit')
      }
    };
    P.tabs = new F.TabManager(D.clearElement(P.e.tabContainer));

    /* Move the status bar between the tab buttons and
       tab panels. Seems to be the best fit in terms of
       functionality and visibility. */
    P.tabs.addCustomWidget( E('#fossil-status-bar') ).addCustomWidget(P.e.editStatus);


    let currentTab/*used for ctrl-enter switch between editor and preview*/;
    P.tabs.addEventListener(
      /* Set up some before-switch-to tab event tasks... */
      'before-switch-to', function(ev){
        const theTab = currentTab = ev.detail, btnSlot = theTab.querySelector('.save-button-slot');
        if(btnSlot){
          /* Several places make sense for a save button, so we'll
             move that button around to those tabs where it makes sense. */
          btnSlot.parentNode.insertBefore( P.e.btnSave.parentNode, btnSlot );
          btnSlot.parentNode.insertBefore( P.e.btnSaveClose.parentNode, btnSlot );
          P.updateSaveButton();
        }
        if(theTab===P.e.tabs.preview){
          P.baseHrefForWiki();
          if(P.previewNeedsUpdate && P.e.cbAutoPreview.checked) P.preview();
        }else if(theTab===P.e.tabs.diff){
          /* Work around a weird bug where the page gets wider than
................................................................................
          P.baseHrefRestore();
        }else if(theTab===P.e.tabs.diff){
          /* See notes in the before-switch-to handler. */
          D.addClass(P.e.diffTarget, 'hidden');
        }
      }
    );
    ////////////////////////////////////////////////////////////
    // Trigger preview on Ctrl-Enter. This only works on the built-in
    // editor widget, not a client-provided one.
    P.e.taEditor.addEventListener('keydown',function(ev){
      if(ev.ctrlKey && 13 === ev.keyCode){
        ev.preventDefault();
        ev.stopPropagation();
        P.e.taEditor.blur(/*force change event, if needed*/);
        P.tabs.switchToTab(P.e.tabs.preview);
        if(!P.e.cbAutoPreview.checked){/* If NOT in auto-preview mode, trigger an update. */
          P.preview();
        }
      }
    }, false);
    // If we're in the preview tab, have ctrl-enter switch back to the editor.
    document.body.addEventListener('keydown',function(ev){
      if(ev.ctrlKey && 13 === ev.keyCode){
        if(currentTab === P.e.tabs.preview){
          //ev.preventDefault();
          //ev.stopPropagation();
          P.tabs.switchToTab(P.e.tabs.content);
          P.e.taEditor.focus(/*doesn't work for client-supplied editor widget!
                              And it's slow as molasses for long docs, as focus()
                              forces a document reflow. */);
          //console.debug("BODY ctrl-enter");
        }
      }
    }, true);

    F.connectPagePreviewers(
      P.e.tabs.preview.querySelector(
        '#btn-preview-refresh'
      )
    );

................................................................................
        delete P.winfo;
        P.updatePageTitle();
        F.message("Discarded new page ["+w.name+"].");
      }
    };

    if(P.config.useConfirmerButtons.reload){
      P.tabs.switchToTab(1/*DOM visibility workaround*/);
      F.confirmer(P.e.btnReload, {
        pinSize: true,
        confirmText: "Really reload, losing edits?",
        onconfirm: doReload,
        ticks: F.config.confirmerButtonTicks
      });
    }else{
      P.e.btnReload.addEventListener('click', doReload, false);
    }
    if(P.config.useConfirmerButtons.save){
      P.tabs.switchToTab(1/*DOM visibility workaround*/);
      F.confirmer(P.e.btnSave, {
        pinSize: true,
        confirmText: "Really save changes?",
        onconfirm: ()=>doSave(),
        ticks: F.config.confirmerButtonTicks
      });
      F.confirmer(P.e.btnSaveClose, {
................................................................................
        ticks: F.config.confirmerButtonTicks
      });
    }else{
      P.e.btnSave.addEventListener('click', ()=>doSave(), false);
      P.e.btnSaveClose.addEventListener('click', ()=>doSave(true), false);
    }

    P.e.taEditor.addEventListener('change', ()=>P.notifyOfChange(), false);





    
    P.selectMimetype(false, true);
    P.e.selectMimetype.addEventListener(
      'change',
      function(e){
        if(P.winfo && P.winfo.mimetype !== e.target.value){
          P.winfo.mimetype = e.target.value;
................................................................................
        if(!winfo.version && winfo.type!=='sandbox'){
          F.message('You are editing a new, unsaved page:',winfo.name);
        }
        P.updatePageTitle().updateSaveButton(/* b/c save() routes through here */);
      },
      false
    );
    /* These init()s need to come after P's event handlers are registered.
       The tab-switching is a workaround for the pinSize option of the confirmer widgets:
       it does not work if the confirmer button being initialized is in a hidden
       part of the DOM :/. */
    P.tabs.switchToTab(0);
    WikiList.init( P.e.tabs.pageList.firstElementChild );
    P.tabs.switchToTab(1);
    P.stashWidget.init(P.e.tabs.content.lastElementChild);
    P.tabs.switchToTab(0);
    //P.$wikiList = WikiList/*only for testing/debugging*/;
  }/*F.onPageLoad()*/);

  /**
     Returns true if fossil.page.winfo is set, indicating that a page
     has been loaded, else it reports an error and returns false.

................................................................................
     P.wikiContent(). Returns this object.
  */
  P.setContentMethods = function(getter, setter){
    this.wikiContent.get = getter;
    this.wikiContent.set = setter;
    return this;
  };

  /**
     Alerts the editor app that a "change" has happened in the editor.
     When connecting 3rd-party editor widgets to this app, it is
     necessary to call this for any "change" events the widget emits.
     Whether or not "change" means that there were "really" edits is
     irrelevant, but this app will not allow saving unless it believes
     at least one "change" has been made (by being signaled through
     this method).

     This function may perform an arbitrary amount of work, so it
     should not be called for every keypress within the editor
     widget. Calling it for "blur" events is generally sufficient, and
     calling it for each Enter keypress is generally reasonable but
     also computationally costly.
  */
  P.notifyOfChange = function(){
    P._isDirty = true;
    P.stashContentChange();
  };

  /**
     Removes the default editor widget (and any dependent elements)
     from the DOM, adds the given element in its place, removes this
     method from this object, and returns this object. This is not
     needed if the 3rd-party widget replaces or hides this app's
     editor widget (e.g. TinyMCE).
  */
  P.replaceEditorElement = function(newEditor){
    P.e.taEditor.parentNode.insertBefore(newEditor, P.e.taEditor);
    P.e.taEditor.remove();
    P.e.selectFontSizeWrap.remove();
    delete this.replaceEditorElement;
    return P;
................................................................................
     this page's input fields, and updates the UI with with the
     preview.

     Returns this object, noting that the operation is async.
  */
  P.preview = function f(switchToTab){
    if(!affirmPageLoaded()) return this;
    return this._postPreview(this.wikiContent(), function(c){
      P._previewTo(c);
      if(switchToTab) self.tabs.switchToTab(self.e.tabs.preview);
    });
  };

  /**
     Callback for use with F.connectPagePreviewers(). Gets passed
     the preview content.
  */
  P._previewTo = function(c){
    const target = this.e.previewTarget;


    D.clearElement(target);
    if('string'===typeof c) D.parseHtml(target,c);

    if(F.pikchr){
      F.pikchr.addSrcView(target.querySelectorAll('svg.pikchr'));
    }
  };


  
  /**
     Callback for use with F.connectPagePreviewers()
  */
  P._postPreview = function(content,callback){
    if(!affirmPageLoaded()) return this;
    if(!content){
      callback(content);
................................................................................
        P.previewNeedsUpdate = false;
        P.dispatchEvent('wiki-preview-updated',{
          mimetype: mimetype,
          element: P.e.previewTarget
        });
      },
      onerror: (e)=>{
        F.fetch.onerror(e);
        callback("Error fetching preview: "+e);
      }
    });
    return this;
  };

  /**
................................................................................
    fd.append('content',content);
    if(this.e.selectDiffWS) fd.append('ws',this.e.selectDiffWS.value);
    F.message(
      "Fetching diff..."
    ).fetch('wikiajax/diff',{
      payload: fd,
      onload: function(c){
        D.parseHtml(D.clearElement(target), [
          "<div>Diff <code>[",
          self.winfo.name,
          "]</code> &rarr; Local Edits</div>",
          c||'No changes.'
        ].join(''));
        if(sbs) P.tweakSbsDiffs2();
        F.message('Updated diff.');
        self.tabs.switchToTab(self.e.tabs.diff);
      }
    });
    return this;
  };
................................................................................
      const wi = this.winfo;
      wi.mimetype = P.e.selectMimetype.value;
      if(onlyWinfo && $stash.hasStashedContent(wi)){
        $stash.updateWinfo(wi);
      }else{
        $stash.updateWinfo(wi, P.wikiContent());
      }
      F.message("Stashed changes to page ["+wi.name+"].");
      P.updatePageTitle();
      $stash.prune();
      this.previewNeedsUpdate = true;
    }
    return this;
  };

Added src/fossil.pikchr.js.









































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function(F/*window.fossil object*/){
  "use strict";
  const D = F.dom, P = F.pikchr = {};

  /**
     Initializes pikchr-rendered elements with the ability to
     toggle between their SVG and source code.

     The first argument may be any of:

     - A single SVG.pikchr element.

     - A collection (with a forEach method) of such elements.

     - A CSS selector string for one or more such elements.

     - An array of such strings.

     Passing no value is equivalent to passing 'svg.pikchr'.

     For each SVG in the resulting set, this function sets up event
     handlers which allow the user to toggle the SVG between image and
     source code modes. The image will switch modes in response to
     cltr-click and, if its *parent* element has the "toggle" CSS
     class, it will also switch modes in response to single-click.

     If the parent element has the "source" CSS class, the image
     starts off with its source code visible and the image hidden,
     instead of the default of the other way around.

     Returns this object.

     Each element will only be processed once by this routine, even if
     it is passed to this function multiple times. Each processed
     element gets a "data" attribute set to it to indicate that it was
     already dealt with.

     This code expects the following structure around the SVGs, and
     will not process any which don't match this:

     <DIV.pikchr-wrapper>
       <DIV.pikchr-svg><SVG.pikchr></SVG></DIV>
       <PRE.pikchr-src></PRE>
     </DIV>
  */
  P.addSrcView = function f(svg){
    if(!f.hasOwnProperty('parentClick')){
      f.parentClick = function(ev){
        if(ev.altKey || ev.metaKey || ev.ctrlKey
           /* Every combination of special key (alt, shift, ctrl,
              meta) is handled differently everywhere. Shift is used
              by the browser, Ctrl doesn't work on an iMac, and Alt is
              intercepted by most Linux window managers to control
              window movement! So...  we just listen for *any* of them
              (except Shift) and the user will need to find one which
              works on on their environment. */
           || this.classList.contains('toggle')){
          this.classList.toggle('source');
          ev.stopPropagation();
          ev.preventDefault();
        }
      };
    };
    if(!svg) svg = 'svg.pikchr';
    if('string' === typeof svg){
      document.querySelectorAll(svg).forEach((e)=>f.call(this, e));
      return this;
    }else if(svg.forEach){
      svg.forEach((e)=>f.call(this, e));
      return this;
    }
    if(svg.dataset.pikchrProcessed){
      return this;
    }
    svg.dataset.pikchrProcessed = 1;
    const parent = svg.parentNode.parentNode /* outermost div.pikchr-wrapper */;
    const srcView = parent ? svg.parentNode.nextElementSibling : undefined;
    if(!srcView || !srcView.classList.contains('pikchr-src')){
      /* Without this element, there's nothing for us to do here. */
      return this;
    }
    parent.addEventListener('click', f.parentClick, false);
  };
})(window.fossil);

Added src/fossil.popupwidget.js.





















































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
(function(F/*fossil object*/){
  /**
     A very basic tooltip-like widget. It's intended to be popped up
     to display basic information or basic user interaction
     components, e.g. a copy-to-clipboard button.

     Requires: fossil.bootstrap, fossil.dom
  */
  const D = F.dom;

  /**
     Creates a new tooltip-like widget using the given options object.

     Options:

     .refresh: callback which is called just before the tooltip is
     revealed or moved. It must refresh the contents of the tooltip,
     if needed, by applying the content to/within this.e, which is the
     base DOM element for the tooltip (and is a child of
     document.body). If the contents are static and set up via the
     .init option then this callback is not needed.

     .adjustX: an optional callback which is called when the tooltip
     is to be displayed at a given position and passed the X
     viewport-relative coordinate. This routine must either return its
     argument as-is or return an adjusted value. The intent is to
     allow a given tooltip may be positioned more appropriately for a
     given context, if needed (noting that the desired position can,
     and probably should, be passed to the show() method
     instead). This class's API assumes that clients give it
     viewport-relative coordinates, and it will take care to translate
     those to page-relative, so this callback should not do so.

     .adjustY: the Y counterpart of adjustX.

     .init: optional callback called one time to initialize the state
     of the tooltip. This is called after the this.e has been created
     and added (initially hidden) to the DOM. If this is called, it is
     removed from the object immediately after it is called.

     All callback options are called with the PopupWidget object as
     their "this".


     .cssClass: optional CSS class, or list of classes, to apply to
     the new element.

     .style: optional object of properties to copy directly into
     the element's style object.     

     The options passed to this constructor get normalized into a
     separate object which includes any default values for options not
     provided by the caller. That object is available this the
     resulting PopupWidget's options property. Default values for any
     options not provided by the caller are pulled from
     PopupWidget.defaultOptions, and modifying those affects all
     future calls to this method but has no effect on existing
     instances.


     Example:

     const tip = new fossil.PopupWidget({
       init: function(){
         // optionally populate DOM element this.e with the widget's
         // content.
       },
       refresh: function(){
         // (re)populate/refresh the contents of the main
         // wrapper element, this.e.
       }
     });

     tip.show(50, 100);
     // ^^^ viewport-relative coordinates. See show() for other options.

  */
  F.PopupWidget = function f(opt){
    opt = F.mergeLastWins(f.defaultOptions,opt);
    this.options = opt;
    const e = this.e = D.addClass(D.div(), opt.cssClass);
    this.show(false);
    if(opt.style){
      let k;
      for(k in opt.style){
        if(opt.style.hasOwnProperty(k)) e.style[k] = opt.style[k];
      }
    }
    D.append(document.body, e/*must be in the DOM for size calc. to work*/);
    D.copyStyle(e, opt.style);
    if(opt.init){
      opt.init.call(this);
      delete opt.init;
    }
  };

  /**
     Default options for the PopupWidget constructor. These values are
     used for any options not provided by the caller. Any changes made
     to this instace affect future calls to PopupWidget() but have no
     effect on existing instances.
  */
  F.PopupWidget.defaultOptions = {
    cssClass: 'fossil-tooltip',
    style: undefined /*{optional properties copied as-is into element.style}*/,
    adjustX: (x)=>x,
    adjustY: (y)=>y,
    refresh: function(){},
    init: undefined /* optional initialization function */
  };

  F.PopupWidget.prototype = {

    /** Returns true if the widget is currently being shown, else false. */
    isShown: function(){return !this.e.classList.contains('hidden')},

    /** Calls the refresh() method of the options object and returns
        this object. */
    refresh: function(){
      if(this.options.refresh){
        this.options.refresh.call(this);
      }
      return this;
    },

    /**
       Shows or hides the tooltip.

       Usages:

       (bool showIt) => hide it or reveal it at its last position.

       (x, y) => reveal/move it at/to the given
       relative-to-the-viewport position, which will be adjusted to make
       it page-relative.

       (DOM element) => reveal/move it at/to a position based on the
       the given element (adjusted slightly).

       For the latter two, this.options.adjustX() and adjustY() will
       be called to adjust it further.

       Returns this object.

       Sidebar: showing/hiding the widget is, as is conventional for
       this framework, done by removing/adding the 'hidden' CSS class
       to it, so that class must be defined appropriately.
    */
    show: function(){
      var x = undefined, y = undefined, showIt;
      if(2===arguments.length){
        x = arguments[0];
        y = arguments[1];
        showIt = true;
      }else if(1===arguments.length){
        if(arguments[0] instanceof HTMLElement){
          const p = arguments[0];
          const r = p.getBoundingClientRect();
          x = r.x + r.x/5;
          y = r.y - r.height/2;
          showIt = true;
        }else{
          showIt = !!arguments[0];
        }
      }
      if(showIt){
        this.refresh();
        x = this.options.adjustX.call(this,x);
        y = this.options.adjustY.call(this,y);
        x += window.pageXOffset;
        y += window.pageYOffset;
      }
      if(showIt){
        if('number'===typeof x && 'number'===typeof y){
          this.e.style.left = x+"px";
          this.e.style.top = y+"px";
        }
        D.removeClass(this.e, 'hidden');
      }else{
        D.addClass(this.e, 'hidden');
        this.e.style.removeProperty('left');
        this.e.style.removeProperty('top');
      }
      return this;
    },

    hide: function(){return this.show(false)}
  }/*F.PopupWidget.prototype*/;

  /**
     Internal impl for F.toast() and friends.

     args:

     1) CSS class to assign to the outer element, along with
     fossil-toast-message. Must be falsy for the non-warning/non-error
     case.

     2) Multiplier of F.toast.config.displayTimeMs. Should be
     1 for default case and progressively higher for warning/error
     cases.

     3) The 'arguments' object from the function which is calling
     this.

     Returns F.toast.
  */
  const toastImpl = function f(cssClass, durationMult, argsObject){
    if(!f.toaster){
      f.toaster = new F.PopupWidget({
        cssClass: 'fossil-toast-message'
      });
    }
    const T = f.toaster;
    if(f._timer) clearTimeout(f._timer);
    D.clearElement(T.e);
    if(f._prevCssClass) T.e.classList.remove(f._prevCssClass);
    if(cssClass) T.e.classList.add(cssClass);
    f._prevCssClass = cssClass;
    D.append(T.e, Array.prototype.slice.call(argsObject,0));
    T.show(F.toast.config.position.x, F.toast.config.position.y);
    f._timer = setTimeout(
      ()=>T.hide(),
      F.toast.config.displayTimeMs * durationMult
    );
    return F.toast;
  };

  F.toast = {
    config: {
      position: { x: 5, y: 5 /*viewport-relative, pixels*/ },
      displayTimeMs: 3000
    },
    /**
       Convenience wrapper around a PopupWidget which pops up a shared
       PopupWidget instance to show toast-style messages (commonly seen
       on Android). Its arguments may be anything suitable for passing
       to fossil.dom.append(), and each argument is first append()ed to
       the toast widget, then the widget is shown for
       F.toast.config.displayTimeMs milliseconds. This is called while
       a toast is currently being displayed, the first will be overwritten
       and the time until the message is hidden will be reset.

       The toast is always shown at the viewport-relative coordinates
       defined by the F.toast.config.position.

       The toaster's DOM element has the CSS classes fossil-tooltip
       and fossil-toast, so can be style via those.
    */
    message: function(/*...*/){
      return toastImpl(false,1, arguments);
    },
    /**
       Displays a toast with the 'warning' CSS class assigned to it. It
       displays for 1.5 times as long as a normal toast.
    */
    warning: function(/*...*/){
      return toastImpl('warning',1.5,arguments);
    },
    /**
       Displays a toast with the 'warning' CSS class assigned to it. It
       displays for twice as long as a normal toast.
    */
    error: function(/*...*/){
      return toastImpl('error',2,arguments);
    }
  }/*F.toast*/;


  F.helpButtonlets = {
    /**
       Initializes one or more "help buttonlets". It may be passed any of:

       - A string: CSS selector (multiple matches are legal)

       - A single DOM element.

       - A forEach-compatible container of DOM elements.

       - No arguments, which is equivalent to passing the string
       ".help-buttonlet:not(.processed)".

       Passing the same element(s) more than once is a no-op: during
       initialization, each elements get the class'processed' added to
       it, and any elements with that class are skipped.

       All child nodes of a help buttonlet are removed from the button
       during initialization and stashed away for use in a PopupWidget
       when the botton is clicked.

    */
    setup: function f(){
      if(!f.hasOwnProperty('clickHandler')){
        f.clickHandler = function fch(ev){
          if(!fch.popup){
            fch.popup = new F.PopupWidget({
              cssClass: ['fossil-tooltip', 'help-buttonlet-content'],
              refresh: function(){
              }
            });
            fch.popup.e.style.maxWidth = '80%'/*of body*/;
            const hide = ()=>fch.popup.hide();
            fch.popup.e.addEventListener('click', hide, false);
            document.body.addEventListener('click', hide, true);
            document.body.addEventListener('keydown', function(ev){
              if(fch.popup.isShown() && 27===ev.which){
                fch.popup.hide();
              }
            }, true);
          }
          D.append(D.clearElement(fch.popup.e), ev.target.$helpContent);
          var popupRect = ev.target.getClientRects()[0];
          var x = popupRect.left, y = popupRect.top;
          if(x<0) x = 0;
          if(y<0) y = 0;
          /* Shift the help around a bit to "better" fit the
             screen. However, fch.popup.e.getClientRects() is empty
             until the popup is shown, so we have to show it,
             calculate the resulting size, then move and/or resize it.

             This algorithm/these heuristics can certainly be improved
             upon.
          */
          fch.popup.show(x, y);
          x = popupRect.left, y = popupRect.top;
          popupRect = fch.popup.e.getBoundingClientRect();
          const rectBody = document.body.getClientRects()[0];
          if(popupRect.right > rectBody.right){
            x -= (popupRect.right - rectBody.right);
          }
          if(x + popupRect.width > rectBody.right){
            x = rectBody.x + (rectBody.width*0.1);
            fch.popup.e.style.minWidth = '70%';
          }else{
            fch.popup.e.style.removeProperty('min-width');
            x -= popupRect.width/2;
          }
          if(x<0) x = 0;
          //console.debug("dimensions",x,y, popupRect, rectBody);
          fch.popup.show(x, y);
        };
        f.foreachElement = function(e){
          if(e.classList.contains('processed')) return;
          e.classList.add('processed');
          e.$helpContent = [];
          /* We have to move all child nodes out of the way because we
             cannot hide TEXT nodes via CSS (which cannot select TEXT
             nodes). We have to do it in two steps to avoid invaliding
             the list during traversal. */
          e.childNodes.forEach((ch)=>e.$helpContent.push(ch));
          e.$helpContent.forEach((ch)=>ch.remove());
          e.addEventListener('click', f.clickHandler, false);
        };
      }/*static init*/
      var elems;
      if(!arguments.length){
        arguments[0] = '.help-buttonlet:not(.processed)';
        arguments.length = 1;
      }
      if(arguments.length){
        if('string'===typeof arguments[0]){
          elems = document.querySelectorAll(arguments[0]);
        }else if(arguments[0] instanceof HTMLElement){
          elems = [arguments[0]];
        }else if(arguments[0].forEach){/* assume DOM element list or array */
          elems = arguments[0];
        }
      }
      if(elems) elems.forEach(f.foreachElement);
    },
    
    /**
       Sets up the given element as a "help buttonlet", adding the CSS
       class help-buttonlet to it. Any (optional) arguments after the
       first are appended to the element using fossil.dom.append(), so
       that they become the content for the buttonlet's popup help.

       The element is then passed to this.setup() before it
       is returned from this function.
    */
    create: function(elem/*...body*/){
      D.addClass(elem, 'help-buttonlet');
      if(arguments.length>1){
        const args = Array.prototype.slice.call(arguments,1);
        D.append(elem, args);
      }
      this.setup(elem);
      return elem;
    }
  }/*helpButtonlets*/;

  F.onDOMContentLoaded( ()=>F.helpButtonlets.setup() );
  
})(window.fossil);

Changes to src/fossil.storage.js.

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
...
133
134
135
136
137
138
139















140
141
142
143
  /**
     A proxy for localStorage or sessionStorage or a
     page-instance-local proxy, if neither one is availble.

     Which exact storage implementation is uses is unspecified, and
     apps must not rely on it.
  */
  fossil.storage = {
    storageKeyPrefix: storageKeyPrefix,
    /** Sets the storage key k to value v, implicitly converting
        it to a string. */
    set: (k,v)=>$storage.setItem(storageKeyPrefix+k,v),
    /** Sets storage key k to JSON.stringify(v). */
    setJSON: (k,v)=>$storage.setItem(storageKeyPrefix+k,JSON.stringify(v)),
    /** Returns the value for the given storage key, or
................................................................................
        and sessionStorage are unavailable. */
    isTransient: ()=>$storageHolder!==$storage,
    /** Returns a symbolic name for the current storage mechanism. */
    storageImplName: function(){
      if($storage===window.localStorage) return 'localStorage';
      else if($storage===window.sessionStorage) return 'sessionStorage';
      else return 'transient';















    }
  };

})(window.fossil);







|







 







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




87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
...
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
  /**
     A proxy for localStorage or sessionStorage or a
     page-instance-local proxy, if neither one is availble.

     Which exact storage implementation is uses is unspecified, and
     apps must not rely on it.
  */
  F.storage = {
    storageKeyPrefix: storageKeyPrefix,
    /** Sets the storage key k to value v, implicitly converting
        it to a string. */
    set: (k,v)=>$storage.setItem(storageKeyPrefix+k,v),
    /** Sets storage key k to JSON.stringify(v). */
    setJSON: (k,v)=>$storage.setItem(storageKeyPrefix+k,JSON.stringify(v)),
    /** Returns the value for the given storage key, or
................................................................................
        and sessionStorage are unavailable. */
    isTransient: ()=>$storageHolder!==$storage,
    /** Returns a symbolic name for the current storage mechanism. */
    storageImplName: function(){
      if($storage===window.localStorage) return 'localStorage';
      else if($storage===window.sessionStorage) return 'sessionStorage';
      else return 'transient';
    },

    /**
       Returns a brief help text string for the currently-selected
       storage type.
    */
    storageHelpDescription: function(){
      return {
        localStorage: "Browser-local persistent storage with an "+
          "unspecified long-term lifetime (survives closing the browser, "+
          "but maybe not a browser upgrade).",
        sessionStorage: "Storage local to this browser tab, "+
          "lost if this tab is closed.",
        "transient": "Transient storage local to this invocation of this page."
      }[this.storageImplName()];
    }
  };

})(window.fossil);

Changes to src/fossil.tabs.js.

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
...
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
...
218
219
220
221
222
223
224










225
226
227
228
229
230
231
...
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
  */
  TabManager.defaultOptions = {
    tabAccessKeys: true
  };

  /**
     Internal helper to normalize a method argument to a tab
     element. arg may be a tab DOM element or an index into
     tabMgr.e.tabs.childNodes. Returns the corresponding tab element.

  */
  const tabArg = function(arg,tabMgr){
    if('string'===typeof arg) arg = E(arg);
    else if(tabMgr && 'number'===typeof arg && arg>=0){
      arg = tabMgr.e.tabs.childNodes[arg];
    }
    if(arg){
      if('FIELDSET'===arg.tagName && arg.classList.contains('tab-wrapper')){
        arg = arg.firstElementChild;
      }
    }
    return arg;
  };

  /**
    Sets sets the visibility of tab element e to on or off. e MUST be
    a TabManager tab element which has been wrapped in a
    FIELDSET.tab-wrapper parent element. We disable the hidden
    FIELDSET.tab-wrapper elements so that any access keys assigned
    to their children cannot be inadvertently triggered
  */
  const setVisible = function(e,yes){
    const fsWrapper = e.parentElement/*FIELDSET wrapper*/;
    if(yes){
      D.removeClass(e, 'hidden');
      D.enable(fsWrapper);
    }else{
      D.addClass(e, 'hidden');
      D.disable(fsWrapper);
    }
  };

  TabManager.prototype = {
    /**
       Initializes the tabs associated with the given tab container
       (DOM element or selector for a single element). This must be
       called once before using any other member functions of a given
................................................................................
      if(!f.click){
        f.click = function(e){
         e.target.$manager.switchToTab(e.target.$tab);
        };
      }
      tab = tabArg(tab);
      tab.remove();
      const eFs = D.addClass(D.fieldset(), 'tab-wrapper');
      D.append(eFs, D.addClass(tab,'tab-panel'));
      D.append(this.e.tabs, eFs);
      const tabCount = this.e.tabBar.childNodes.length+1;
      const lbl = tab.dataset.tabLabel || 'Tab #'+tabCount;
      const btn = D.addClass(D.append(D.span(), lbl), 'tab-button');
      D.append(this.e.tabBar,btn);
      btn.$manager = this;
      btn.$tab = tab;
      if(this.options.tabAccessKeys){
................................................................................

       Returns this object.
    */
    addEventListener: function(eventName, callback){
      this.e.container.addEventListener(eventName, callback, false);
      return this;
    },











    /**
       If the given DOM element, unique selector, or integer (0-based
       tab number) is one of this object's tabs, the UI makes that tab
       the currently-visible one, firing any relevant events. Returns
       this object. If the argument is the current tab, this is a
       no-op, and no events are fired.
................................................................................
      if(tab===this._currentTab) return this;
      else if(this._currentTab){
        this._dispatchEvent('before-switch-from', this._currentTab);
      }
      delete this._currentTab;
      this.e.tabs.childNodes.forEach((e,ndx)=>{
        const btn = this.e.tabBar.childNodes[ndx];
        e = e.firstElementChild /* b/c arguments[0] is a FIELDSET wrapper */;
        if(e===tab){
          if(D.hasClass(e,'selected')){
            return;
          }
          self._dispatchEvent('before-switch-to',tab);
          setVisible(e, true);
          this._currentTab = e;







|
|
>






<
<
<
<
<





|
<
<
<


<
<
<
<
<
|
<
<







 







<
|
<







 







>
>
>
>
>
>
>
>
>
>







 







<







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
...
148
149
150
151
152
153
154

155

156
157
158
159
160
161
162
...
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
...
230
231
232
233
234
235
236

237
238
239
240
241
242
243
  */
  TabManager.defaultOptions = {
    tabAccessKeys: true
  };

  /**
     Internal helper to normalize a method argument to a tab
     element. arg may be a tab DOM element, a selector string, or an
     index into tabMgr.e.tabs.childNodes. Returns the corresponding
     tab element.
  */
  const tabArg = function(arg,tabMgr){
    if('string'===typeof arg) arg = E(arg);
    else if(tabMgr && 'number'===typeof arg && arg>=0){
      arg = tabMgr.e.tabs.childNodes[arg];
    }





    return arg;
  };

  /**
    Sets sets the visibility of tab element e to on or off. e MUST be
    a TabManager tab element.



  */
  const setVisible = function(e,yes){





    D[yes ? 'removeClass' : 'addClass'](e, 'hidden');


  };

  TabManager.prototype = {
    /**
       Initializes the tabs associated with the given tab container
       (DOM element or selector for a single element). This must be
       called once before using any other member functions of a given
................................................................................
      if(!f.click){
        f.click = function(e){
         e.target.$manager.switchToTab(e.target.$tab);
        };
      }
      tab = tabArg(tab);
      tab.remove();

      D.append(this.e.tabs, D.addClass(tab,'tab-panel'));

      const tabCount = this.e.tabBar.childNodes.length+1;
      const lbl = tab.dataset.tabLabel || 'Tab #'+tabCount;
      const btn = D.addClass(D.append(D.span(), lbl), 'tab-button');
      D.append(this.e.tabBar,btn);
      btn.$manager = this;
      btn.$tab = tab;
      if(this.options.tabAccessKeys){
................................................................................

       Returns this object.
    */
    addEventListener: function(eventName, callback){
      this.e.container.addEventListener(eventName, callback, false);
      return this;
    },

    /**
       Inserts the given DOM element immediately after the tab bar.
       Intended for a status bar or similar always-visible component.
       Returns this object.
    */
    addCustomWidget: function(e){
      this.e.container.insertBefore(e, this.e.tabs);
      return this;
    },

    /**
       If the given DOM element, unique selector, or integer (0-based
       tab number) is one of this object's tabs, the UI makes that tab
       the currently-visible one, firing any relevant events. Returns
       this object. If the argument is the current tab, this is a
       no-op, and no events are fired.
................................................................................
      if(tab===this._currentTab) return this;
      else if(this._currentTab){
        this._dispatchEvent('before-switch-from', this._currentTab);
      }
      delete this._currentTab;
      this.e.tabs.childNodes.forEach((e,ndx)=>{
        const btn = this.e.tabBar.childNodes[ndx];

        if(e===tab){
          if(D.hasClass(e,'selected')){
            return;
          }
          self._dispatchEvent('before-switch-to',tab);
          setVisible(e, true);
          this._currentTab = e;

Changes to src/fuzz.c.

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
**     ./configure
**
** Then edit the Makefile as follows:
**
**   (1)  Change CC to be "clang-6.0" or some other compiler that
**        supports libFuzzer
**
**   (2)  Chagne APPNAME to "fossil-fuzz"
**
**   (3)  Add "-fsanitize=fuzzer" and "-DFOSSIL_FUZZ" to TCCFLAGS.  Perhaps
**        make the first change "-fsanitize=fuzzer,undefined,address" for
**        extra, but slower, testing.
**
** Then build the fuzzer using:
**







|







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
**     ./configure
**
** Then edit the Makefile as follows:
**
**   (1)  Change CC to be "clang-6.0" or some other compiler that
**        supports libFuzzer
**
**   (2)  Change APPNAME to "fossil-fuzz"
**
**   (3)  Add "-fsanitize=fuzzer" and "-DFOSSIL_FUZZ" to TCCFLAGS.  Perhaps
**        make the first change "-fsanitize=fuzzer,undefined,address" for
**        extra, but slower, testing.
**
** Then build the fuzzer using:
**

Changes to src/hook.c.

37
38
39
40
41
42
43













44
45
46
47
48
49
50
...
120
121
122
123
124
125
126


127

128
129
130
131
132

133
134
135
136
137
138
139
...
241
242
243
244
245
246
247

248
249
250
251
252
253
254
255
256
257

258
259
260
261
262
263
264
...
288
289
290
291
292
293
294

295

296
297
298
299
300
301
302
303
304

305
306
307
308
309
310
311
...
319
320
321
322
323
324
325

326
327
328
329
330
331
332
...
464
465
466
467
468
469
470














471
472
473
474
475
476
477
** into the command via standard input.  Each line of input begins with
** the hash of the artifact and continues with a description of the
** interpretation of the artifact.
*/
#include "config.h"
#include "hook.h"














/*
** List of valid hook types:
*/
static const char *azType[] = {
   "after-receive",
   "before-commit",
   "disabled",
................................................................................
** (N is normally a small number) and so post-receive hooks should
** probably be deferred until after the new artifacts arrive.
**
** If N==0, then there is no expectation of new artifacts arriving
** soon and so post-receive hooks can be run without delay.
*/
void hook_expecting_more_artifacts(int N){


  if( N>0 ){

    db_multi_exec(
      "REPLACE INTO config(name,value,mtime)"
      "VALUES('hook-embargo',now()+%d,now())",
      N
    );

  }else{
    db_unset("hook-embargo",0);
  }
}


/*
................................................................................
    verify_all_options();
    if( zCmd==0 || zType==0 ){
      fossil_fatal("the --command and --type options are required");
    }
    validate_type(zType);
    nSeq = zSeq ? atoi(zSeq) : 10;
    db_begin_write();

    db_multi_exec(
       "INSERT OR IGNORE INTO config(name,value) VALUES('hooks','[]');\n"
       "UPDATE config"
       "  SET value=json_insert("
       "     CASE WHEN json_valid(value) THEN value ELSE '[]' END,'$[#]',"
       "     json_object('cmd',%Q,'type',%Q,'seq',%d)),"
       "      mtime=now()"
       " WHERE name='hooks';",
       zCmd, zType, nSeq
    );

    db_commit_transaction();
  }else
  if( strncmp(zCmd, "edit", nCmd)==0 ){
    const char *zCmd = find_option("command",0,1);
    const char *zType = find_option("type",0,1);
    const char *zSeq = find_option("sequence",0,1);
    int nSeq;
................................................................................
      if( zType ){
        blob_append_sql(&sql, ",'$[%d].type',%Q", id, zType);
      }
      if( zSeq ){
        blob_append_sql(&sql, ",'$[%d].seq',%d", id, nSeq);
      }
      blob_append_sql(&sql,") WHERE name='hooks';");

      db_multi_exec("%s", blob_sql_text(&sql));

      blob_reset(&sql);
    }
    db_commit_transaction();
  }else
  if( strncmp(zCmd, "delete", nCmd)==0 ){
    int i;
    verify_all_options();
    if( g.argc<4 ) usage("delete ID ...");
    db_begin_write();

    db_multi_exec(
       "INSERT OR IGNORE INTO config(name,value) VALUES('hooks','[]');\n"
    );
    for(i=3; i<g.argc; i++){
      const char *zId = g.argv[i];
      if( strcmp(zId,"all")==0 ){
        db_set("hooks","[]", 0);
................................................................................
        "  SET value=json_remove("
        "     CASE WHEN json_valid(value) THEN value ELSE '[]' END,'$[%d]'),"
        "      mtime=now()"
        " WHERE name='hooks';",
        atoi(zId)
      );
    }

    db_commit_transaction();
  }else
  if( strncmp(zCmd, "list", nCmd)==0 ){
    Stmt q;
    int n = 0;
    verify_all_options();
    db_prepare(&q,
................................................................................
  db_finalize(&q);
  db_set("hook-last-rcvid", zNewRcvid, 0);
  blob_reset(&chng);
hook_backoffice_done:
  db_commit_transaction();
  return cnt;
}















/*
** Run all hooks of type zType.  Use zAuxFile as the auxiliary information
** file.
**
** If any hook returns non-zero, then stop running and return non-zero.
** Return zero only if all hooks return zero.







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







 







>
>
|
>





>







 







>










>







 







>

>









>







 







>







 







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







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
...
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
...
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
...
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
...
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
...
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
** into the command via standard input.  Each line of input begins with
** the hash of the artifact and continues with a description of the
** interpretation of the artifact.
*/
#include "config.h"
#include "hook.h"

/*
** SETTING: hooks sensitive
** The "hooks" setting contains JSON that describes all defined
** hooks.  The value is an array of objects.  Each object describes
** a single hook.  Example:
**
**
**    {
**    "type": "after-receive",  // type of hook
**    "cmd": "command-to-run",  // command to run
**    "seq": 50                 // run in this order
**    }
*/
/*
** List of valid hook types:
*/
static const char *azType[] = {
   "after-receive",
   "before-commit",
   "disabled",
................................................................................
** (N is normally a small number) and so post-receive hooks should
** probably be deferred until after the new artifacts arrive.
**
** If N==0, then there is no expectation of new artifacts arriving
** soon and so post-receive hooks can be run without delay.
*/
void hook_expecting_more_artifacts(int N){
  if( !db_is_writeable("repository") ){
    /* No-op */
  }else if( N>0 ){
    db_unprotect(PROTECT_CONFIG);
    db_multi_exec(
      "REPLACE INTO config(name,value,mtime)"
      "VALUES('hook-embargo',now()+%d,now())",
      N
    );
    db_protect_pop();
  }else{
    db_unset("hook-embargo",0);
  }
}


/*
................................................................................
    verify_all_options();
    if( zCmd==0 || zType==0 ){
      fossil_fatal("the --command and --type options are required");
    }
    validate_type(zType);
    nSeq = zSeq ? atoi(zSeq) : 10;
    db_begin_write();
    db_unprotect(PROTECT_CONFIG);
    db_multi_exec(
       "INSERT OR IGNORE INTO config(name,value) VALUES('hooks','[]');\n"
       "UPDATE config"
       "  SET value=json_insert("
       "     CASE WHEN json_valid(value) THEN value ELSE '[]' END,'$[#]',"
       "     json_object('cmd',%Q,'type',%Q,'seq',%d)),"
       "      mtime=now()"
       " WHERE name='hooks';",
       zCmd, zType, nSeq
    );
    db_protect_pop();
    db_commit_transaction();
  }else
  if( strncmp(zCmd, "edit", nCmd)==0 ){
    const char *zCmd = find_option("command",0,1);
    const char *zType = find_option("type",0,1);
    const char *zSeq = find_option("sequence",0,1);
    int nSeq;
................................................................................
      if( zType ){
        blob_append_sql(&sql, ",'$[%d].type',%Q", id, zType);
      }
      if( zSeq ){
        blob_append_sql(&sql, ",'$[%d].seq',%d", id, nSeq);
      }
      blob_append_sql(&sql,") WHERE name='hooks';");
      db_unprotect(PROTECT_CONFIG);
      db_multi_exec("%s", blob_sql_text(&sql));
      db_protect_pop();
      blob_reset(&sql);
    }
    db_commit_transaction();
  }else
  if( strncmp(zCmd, "delete", nCmd)==0 ){
    int i;
    verify_all_options();
    if( g.argc<4 ) usage("delete ID ...");
    db_begin_write();
    db_unprotect(PROTECT_CONFIG);
    db_multi_exec(
       "INSERT OR IGNORE INTO config(name,value) VALUES('hooks','[]');\n"
    );
    for(i=3; i<g.argc; i++){
      const char *zId = g.argv[i];
      if( strcmp(zId,"all")==0 ){
        db_set("hooks","[]", 0);
................................................................................
        "  SET value=json_remove("
        "     CASE WHEN json_valid(value) THEN value ELSE '[]' END,'$[%d]'),"
        "      mtime=now()"
        " WHERE name='hooks';",
        atoi(zId)
      );
    }
    db_protect_pop();
    db_commit_transaction();
  }else
  if( strncmp(zCmd, "list", nCmd)==0 ){
    Stmt q;
    int n = 0;
    verify_all_options();
    db_prepare(&q,
................................................................................
  db_finalize(&q);
  db_set("hook-last-rcvid", zNewRcvid, 0);
  blob_reset(&chng);
hook_backoffice_done:
  db_commit_transaction();
  return cnt;
}

/*
** Return true if one or more hooks of type zType exit.
*/
int hook_exists(const char *zType){
  return db_exists(
      "SELECT 1"
      "  FROM config, json_each(config.value) AS jx"
      " WHERE config.name='hooks' AND json_valid(config.value)"
      "   AND json_extract(jx.value,'$.type')=%Q"
      " ORDER BY json_extract(jx.value,'$.seq');",
      zType
  );
}

/*
** Run all hooks of type zType.  Use zAuxFile as the auxiliary information
** file.
**
** If any hook returns non-zero, then stop running and return non-zero.
** Return zero only if all hooks return zero.

Changes to src/http_ssl.c.

574
575
576
577
578
579
580

581
582
583
584
585
586

587
588
589
590
591
592
593
  if( strncmp("remove-exception",zCmd,nCmd)==0 ){
    int i;
    Blob sql;
    char *zSep = "(";
    db_begin_transaction();
    blob_init(&sql, 0, 0);
    if( g.argc==4 && find_option("all",0,0)!=0 ){

      blob_append_sql(&sql,
        "DELETE FROM global_config WHERE name GLOB 'cert:*';\n"
        "DELETE FROM global_config WHERE name GLOB 'trusted:*';\n"
        "DELETE FROM config WHERE name GLOB 'cert:*';\n"
        "DELETE FROM config WHERE name GLOB 'trusted:*';\n"
      );

    }else{
      if( g.argc<4 ){
        usage("remove-exception DOMAIN-NAME ...");
      }
      blob_append_sql(&sql,"DELETE FROM global_config WHERE name IN ");
      for(i=3; i<g.argc; i++){
        blob_append_sql(&sql,"%s'cert:%q','trust:%q'",







>






>







574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
  if( strncmp("remove-exception",zCmd,nCmd)==0 ){
    int i;
    Blob sql;
    char *zSep = "(";
    db_begin_transaction();
    blob_init(&sql, 0, 0);
    if( g.argc==4 && find_option("all",0,0)!=0 ){
      db_unprotect(PROTECT_CONFIG);
      blob_append_sql(&sql,
        "DELETE FROM global_config WHERE name GLOB 'cert:*';\n"
        "DELETE FROM global_config WHERE name GLOB 'trusted:*';\n"
        "DELETE FROM config WHERE name GLOB 'cert:*';\n"
        "DELETE FROM config WHERE name GLOB 'trusted:*';\n"
      );
      db_protect_pop();
    }else{
      if( g.argc<4 ){
        usage("remove-exception DOMAIN-NAME ...");
      }
      blob_append_sql(&sql,"DELETE FROM global_config WHERE name IN ");
      for(i=3; i<g.argc; i++){
        blob_append_sql(&sql,"%s'cert:%q','trust:%q'",

Changes to src/import.c.

158
159
160
161
162
163
164

165
166

167
168
169
170
171
172
173
...
200
201
202
203
204
205
206



207
208
209
210
211
212
213
...
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
...
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
....
1347
1348
1349
1350
1351
1352
1353

1354
1355
1356
1357
1358
1359
1360
1361
....
1757
1758
1759
1760
1761
1762
1763

1764
1765
1766
1767
1768
1769

1770
1771
1772
1773
1774
1775
1776
  Blob cmpr;
  int rid;

  hname_hash(pContent, 0, &hash);
  rid = db_int(0, "SELECT rid FROM blob WHERE uuid=%B", &hash);
  if( rid==0 ){
    static Stmt ins;

    db_static_prepare(&ins,
        "INSERT INTO blob(uuid, size, content) VALUES(:uuid, :size, :content)"

    );
    db_bind_text(&ins, ":uuid", blob_str(&hash));
    db_bind_int(&ins, ":size", gg.nData);
    blob_compress(pContent, &cmpr);
    db_bind_blob(&ins, ":content", &cmpr);
    db_step(&ins);
    db_reset(&ins);
................................................................................
/*
** Use data accumulated in gg from a "blob" record to add a new file
** to the BLOB table.
*/
static void finish_blob(void){
  Blob content;
  blob_init(&content, gg.aData, gg.nData);



  fast_insert_content(&content, gg.zMark, 0, 0);
  blob_reset(&content);
  import_reset(0);
}

/*
** Use data accumulated in gg from a "tag" record to add a new
................................................................................
      ** of pattern B with the same TAGNAME, then only put the tag on the
      ** last commit that holds that tag.
      **
      ** None of the above is explained in the git-fast-export
      ** documentation.  We had to figure it out via trial and error.
      */
      for(i=5; i<strlen(zRefName) && zRefName[i]!='/'; i++){}
      gg.tagCommit = strncmp(&zRefName[5], "tags", 4)==0;  /* True for pattern B */
      if( zRefName[i+1]!=0 ) zRefName += i+1;
      if( fossil_strcmp(zRefName, "master")==0 ) zRefName = ggit.zMasterName;
      gg.zBranch = fossil_strdup(zRefName);
      gg.fromLoaded = 0;
    }else
    if( strncmp(zLine, "tag ", 4)==0 ){
      gg.xFinish();
................................................................................
        gg.zUser = fossil_strdup(z);
      }
      secSince1970 = 0;
      for(zTo++; fossil_isdigit(*zTo); zTo++){
        secSince1970 = secSince1970*10 + *zTo - '0';
      }
      fossil_free(gg.zDate);
      gg.zDate = db_text(0, "SELECT datetime(%lld, 'unixepoch')", secSince1970);
      gg.zDate[10] = 'T';
    }else
    if( strncmp(zLine, "from ", 5)==0 ){
      trim_newline(&zLine[5]);
      fossil_free(gg.zFromMark);
      gg.zFromMark = fossil_strdup(&zLine[5]);
      fossil_free(gg.zFrom);
................................................................................
    "   AND tbranch=:branch"
  );
  db_prepare(&addRev,
    "INSERT OR IGNORE INTO xrevisions (trev, tbranch) VALUES(:rev, :branch)"
  );
  db_prepare(&cpyPath,
    "INSERT INTO xfiles (tpath, tbranch, tuuid, tperm)"

    " SELECT :path||:sep||substr(filename, length(:srcpath)+2), :branch, uuid, perm"
    " FROM xfoci"
    " WHERE checkinID=:rid"
    "   AND filename>:srcpath||'/'"
    "   AND filename<:srcpath||'0'"
  );
  db_prepare(&cpyRoot,
    "INSERT INTO xfiles (tpath, tbranch, tuuid, tperm)"
................................................................................
  }
  if( !incrFlag ){
    if( forceFlag ) file_delete(g.argv[2]);
    db_create_repository(g.argv[2]);
  }
  db_open_repository(g.argv[2]);
  db_open_config(0, 0);


  db_begin_transaction();
  if( !incrFlag ){
    db_initial_setup(0, 0, zDefaultUser);
    db_set("main-branch", gimport.zTrunkName, 0);
  }


  if( svnFlag ){
    db_multi_exec(
       "CREATE TEMP TABLE xrevisions("
       " trev INTEGER, tbranch INT, trid INT, tparent INT DEFAULT 0,"
       " UNIQUE(tbranch, trev)"
       ");"







>

|
>







 







>
>
>







 







|







 







|







 







>
|







 







>






>







158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
...
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
...
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
...
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
....
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
....
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
  Blob cmpr;
  int rid;

  hname_hash(pContent, 0, &hash);
  rid = db_int(0, "SELECT rid FROM blob WHERE uuid=%B", &hash);
  if( rid==0 ){
    static Stmt ins;
    assert( g.rcvid>0 );
    db_static_prepare(&ins,
        "INSERT INTO blob(uuid, size, rcvid, content)"
        "VALUES(:uuid, :size, %d, :content)", g.rcvid
    );
    db_bind_text(&ins, ":uuid", blob_str(&hash));
    db_bind_int(&ins, ":size", gg.nData);
    blob_compress(pContent, &cmpr);
    db_bind_blob(&ins, ":content", &cmpr);
    db_step(&ins);
    db_reset(&ins);
................................................................................
/*
** Use data accumulated in gg from a "blob" record to add a new file
** to the BLOB table.
*/
static void finish_blob(void){
  Blob content;
  blob_init(&content, gg.aData, gg.nData);
  if( manifest_is_well_formed(gg.aData, gg.nData) ){
    sterilize_manifest(&content, -1);
  }
  fast_insert_content(&content, gg.zMark, 0, 0);
  blob_reset(&content);
  import_reset(0);
}

/*
** Use data accumulated in gg from a "tag" record to add a new
................................................................................
      ** of pattern B with the same TAGNAME, then only put the tag on the
      ** last commit that holds that tag.
      **
      ** None of the above is explained in the git-fast-export
      ** documentation.  We had to figure it out via trial and error.
      */
      for(i=5; i<strlen(zRefName) && zRefName[i]!='/'; i++){}
      gg.tagCommit = strncmp(&zRefName[5], "tags", 4)==0; /* pattern B */
      if( zRefName[i+1]!=0 ) zRefName += i+1;
      if( fossil_strcmp(zRefName, "master")==0 ) zRefName = ggit.zMasterName;
      gg.zBranch = fossil_strdup(zRefName);
      gg.fromLoaded = 0;
    }else
    if( strncmp(zLine, "tag ", 4)==0 ){
      gg.xFinish();
................................................................................
        gg.zUser = fossil_strdup(z);
      }
      secSince1970 = 0;
      for(zTo++; fossil_isdigit(*zTo); zTo++){
        secSince1970 = secSince1970*10 + *zTo - '0';
      }
      fossil_free(gg.zDate);
      gg.zDate = db_text(0, "SELECT datetime(%lld, 'unixepoch')",secSince1970);
      gg.zDate[10] = 'T';
    }else
    if( strncmp(zLine, "from ", 5)==0 ){
      trim_newline(&zLine[5]);
      fossil_free(gg.zFromMark);
      gg.zFromMark = fossil_strdup(&zLine[5]);
      fossil_free(gg.zFrom);
................................................................................
    "   AND tbranch=:branch"
  );
  db_prepare(&addRev,
    "INSERT OR IGNORE INTO xrevisions (trev, tbranch) VALUES(:rev, :branch)"
  );
  db_prepare(&cpyPath,
    "INSERT INTO xfiles (tpath, tbranch, tuuid, tperm)"
    " SELECT :path||:sep||substr(filename,"
          "  length(:srcpath)+2), :branch, uuid, perm"
    " FROM xfoci"
    " WHERE checkinID=:rid"
    "   AND filename>:srcpath||'/'"
    "   AND filename<:srcpath||'0'"
  );
  db_prepare(&cpyRoot,
    "INSERT INTO xfiles (tpath, tbranch, tuuid, tperm)"
................................................................................
  }
  if( !incrFlag ){
    if( forceFlag ) file_delete(g.argv[2]);
    db_create_repository(g.argv[2]);
  }
  db_open_repository(g.argv[2]);
  db_open_config(0, 0);
  db_unprotect(PROTECT_ALL);

  db_begin_transaction();
  if( !incrFlag ){
    db_initial_setup(0, 0, zDefaultUser);
    db_set("main-branch", gimport.zTrunkName, 0);
  }
  content_rcvid_init(svnFlag ? "svn-import" : "git-import");

  if( svnFlag ){
    db_multi_exec(
       "CREATE TEMP TABLE xrevisions("
       " trev INTEGER, tbranch INT, trid INT, tparent INT DEFAULT 0,"
       " UNIQUE(tbranch, trev)"
       ");"

Changes to src/info.c.

1045
1046
1047
1048
1049
1050
1051

1052
1053
1054
1055
1056
1057
1058
....
2009
2010
2011
2012
2013
2014
2015
2016

2017




2018
2019
2020
2021
2022
2023







2024
2025
2026


2027

2028
2029
2030
2031
2032




2033
2034
2035
2036
2037
2038
2039
....
2045
2046
2047
2048
2049
2050
2051

2052
2053
2054









2055

2056
2057
2058

2059
2060
2061





2062
2063
2064
2065
2066
2067
2068
2069
2070









2071


2072
2073
2074
2075
2076
2077





2078
2079
2080
2081
2082
2083

2084
2085
2086



2087
2088
2089
2090
2091
2092



2093
2094
2095

2096
2097



























2098
2099
2100
2101
2102
2103
2104
....
2116
2117
2118
2119
2120
2121
2122

2123
2124
2125
2126
2127
2128
2129
....
2140
2141
2142
2143
2144
2145
2146

2147
2148
2149
2150
2151
2152
2153
....
2249
2250
2251
2252
2253
2254
2255
2256


2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
....
2348
2349
2350
2351
2352
2353
2354







2355
2356
2357
2358
2359
2360
2361
....
2366
2367
2368
2369
2370
2371
2372

2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384


2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403

2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
....
3341
3342
3343
3344
3345
3346
3347




































  @ <div class="section">Content</div>
  blob_init(&wiki, pWiki->zWiki, -1);
  safe_html_context(DOCSRC_WIKI);
  wiki_render_by_mimetype(&wiki, pWiki->zMimetype);
  blob_reset(&wiki);
  manifest_destroy(pWiki);

  style_footer();
}

/*
** Find an check-in based on query parameter zParam and parse its
** manifest.  Return the number of errors.
*/
................................................................................
    }
  }
  manifest_destroy(pManifest);
  return rid;
}

/*
** The "z" argument is a string that contains the text of a source code

** file.  This routine appends that text to the HTTP reply with line numbering.




**
** zLn is the ?ln= parameter for the HTTP query.  If there is an argument,
** then highlight that line number and scroll to it once the page loads.
** If there are two line numbers, highlight the range of lines.
** Multiple ranges can be highlighed by adding additional line numbers
** separated by a non-digit character (also not one of [-,.]).







*/
void output_text_with_line_numbers(
  const char *z,


  const char *zLn

){
  int iStart, iEnd;    /* Start and end of region to highlight */
  int n = 0;           /* Current line number */
  int i = 0;           /* Loop index */
  int iTop = 0;        /* Scroll so that this line is on top of screen. */




  Stmt q;

  iStart = iEnd = atoi(zLn);
  db_multi_exec(
    "CREATE TEMP TABLE lnos(iStart INTEGER PRIMARY KEY, iEnd INTEGER)");
  if( iStart>0 ){
    do{
................................................................................
        while( fossil_isdigit(zLn[i]) ) i++;
      }
      while( fossil_isdigit(zLn[i]) ) i++;
      if( iEnd<iStart ) iEnd = iStart;
      db_multi_exec(
        "INSERT OR REPLACE INTO lnos VALUES(%d,%d)", iStart, iEnd
      );

      iStart = iEnd = atoi(&zLn[i++]);
    }while( zLn[i] && iStart && iEnd );
  }









  db_prepare(&q, "SELECT min(iStart), max(iEnd) FROM lnos");

  if( db_step(&q)==SQLITE_ROW ){
    iStart = db_column_int(&q, 0);
    iEnd = db_column_int(&q, 1);

    iTop = iStart - 15 + (iEnd-iStart)/4;
    if( iTop>iStart - 2 ) iTop = iStart-2;
  }





  db_finalize(&q);
  @ <pre>
  while( z[0] ){
    n++;
    db_prepare(&q,
      "SELECT min(iStart), max(iEnd) FROM lnos"
      " WHERE iStart <= %d AND iEnd >= %d", n, n);
    if( db_step(&q)==SQLITE_ROW ){
      iStart = db_column_int(&q, 0);









      iEnd = db_column_int(&q, 1);


    }
    db_finalize(&q);
    for(i=0; z[i] && z[i]!='\n'; i++){}
    if( n==iTop ) cgi_append_content("<span id=\"scrollToMe\">", -1);
    if( n==iStart ){
      cgi_append_content("<div class=\"selectedText\">",-1);





    }
    cgi_printf("%6d  ", n);
    if( i>0 ){
      char *zHtml = htmlize(z, i);
      cgi_append_content(zHtml, -1);
      fossil_free(zHtml);

    }
    if( n==iTop ) cgi_append_content("</span>", -1);
    if( n==iEnd ) cgi_append_content("</div>", -1);



    else cgi_append_content("\n", 1);
    z += i;
    if( z[0]=='\n' ) z++;
  }
  if( n<iEnd ) cgi_printf("</div>");
  @ </pre>



  if( db_int(0, "SELECT EXISTS(SELECT 1 FROM lnos)") ){
    builtin_request_js("scroll.js");
  }

}





























/*
** WEBPAGE: artifact
** WEBPAGE: file
** WEBPAGE: whatis
**
** Typical usage:
................................................................................
**   verbose         - show more detail in the description
**   download        - redirect to the download (artifact page only)
**   name=NAME       - filename or hash as a query parameter
**   filename=NAME   - alternative spelling for "name="
**   fn=NAME         - alternative spelling for "name="
**   ci=VERSION      - The specific check-in to use with "name=" to
**                     identify the file.

**
** The /artifact page show the complete content of a file
** identified by HASH.  The /whatis page shows only a description
** of how the artifact is used.  The /file page shows the most recent
** version of the file or directory called NAME, or a list of the
** top-level directory if NAME is omitted.
**
................................................................................
void artifact_page(void){
  int rid = 0;
  Blob content;
  const char *zMime;
  Blob downloadName;
  int renderAsWiki = 0;
  int renderAsHtml = 0;

  int objType;
  int asText;
  const char *zUuid = 0;
  u32 objdescFlags = OBJDESC_BASE;
  int descOnly = fossil_strcmp(g.zPath,"whatis")==0;
  int isFile = fossil_strcmp(g.zPath,"file")==0;
  const char *zLn = P("ln");
................................................................................
      @ from the %z(href("%R/info/tip"))latest check-in</a></h2>
    }else{
      const char *zPath;
      Blob path;
      blob_zero(&path);
      hyperlinked_path(zName, &path, zCI, "dir", "", LINKPATH_FINFO);
      zPath = blob_str(&path);
      @ <h2>File %s(zPath) \


      if( isBranchCI ){
        @ on branch %z(href("%R/timeline?r=%T",zCI))%h(zCI)</a></h2>
      }else if( isSymbolicCI ){
        @ as of check-in %z(href("%R/info/%!S",zCIUuid))%s(zCI)</a></h2>
      }else{
        @ as of check-in [%z(href("%R/info/%!S",zCIUuid))%S(zCIUuid)</a>]</h2>
      }
      blob_reset(&path);
    }
    style_submenu_element("Artifact", "%R/artifact/%S", zUuid);
    style_submenu_element("Annotate", "%R/annotate?filename=%T&checkin=%T",
                          zName, zCI);
    style_submenu_element("Blame", "%R/blame?filename=%T&checkin=%T",
................................................................................
           || fossil_strcmp(zMime, "text/x-markdown")==0 ){
      if( asText ){
        style_submenu_element("Wiki", "%s", url_render(&url, "txt", 0, 0, 0));
      }else{
        renderAsWiki = 1;
        style_submenu_element("Text", "%s", url_render(&url, "txt", "1", 0, 0));
      }







    }
    if( fileedit_is_editable(zName) ){
      style_submenu_element("Edit",
                            "%R/fileedit?filename=%T&checkin=%!S",
                            zName, zCI);
    }
  }
................................................................................
    style_submenu_element("Content", "%R/artifact/%s", zUuid);
  }else{
    @ <hr />
    content_get(rid, &content);
    if( renderAsWiki ){
      safe_html_context(DOCSRC_FILE);
      wiki_render_by_mimetype(&content, zMime);

    }else if( renderAsHtml ){
      @ <iframe src="%R/raw/%s(zUuid)"
      @ width="100%%" frameborder="0" marginwidth="0" marginheight="0"
      @ sandbox="allow-same-origin" id="ifm1">
      @ </iframe>
      @ <script nonce="%h(style_nonce())">
      @ document.getElementById("ifm1").addEventListener("load",
      @   function(){
      @     this.height=this.contentDocument.documentElement.scrollHeight + 75;
      @   }
      @ );
      @ </script>


    }else{
      style_submenu_element("Hex", "%s/hexdump?name=%s", g.zTop, zUuid);
      if( zLn==0 || atoi(zLn)==0 ){
        style_submenu_checkbox("ln", "Line Numbers", 0, 0);
      }
      blob_to_utf8_no_bom(&content, 0);
      zMime = mimetype_from_content(&content);
      @ <blockquote>
      if( zMime==0 ){
        const char *z, *zFileName, *zExt;
        z = blob_str(&content);
        zFileName = db_text(0,
         "SELECT name FROM mlink, filename"
         " WHERE filename.fnid=mlink.fnid"
         "   AND mlink.fid=%d",
         rid);
        zExt = zFileName ? strrchr(zFileName, '.') : 0;
        if( zLn ){
          output_text_with_line_numbers(z, zLn);

        }else if( zExt && zExt[1] ){
          @ <pre>
          @ <code class="language-%s(zExt+1)">%h(z)</code>
          @ </pre>
        }else{
          @ <pre>
          @ %h(z)
          @ </pre>
        }
      }else if( strncmp(zMime, "image/", 6)==0 ){
................................................................................
  if( fDryRun==0 ){
    show_common_info(rid, "hash:", 1, 0);
  }
  if( g.localOpen ){
    manifest_to_disk(rid);
  }
}










































>







 







|
>
|
>
>
>
>






>
>
>
>
>
>
>



>
>
|
>





>
>
>
>







 







>



>
>
>
>
>
>
>
>
>
|
>
|
|
|
>
|
|
|
>
>
>
>
>
|
<
<
<
<
<
<
<
<
>
>
>
>
>
>
>
>
>
|
>
>
|
<
<
<
|
<
>
>
>
>
>

<
<
<
<
<
>
|
|
<
>
>
>
|
<
<

|
<
>
>
>
|
|
|
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>







 







>







 







|
>
>



|

|







 







>
>
>
>
>
>
>







 







>





|






>
>







|








|

|
>


|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
....
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
....
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
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





2120
2121
2122

2123
2124
2125
2126


2127
2128

2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
....
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
....
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
....
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
....
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
....
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
....
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464

  @ <div class="section">Content</div>
  blob_init(&wiki, pWiki->zWiki, -1);
  safe_html_context(DOCSRC_WIKI);
  wiki_render_by_mimetype(&wiki, pWiki->zMimetype);
  blob_reset(&wiki);
  manifest_destroy(pWiki);
  document_emit_js();
  style_footer();
}

/*
** Find an check-in based on query parameter zParam and parse its
** manifest.  Return the number of errors.
*/
................................................................................
    }
  }
  manifest_destroy(pManifest);
  return rid;
}

/*
** The "z" argument is a string that contains the text of a source
** code file and nZ is its length in bytes. This routine appends that
** text to the HTTP reply with line numbering.
**
** zName is the content's file name, if any (it may be NULL). If that
** name contains a '.' then the part after the final '.' is used as
** the X part of a "language-X" CSS class on the generated CODE block.
**
** zLn is the ?ln= parameter for the HTTP query.  If there is an argument,
** then highlight that line number and scroll to it once the page loads.
** If there are two line numbers, highlight the range of lines.
** Multiple ranges can be highlighed by adding additional line numbers
** separated by a non-digit character (also not one of [-,.]).
**
** If includeJS is true then the JS code associated with line
** numbering is also emitted, else it is not. If this routine is
** called multiple times in a single app run, the JS is emitted only
** once. Note that when using this routine to emit Ajax responses, the
** JS should be not be included, as it will not get imported properly
** into the response's rendering.
*/
void output_text_with_line_numbers(
  const char *z,
  int nZ,
  const char *zName,
  const char *zLn,
  int includeJS
){
  int iStart, iEnd;    /* Start and end of region to highlight */
  int n = 0;           /* Current line number */
  int i = 0;           /* Loop index */
  int iTop = 0;        /* Scroll so that this line is on top of screen. */
  int nLine = 0;       /* content line count */
  int nSpans = 0;      /* number of distinct zLn spans */
  const char *zExt = file_extension(zName);
  static int emittedJS = 0; /* emitted shared JS yet? */
  Stmt q;

  iStart = iEnd = atoi(zLn);
  db_multi_exec(
    "CREATE TEMP TABLE lnos(iStart INTEGER PRIMARY KEY, iEnd INTEGER)");
  if( iStart>0 ){
    do{
................................................................................
        while( fossil_isdigit(zLn[i]) ) i++;
      }
      while( fossil_isdigit(zLn[i]) ) i++;
      if( iEnd<iStart ) iEnd = iStart;
      db_multi_exec(
        "INSERT OR REPLACE INTO lnos VALUES(%d,%d)", iStart, iEnd
      );
      ++nSpans;
      iStart = iEnd = atoi(&zLn[i++]);
    }while( zLn[i] && iStart && iEnd );
  }
  /*cgi_printf("<!-- ln span count=%d -->", nSpans);*/
  cgi_append_content("<table class='numbered-lines'><tbody>"
                     "<tr><td class='line-numbers'>", -1);
  iStart = iEnd = 0;
  count_lines(z, nZ, &nLine);
  for( n=1 ; n<=nLine; ++n ){
    const char * zAttr = "";
    const char * zId = "";
    if(nSpans>0 && iEnd==0){/*Grab the next range of zLn marking*/
      db_prepare(&q, "SELECT iStart, iEnd FROM lnos "
                 "WHERE iStart >= %d ORDER BY iStart", n);
      if( db_step(&q)==SQLITE_ROW ){
        iStart = db_column_int(&q, 0);
        iEnd = db_column_int(&q, 1);
        if(!iTop){
          iTop = iStart - 15 + (iEnd-iStart)/4;
          if( iTop>iStart - 2 ) iTop = iStart-2;
        }
      }else{
        /* Note that overlapping multi-spans, e.g. 10-15+12-20,
           can cause us to miss a row. */
        iStart = iEnd = 0;
      }
      db_finalize(&q);








      --nSpans;
      /*cgi_printf("<!-- iStart=%d, iEnd=%d -->", iStart, iEnd);*/
    }
    if(n==iTop) {
      zId = " id='scrollToMe'";
    }
    if(n==iStart){/*Figure out which CSS class(es) this line needs...*/
      if(n==iEnd){
        zAttr = " class='selected-line start end'";
        iEnd = 0;
      }else{
        zAttr = " class='selected-line start'";
      }



      iStart = 0;

    }else if(n==iEnd){
      zAttr = " class='selected-line end'";
      iEnd = 0;
    }else if( n>iStart && n<iEnd ){
      zAttr = " class='selected-line'";
    }





    cgi_printf("<span%s%s>%6d</span>", zId, zAttr, n);
  }
  cgi_append_content("</td><td class='file-content'><pre>",-1);

  if(zExt && *zExt){
    cgi_printf("<code class='language-%h'>",zExt);
  }else{
    cgi_append_content("<code>", -1);


  }
  cgi_printf("%z", htmlize(z, nZ));

  CX("</code></pre></td></tr></tbody></table>\n");
  if(includeJS && !emittedJS){
    emittedJS = 1;
    if( db_int(0, "SELECT EXISTS(SELECT 1 FROM lnos)") ){
      builtin_request_js("scroll.js");
    }
    builtin_fossil_js_bundle_or("numbered-lines", 0);
  }
}

/*
** COMMAND: test-line-numbers
**
** Usage: %fossil test-line-numbers FILE ?LN-SPEC?
**
*/
void cmd_test_line_numbers(void){
  Blob content = empty_blob;
  const char * zLn = "";
  const char * zFilename = 0;

  if(g.argc < 3){
    usage("FILE");
  }else if(g.argc>3){
    zLn = g.argv[3];
  }
  db_find_and_open_repository(0,0);
  zFilename = g.argv[2];
  fossil_print("%s %s\n", zFilename, zLn);

  blob_read_from_file(&content, zFilename, ExtFILE);
  output_text_with_line_numbers(blob_str(&content), blob_size(&content),
                                zFilename, zLn, 0);
  blob_reset(&content);
  fossil_print("%b\n", cgi_output_blob());
}

/*
** WEBPAGE: artifact
** WEBPAGE: file
** WEBPAGE: whatis
**
** Typical usage:
................................................................................
**   verbose         - show more detail in the description
**   download        - redirect to the download (artifact page only)
**   name=NAME       - filename or hash as a query parameter
**   filename=NAME   - alternative spelling for "name="
**   fn=NAME         - alternative spelling for "name="
**   ci=VERSION      - The specific check-in to use with "name=" to
**                     identify the file.
**   txt             - Force display of unformatted source text
**
** The /artifact page show the complete content of a file
** identified by HASH.  The /whatis page shows only a description
** of how the artifact is used.  The /file page shows the most recent
** version of the file or directory called NAME, or a list of the
** top-level directory if NAME is omitted.
**
................................................................................
void artifact_page(void){
  int rid = 0;
  Blob content;
  const char *zMime;
  Blob downloadName;
  int renderAsWiki = 0;
  int renderAsHtml = 0;
  int renderAsSvg = 0;
  int objType;
  int asText;
  const char *zUuid = 0;
  u32 objdescFlags = OBJDESC_BASE;
  int descOnly = fossil_strcmp(g.zPath,"whatis")==0;
  int isFile = fossil_strcmp(g.zPath,"file")==0;
  const char *zLn = P("ln");
................................................................................
      @ from the %z(href("%R/info/tip"))latest check-in</a></h2>
    }else{
      const char *zPath;
      Blob path;
      blob_zero(&path);
      hyperlinked_path(zName, &path, zCI, "dir", "", LINKPATH_FINFO);
      zPath = blob_str(&path);
      @ <h2>File %s(zPath) artifact \
      style_copy_button(1,"hash-fid",0,0,"%z%S</a> ",
           href("%R/info/%s",zUuid),zUuid);
      if( isBranchCI ){
        @ on branch %z(href("%R/timeline?r=%T",zCI))%h(zCI)</a></h2>
      }else if( isSymbolicCI ){
        @ part of check-in %z(href("%R/info/%!S",zCIUuid))%s(zCI)</a></h2>
      }else{
        @ part of check-in %z(href("%R/info/%!S",zCIUuid))%S(zCIUuid)</a></h2>
      }
      blob_reset(&path);
    }
    style_submenu_element("Artifact", "%R/artifact/%S", zUuid);
    style_submenu_element("Annotate", "%R/annotate?filename=%T&checkin=%T",
                          zName, zCI);
    style_submenu_element("Blame", "%R/blame?filename=%T&checkin=%T",
................................................................................
           || fossil_strcmp(zMime, "text/x-markdown")==0 ){
      if( asText ){
        style_submenu_element("Wiki", "%s", url_render(&url, "txt", 0, 0, 0));
      }else{
        renderAsWiki = 1;
        style_submenu_element("Text", "%s", url_render(&url, "txt", "1", 0, 0));
      }
    }else if( fossil_strcmp(zMime, "image/svg+xml")==0 ){
      if( asText ){
        style_submenu_element("Svg", "%s", url_render(&url, "txt", 0, 0, 0));
      }else{
        renderAsSvg = 1;
        style_submenu_element("Text", "%s", url_render(&url, "txt", "1", 0, 0));
      }
    }
    if( fileedit_is_editable(zName) ){
      style_submenu_element("Edit",
                            "%R/fileedit?filename=%T&checkin=%!S",
                            zName, zCI);
    }
  }
................................................................................
    style_submenu_element("Content", "%R/artifact/%s", zUuid);
  }else{
    @ <hr />
    content_get(rid, &content);
    if( renderAsWiki ){
      safe_html_context(DOCSRC_FILE);
      wiki_render_by_mimetype(&content, zMime);
      document_emit_js();
    }else if( renderAsHtml ){
      @ <iframe src="%R/raw/%s(zUuid)"
      @ width="100%%" frameborder="0" marginwidth="0" marginheight="0"
      @ sandbox="allow-same-origin" id="ifm1">
      @ </iframe>
      @ <script nonce="%h(style_nonce())">/* info.c:%d(__LINE__) */
      @ document.getElementById("ifm1").addEventListener("load",
      @   function(){
      @     this.height=this.contentDocument.documentElement.scrollHeight + 75;
      @   }
      @ );
      @ </script>
    }else if( renderAsSvg ){
      @ <object type="image/svg+xml" data="%R/raw/%s(zUuid)"></object>
    }else{
      style_submenu_element("Hex", "%s/hexdump?name=%s", g.zTop, zUuid);
      if( zLn==0 || atoi(zLn)==0 ){
        style_submenu_checkbox("ln", "Line Numbers", 0, 0);
      }
      blob_to_utf8_no_bom(&content, 0);
      zMime = mimetype_from_content(&content);
      @ <blockquote class="file-content">
      if( zMime==0 ){
        const char *z, *zFileName, *zExt;
        z = blob_str(&content);
        zFileName = db_text(0,
         "SELECT name FROM mlink, filename"
         " WHERE filename.fnid=mlink.fnid"
         "   AND mlink.fid=%d",
         rid);
        zExt = zFileName ? file_extension(zFileName) : 0;
        if( zLn ){
          output_text_with_line_numbers(z, blob_size(&content),
                                        zFileName, zLn, 1);
        }else if( zExt && zExt[1] ){
          @ <pre>
          @ <code class="language-%s(zExt)">%h(z)</code>
          @ </pre>
        }else{
          @ <pre>
          @ %h(z)
          @ </pre>
        }
      }else if( strncmp(zMime, "image/", 6)==0 ){
................................................................................
  if( fDryRun==0 ){
    show_common_info(rid, "hash:", 1, 0);
  }
  if( g.localOpen ){
    manifest_to_disk(rid);
  }
}


/*
** COMMAND: test-symlink-list
**
** Show all symlinks that have been checked into a Fossil repository.
**
** This command does a linear scan through all check-ins and so might take
** several seconds on a large repository.
*/
void test_symlink_list_cmd(void){
  Stmt q;
  db_find_and_open_repository(0,0);
  add_content_sql_commands(g.db);
  db_prepare(&q,
     "SELECT min(date(e.mtime)),"
           " b.uuid,"
           " f.filename,"
           " content(f.uuid)"
     " FROM event AS e, blob AS b, files_of_checkin(b.uuid) AS f"
     " WHERE e.type='ci'"
     "   AND b.rid=e.objid"
     "   AND f.perm LIKE '%%l%%'"
     " GROUP BY 3, 4"
     " ORDER BY 1 DESC"
  );
  while( db_step(&q)==SQLITE_ROW ){
    fossil_print("%s %.16s %s -> %s\n",
      db_column_text(&q,0),
      db_column_text(&q,1),
      db_column_text(&q,2),
      db_column_text(&q,3));
  }
  db_finalize(&q);
}

Added src/interwiki.c.



































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
/*
** Copyright (c) 2020 D. Richard Hipp
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the Simplified BSD License (also
** known as the "2-Clause License" or "FreeBSD License".)
**
** This program is distributed in the hope that it will be useful,
** but without any warranty; without even the implied warranty of
** merchantability or fitness for a particular purpose.
**
** Author contact information:
**   drh@hwaci.com
**   http://www.hwaci.com/drh/
**
*******************************************************************************
**
** This file contains subroutines used for recognizing, configuring, and
** handling interwiki hyperlinks.
*/
#include "config.h"
#include "interwiki.h"


/*
** If zTarget is an interwiki link, return a pointer to a URL for that
** link target in memory obtained from fossil_malloc().  If zTarget is
** not a valid interwiki link, return NULL.
**
** An interwiki link target is of the form:
**
**       Code:PageName
**
** "Code" is a brief code that describes the intended target wiki.
** The code must be ASCII alpha-numeric.  No symbols or non-ascii
** characters are allows.  Case is ignored for the code.
** Codes are assigned by "intermap:*" entries in the CONFIG table.
** The link is only valid if there exists an entry in the CONFIG table
** that matches "intermap:Code".
**
** Each value of each intermap:Code entry in the CONFIG table is a JSON
** object with the following fields:
**
**    {
**      "base":  Base URL for the remote site.
**      "hash":  Append this to "base" for Hash targets.
**      "wiki":  Append this to "base" for Wiki targets.
**    }
**
** If the remote wiki is Fossil, then the correct value for "hash" 
** is "/info/" and the correct value for "wiki" is "/wiki?name=".
** If (for example) Wikipedia is the remote, then "hash" should be
** omitted and the correct value for "wiki" is "/wiki/".  
**
** PageName is link name of the target wiki.  Several different forms
** of PageName are recognized.
**
**    Path       If PageName is empty or begins with a "/" character, then
**               it is a pathname that is appended to "base".
**
**    Hash       If PageName is a hexadecimal string of 4 or more
**               characters, then PageName is appended to "hash" which
**               is then appended to "base".
**
**    Wiki       If PageName does not start with "/" and it is
**               not a hexadecimal string of 4 or more characters, then
**               PageName is appended to "wiki" and that combination is
**               appended to "base".
**
** See https://en.wikipedia.org/wiki/Interwiki_links for further information
** on interwiki links.
*/
char *interwiki_url(const char *zTarget){
  int nCode;
  int i;
  const char *zPage;
  int nPage;
  char *zUrl = 0;
  Stmt q;
  for(i=0; fossil_isalnum(zTarget[i]); i++){}
  if( zTarget[i]!=':' ) return 0;
  nCode = i;
  if( nCode==4 && strncmp(zTarget,"wiki",4)==0 ) return 0;
  zPage = zTarget + nCode + 1;
  nPage = (int)strlen(zPage);
  db_prepare(&q, 
     "SELECT json_extract(value,'$.base'),"
           " json_extract(value,'$.hash'),"
           " json_extract(value,'$.wiki')"
     " FROM config WHERE name=lower('interwiki:%.*q')",
     nCode, zTarget);
  while( db_step(&q)==SQLITE_ROW ){
    const char *zBase = db_column_text(&q,0);
    if( zBase==0 || zBase[0]==0 ) break;
    if( nPage==0 || zPage[0]=='/' ){
      /* Path */
      zUrl = mprintf("%s%s", zBase, zPage);
    }else if( nPage>=4 && validate16(zPage,nPage) ){
      /* Hash */
      const char *zHash = db_column_text(&q,1);
      if( zHash && zHash[0] ){
        zUrl = mprintf("%s%s%s", zBase, zHash, zPage);
      }
    }else{
      /* Wiki */
      const char *zWiki = db_column_text(&q,2);
      if( zWiki && zWiki[0] ){
        zUrl = mprintf("%s%s%s", zBase, zWiki, zPage);
      }
    }
    break;
  }
  db_finalize(&q);
  return zUrl;
}

/*
** If hyperlink target zTarget begins with an interwiki tag that ought
** to be excluded from display, then return the number of characters in
** that tag.
**
** Path interwiki targets always return zero.  In other words, links
** of the form:
**
**       remote:/path/to/file.txt
**
** Do not have the interwiki tag removed.  But Hash and Wiki links are
** transformed:
**
**       src:39cb0a323f2f3fb6  ->  39cb0a323f2f3fb6
**       fossil:To Do List     ->  To Do List
*/
int interwiki_removable_prefix(const char *zTarget){
  int i;
  for(i=0; fossil_isalnum(zTarget[i]); i++){}
  if( zTarget[i]!=':' ) return 0;
  i++;
  if( zTarget[i]==0 || zTarget[i]=='/' ) return 0;
  return i;
}

/*
** Verify that a name is a valid interwiki "Code".  Rules:
**
**     *    ascii
**     *    alphanumeric
*/
static int interwiki_valid_name(const char *zName){
  int i;
  for(i=0; zName[i]; i++){
    if( !fossil_isalnum(zName[i]) ) return 0;
  }
  return 1;
}

/*
** COMMAND: interwiki*
**
** Usage: %fossil interwiki COMMAND ...
**
** Manage the "intermap" that defines the mapping from interwiki tags
** to complete URLs for interwiki links.
**
** >  fossil interwiki delete TAG ...
**
**        Delete one or more interwiki maps.
**
** >  fossil interwiki edit TAG --base URL --hash PATH --wiki PATH
**
**        Create a interwiki referenced call TAG.  The base URL is
**        the --base option, which is required.  The --hash and --wiki
**        paths are optional.  The TAG must be lower-case alphanumeric
**        and must be unique.  A new entry is created if it does not
**        already exit.
**
** >  fossil interwiki list
**
**        Show all interwiki mappings.
*/
void interwiki_cmd(void){
  const char *zCmd;
  int nCmd;
  db_find_and_open_repository(0, 0);
  if( g.argc<3 ){
    usage("SUBCOMMAND ...");
  }
  zCmd = g.argv[2];
  nCmd = (int)strlen(zCmd);
  if( strncmp(zCmd,"edit",nCmd)==0 ){
    const char *zName;
    const char *zBase = find_option("base",0,1);
    const char *zHash = find_option("hash",0,1);
    const char *zWiki = find_option("wiki",0,1);
    verify_all_options();
    if( g.argc!=4 ) usage("add TAG ?OPTIONS?");
    zName = g.argv[3];
    if( zBase==0 ){
      fossil_fatal("the --base option is required");
    }
    if( !interwiki_valid_name(zName) ){
      fossil_fatal("not a valid interwiki tag: \"%s\"", zName);
    }
    db_begin_write();
    db_unprotect(PROTECT_CONFIG);
    db_multi_exec(
       "REPLACE INTO config(name,value,mtime)"
       " VALUES('interwiki:'||lower(%Q),"
              " json_object('base',%Q,'hash',%Q,'wiki',%Q),"
              " now());",
       zName, zBase, zHash, zWiki
    );
    setup_incr_cfgcnt();
    db_protect_pop();
    db_commit_transaction();
  }else
  if( strncmp(zCmd, "delete", nCmd)==0 ){
    int i;
    verify_all_options();
    if( g.argc<4 ) usage("delete ID ...");
    db_begin_write();
    db_unprotect(PROTECT_CONFIG);
    for(i=3; i<g.argc; i++){
      const char *zName = g.argv[i];
      db_multi_exec(
        "DELETE FROM config WHERE name='interwiki:%q'", 
        zName
      );
    }
    setup_incr_cfgcnt();
    db_protect_pop();
    db_commit_transaction();
  }else
  if( strncmp(zCmd, "list", nCmd)==0 ){
    Stmt q;
    int n = 0;
    verify_all_options();
    db_prepare(&q,
      "SELECT substr(name,11),"
      "       json_extract(value,'$.base'),"
      "       json_extract(value,'$.hash'),"
      "       json_extract(value,'$.wiki')"
      "  FROM config WHERE name glob 'interwiki:*'"
    );
    while( db_step(&q)==SQLITE_ROW ){
      const char *zBase, *z, *zName;
      if( n++ ) fossil_print("\n");
      zName = db_column_text(&q,0);
      zBase = db_column_text(&q,1);
      fossil_print("%-15s %s\n", zName, zBase);
      z = db_column_text(&q,2);
      if( z ){
        fossil_print("%15s %s%s\n", "", zBase, z);
      }
      z = db_column_text(&q,3);
      if( z ){
        fossil_print("%15s %s%s\n", "", zBase, z);
      }
    }
    db_finalize(&q);
  }else
  {
     fossil_fatal("unknown command \"%s\" - should be one of: "
                  "delete edit list", zCmd);
  }
}


/*
** Append text to the "Markdown" or "Wiki" rules pages that shows
** a table of all interwiki tags available on this system.
*/
void interwiki_append_map_table(Blob *out){
  int n = 0;
  Stmt q;
  db_prepare(&q,
    "SELECT substr(name,11), json_extract(value,'$.base')"
    "  FROM config WHERE name glob 'interwiki:*'"
    " ORDER BY name;"
  );
  while( db_step(&q)==SQLITE_ROW ){
    if( n==0 ){
      blob_appendf(out, "<blockquote><table>\n");
    }
    blob_appendf(out,"<tr><td>%h</td><td>&nbsp;&rarr;&nbsp;</td>",
       db_column_text(&q,0));
    blob_appendf(out,"<td>%h</td></tr>\n",
       db_column_text(&q,1));
    n++;
  }
  db_finalize(&q);
  if( n>0 ){
    blob_appendf(out,"</table></blockquote>\n");
  }else{
    blob_appendf(out,"<i>None</i></blockquote>\n");
  }
}

/*
** WEBPAGE: /intermap
**
** View and modify the interwiki tag map or "intermap".
** This page is visible to administrators only.
*/
void interwiki_page(void){
  Stmt q;
  int n = 0;
  const char *z;
  const char *zTag = "";
  const char *zBase = "";
  const char *zHash = "";
  const char *zWiki = "";
  char *zErr = 0;

  login_check_credentials();
  if( !g.perm.Setup ){
    login_needed(0);
    return;
  }
  if( P("submit")!=0 && cgi_csrf_safe(1) ){
    zTag = PT("tag");
    zBase = PT("base");
    zHash = PT("hash");
    zWiki = PT("wiki");
    if( zTag==0 || zTag[0]==0 || !interwiki_valid_name(zTag) ){
      zErr = mprintf("Not a valid interwiki tag name: \"%s\"", zTag?zTag : "");
    }else if( zBase==0 || zBase[0]==0 ){
      db_unprotect(PROTECT_CONFIG);
      db_multi_exec("DELETE FROM config WHERE name='interwiki:%q';", zTag);
      db_protect_pop();
    }else{
      if( zHash && zHash[0]==0 ) zHash = 0;
      if( zWiki && zWiki[0]==0 ) zWiki = 0;
      db_unprotect(PROTECT_CONFIG);
      db_multi_exec(
        "REPLACE INTO config(name,value,mtime)"
        "VALUES('interwiki:'||lower(%Q),"
        " json_object('base',%Q,'hash',%Q,'wiki',%Q),"
        " now());",
        zTag, zBase, zHash, zWiki);
      db_protect_pop();
    }
  }

  style_header("Interwiki Map Configuration");
  @ <p>Interwiki links are hyperlink targets of the form
  @ <blockquote><i>Tag</i><b>:</b><i>PageName</i></blockquote>
  @ <p>Such links resolve to links to <i>PageName</i> on a separate server
  @ identified by <i>Tag</i>.  The Interwiki Map or "intermap" is a mapping
  @ from <i>Tags</i> to complete Server URLs.
  db_prepare(&q,
    "SELECT substr(name,11),"
    "       json_extract(value,'$.base'),"
    "       json_extract(value,'$.hash'),"
    "       json_extract(value,'$.wiki')"
    "  FROM config WHERE name glob 'interwiki:*'"
  );
  while( db_step(&q)==SQLITE_ROW ){
    if( n==0 ){
      @ The current mapping is as follows:
      @ <ol>
    }
    @ <li><p> %h(db_column_text(&q,0))
    @ <ul>
    @ <li> Base-URL: <tt>%h(db_column_text(&q,1))</tt>
    z = db_column_text(&q,2);
    if( z==0 ){
      @ <li> Hash-path: <i>NULL</i>
    }else{
      @ <li> Hash-path: <tt>%h(z)</tt>
    }
    z = db_column_text(&q,3);
    if( z==0 ){
      @ <li> Wiki-path: <i>NULL</i>
    }else{
      @ <li> Wiki-path: <tt>%h(z)</tt>
    }
    @ </ul>
    n++;
  }
  db_finalize(&q);
  if( n ){
    @ </ol>
  }else{
    @ No mappings are currently defined.
  }

  @ <p>To add a new mapping, fill out the form below providing a unique name
  @ for the tag.  To edit an exist mapping, fill out the form and use the
  @ existing name as the tag.  To delete an existing mapping, fill in the
  @ tag field but leave the "Base URL" field blank.</p>
  if( zErr ){
    @ <p class="error">%h(zErr)</p>
  }
  @ <form method="POST" action="%R/intermap">
  login_insert_csrf_secret();
  @ <table border="0">
  @ <tr><td class="form_label" id="imtag">Tag:</td>
  @ <td><input type="text" id="tag" aria-labeledby="imtag" name="tag" \
  @ size="15" value="%h(zTag)"></td></tr>
  @ <tr><td class="form_label" id="imbase">Base&nbsp;URL:</td>
  @ <td><input type="text" id="base" aria-labeledby="imbase" name="base" \
  @ size="70" value="%h(zBase)"></td></tr>
  @ <tr><td class="form_label" id="imhash">Hash-path:</td>
  @ <td><input type="text" id="hash" aria-labeledby="imhash" name="hash" \
  @ size="20" value="%h(zHash)">
  @ (use "<tt>/info/</tt>" when the target is Fossil)</td></tr>
  @ <tr><td class="form_label" id="imwiki">Wiki-path:</td>
  @ <td><input type="text" id="wiki" aria-labeledby="imwiki" name="wiki" \
  @ size="20" value="%h(zWiki)">
  @ (use "<tt>/wiki?name=</tt>" when the target is Fossil)</td></tr>
  @ <tr><td></td>
  @ <td><input type="submit" name="submit" value="Apply Changes"></td></tr>
  @ </table>
  @ </form>

  style_footer(); 
}

Changes to src/json_config.c.

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
{ "clean-glob",             CONFIGSET_PROJ },
{ "ignore-glob",            CONFIGSET_PROJ },
{ "keep-glob",              CONFIGSET_PROJ },
{ "crlf-glob",              CONFIGSET_PROJ },
{ "crnl-glob",              CONFIGSET_PROJ },
{ "encoding-glob",          CONFIGSET_PROJ },
{ "empty-dirs",             CONFIGSET_PROJ },
#ifdef FOSSIL_LEGACY_ALLOW_SYMLINKS
{ "allow-symlinks",         CONFIGSET_PROJ },
#endif
{ "dotfiles",               CONFIGSET_PROJ },

{ "ticket-table",           CONFIGSET_TKT  },
{ "ticket-common",          CONFIGSET_TKT  },
{ "ticket-change",          CONFIGSET_TKT  },
{ "ticket-newpage",         CONFIGSET_TKT  },
{ "ticket-viewpage",        CONFIGSET_TKT  },







<
<
<







81
82
83
84
85
86
87



88
89
90
91
92
93
94
{ "clean-glob",             CONFIGSET_PROJ },
{ "ignore-glob",            CONFIGSET_PROJ },
{ "keep-glob",              CONFIGSET_PROJ },
{ "crlf-glob",              CONFIGSET_PROJ },
{ "crnl-glob",              CONFIGSET_PROJ },
{ "encoding-glob",          CONFIGSET_PROJ },
{ "empty-dirs",             CONFIGSET_PROJ },



{ "dotfiles",               CONFIGSET_PROJ },

{ "ticket-table",           CONFIGSET_TKT  },
{ "ticket-common",          CONFIGSET_TKT  },
{ "ticket-change",          CONFIGSET_TKT  },
{ "ticket-newpage",         CONFIGSET_TKT  },
{ "ticket-viewpage",        CONFIGSET_TKT  },

Changes to src/json_user.c.

210
211
212
213
214
215
216

217
218
219

220
221
222
223
224
225
226
...
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
...
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
      goto error;
    }else if( db_exists("SELECT 1 FROM user WHERE login=%Q", zName) ){
      json_set_err(FSL_JSON_E_RESOURCE_ALREADY_EXISTS,
                   "User %s already exists.", zName);
      goto error;
    }else{
      Stmt ins = empty_Stmt;

      db_prepare(&ins, "INSERT INTO user (login) VALUES(%Q)",zName);
      db_step( &ins );
      db_finalize(&ins);

      uid = db_int(0,"SELECT uid FROM user WHERE login=%Q", zName);
      assert(uid>0);
      zNameNew = zName;
      cson_object_set( pUser, "uid", cson_value_new_integer(uid) );
    }
  }else{
    uid = db_int(0,"SELECT uid FROM user WHERE login=%Q", zName);
................................................................................
#else /* need name for login group support :/ */
  blob_append_sql(&sql, " WHERE login=%Q", zName);
#endif
#if 0
  puts(blob_str(&sql));
  cson_output_FILE( cson_object_value(pUser), stdout, NULL );
#endif

  db_prepare(&q, "%s", blob_sql_text(&sql));
  db_exec(&q);
  db_finalize(&q);

#if TRY_LOGIN_GROUP
  if( zPW || cson_value_get_bool(forceLogout) ){
    Blob groupSql = empty_blob;
    char * zErr = NULL;
    blob_append_sql(&groupSql,
      "INSERT INTO user(login)"
      "  SELECT %Q WHERE NOT EXISTS(SELECT 1 FROM user WHERE login=%Q);",
      zName, zName
    );
    blob_append(&groupSql, blob_str(&sql), blob_size(&sql));

    login_group_sql(blob_str(&groupSql), NULL, NULL, &zErr);

    blob_reset(&groupSql);
    if( zErr ){
      json_set_err( FSL_JSON_E_UNKNOWN,
                    "Repo-group update at least partially failed: %s",
                    zErr);
      free(zErr);
      goto error;
................................................................................
** Impl of /json/user/save.
*/
static cson_value * json_user_save(){
  /* try to get user info from GET/CLI args and construct
     a JSON form of it... */
  cson_object * u = cson_new_object();
  char const * str = NULL;
  char b = -1;
  int i = -1;
  int uid = -1;
  cson_value * payload = NULL;
  /* String properties... */
#define PROP(LK,SK) str = json_find_option_cstr(LK,NULL,SK);     \
  if(str){ cson_object_set(u, LK, json_new_string(str)); } (void)0
  PROP("name","n");
  PROP("password","p");
  PROP("info","i");
  PROP("capabilities","c");
#undef PROP
  /* Boolean properties... */
#define PROP(LK,DFLT) b = json_find_option_bool(LK,NULL,NULL,DFLT);     \
  if(DFLT!=b){ cson_object_set(u, LK, cson_value_new_bool(b)); } (void)0
  PROP("forceLogout",-1);
#undef PROP

#define PROP(LK,DFLT) i = json_find_option_int(LK,NULL,NULL,DFLT);   \
  if(DFLT != i){ cson_object_set(u, LK, cson_value_new_integer(i)); } (void)0
  PROP("uid",-99);
#undef PROP







>



>







 







>



>










>

>







 







|













|







210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
...
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
...
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
      goto error;
    }else if( db_exists("SELECT 1 FROM user WHERE login=%Q", zName) ){
      json_set_err(FSL_JSON_E_RESOURCE_ALREADY_EXISTS,
                   "User %s already exists.", zName);
      goto error;
    }else{
      Stmt ins = empty_Stmt;
      db_unprotect(PROTECT_USER);
      db_prepare(&ins, "INSERT INTO user (login) VALUES(%Q)",zName);
      db_step( &ins );
      db_finalize(&ins);
      db_protect_pop();
      uid = db_int(0,"SELECT uid FROM user WHERE login=%Q", zName);
      assert(uid>0);
      zNameNew = zName;
      cson_object_set( pUser, "uid", cson_value_new_integer(uid) );
    }
  }else{
    uid = db_int(0,"SELECT uid FROM user WHERE login=%Q", zName);
................................................................................
#else /* need name for login group support :/ */
  blob_append_sql(&sql, " WHERE login=%Q", zName);
#endif
#if 0
  puts(blob_str(&sql));
  cson_output_FILE( cson_object_value(pUser), stdout, NULL );
#endif
  db_unprotect(PROTECT_USER);
  db_prepare(&q, "%s", blob_sql_text(&sql));
  db_exec(&q);
  db_finalize(&q);
  db_protect_pop();
#if TRY_LOGIN_GROUP
  if( zPW || cson_value_get_bool(forceLogout) ){
    Blob groupSql = empty_blob;
    char * zErr = NULL;
    blob_append_sql(&groupSql,
      "INSERT INTO user(login)"
      "  SELECT %Q WHERE NOT EXISTS(SELECT 1 FROM user WHERE login=%Q);",
      zName, zName
    );
    blob_append(&groupSql, blob_str(&sql), blob_size(&sql));
    db_unprotect(PROTECT_USER);
    login_group_sql(blob_str(&groupSql), NULL, NULL, &zErr);
    db_protect_pop();
    blob_reset(&groupSql);
    if( zErr ){
      json_set_err( FSL_JSON_E_UNKNOWN,
                    "Repo-group update at least partially failed: %s",
                    zErr);
      free(zErr);
      goto error;
................................................................................
** Impl of /json/user/save.
*/
static cson_value * json_user_save(){
  /* try to get user info from GET/CLI args and construct
     a JSON form of it... */
  cson_object * u = cson_new_object();
  char const * str = NULL;
  int b = -1;
  int i = -1;
  int uid = -1;
  cson_value * payload = NULL;
  /* String properties... */
#define PROP(LK,SK) str = json_find_option_cstr(LK,NULL,SK);     \
  if(str){ cson_object_set(u, LK, json_new_string(str)); } (void)0
  PROP("name","n");
  PROP("password","p");
  PROP("info","i");
  PROP("capabilities","c");
#undef PROP
  /* Boolean properties... */
#define PROP(LK,DFLT) b = json_find_option_bool(LK,NULL,NULL,DFLT);     \
  if(DFLT!=b){ cson_object_set(u, LK, cson_value_new_bool(b ? 1 : 0)); } (void)0
  PROP("forceLogout",-1);
#undef PROP

#define PROP(LK,DFLT) i = json_find_option_int(LK,NULL,NULL,DFLT);   \
  if(DFLT != i){ cson_object_set(u, LK, cson_value_new_integer(i)); } (void)0
  PROP("uid",-99);
#undef PROP

Changes to src/json_wiki.c.

456
457
458
459
460
461
462
463

464
465
466
467
468
469
470
471

  if( !g.perm.RdWiki && !g.perm.Read ){
    json_set_err(FSL_JSON_E_DENIED,
                 "Requires 'j' or 'o' permissions.");
    return NULL;
  }
  blob_append(&sql,"SELECT"
              " substr(tagname,6) as name"

              " FROM tag WHERE tagname GLOB 'wiki-*'",
              -1);
  zGlob = json_find_option_cstr("glob",NULL,"g");
  if(zGlob && *zGlob){
    blob_append_sql(&sql," AND name %s GLOB %Q",
                    fInvert ? "NOT" : "", zGlob);
  }else{
    zGlob = json_find_option_cstr("like",NULL,"l");







|
>
|







456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

  if( !g.perm.RdWiki && !g.perm.Read ){
    json_set_err(FSL_JSON_E_DENIED,
                 "Requires 'j' or 'o' permissions.");
    return NULL;
  }
  blob_append(&sql,"SELECT"
              " DISTINCT substr(tagname,6) as name"
              " FROM tag JOIN tagxref USING('tagid')"
              " WHERE tagname GLOB 'wiki-*'",
              -1);
  zGlob = json_find_option_cstr("glob",NULL,"g");
  if(zGlob && *zGlob){
    blob_append_sql(&sql," AND name %s GLOB %Q",
                    fInvert ? "NOT" : "", zGlob);
  }else{
    zGlob = json_find_option_cstr("like",NULL,"l");

Changes to src/login.c.

291
292
293
294
295
296
297

298
299
300

301
302
303
304
305
306
307
...
354
355
356
357
358
359
360

361
362
363
364

365
366
367
368
369
370
371
...
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
...
833
834
835
836
837
838
839

840
841
842
843
844
845

846
847
848
849
850
851
852
....
1617
1618
1619
1620
1621
1622
1623

1624

1625
1626
1627
1628
1629
1630
1631
....
1830
1831
1832
1833
1834
1835
1836

1837
1838
1839
1840

1841
1842
1843
1844
1845
1846
1847
....
1968
1969
1970
1971
1972
1973
1974

1975
1976
1977
1978
1979
1980
1981
....
1991
1992
1993
1994
1995
1996
1997

1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008

2009

2010
2011
2012
2013
2014
2015
2016
....
2023
2024
2025
2026
2027
2028
2029

2030
2031
2032
2033
2034
2035
2036

2037
2038
2039
2040
2041
2042
2043
      "   AND length(cookie)>30",
      uid);
  if( zHash==0 ) zHash = db_text(0, "SELECT hex(randomblob(25))");
  zCookie = login_gen_user_cookie_value(zUsername, zHash);
  cgi_set_cookie(zCookieName, zCookie, login_cookie_path(),
                 bSessionCookie ? 0 : expires);
  record_login_attempt(zUsername, zIpAddr, 1);

  db_multi_exec("UPDATE user SET cookie=%Q,"
                "  cexpire=julianday('now')+%d/86400.0 WHERE uid=%d",
                zHash, expires, uid);

  fossil_free(zHash);
  if( zDest ){
    *zDest = zCookie;
  }else{
    free(zCookie);
  }
}
................................................................................
  if(!g.userUid){
    return;
  }else{
    const char *cookie = login_cookie_name();
    /* To logout, change the cookie value to an empty string */
    cgi_set_cookie(cookie, "",
                   login_cookie_path(), -86400);

    db_multi_exec("UPDATE user SET cookie=NULL, ipaddr=NULL, "
                  "  cexpire=0 WHERE uid=%d"
                  "  AND login NOT IN ('anonymous','nobody',"
                  "  'developer','reader')", g.userUid);

    cgi_replace_parameter(cookie, NULL);
    cgi_replace_parameter("anon", NULL);
  }
}

/*
** Return true if the prefix of zStr matches zPattern.  Return false if
................................................................................
           @ Your password is unchanged.
           @ </span></p>
        ;
      }else{
        char *zNewPw = sha1_shared_secret(zNew1, g.zLogin, 0);
        char *zChngPw;
        char *zErr;



        db_multi_exec(
           "UPDATE user SET pw=%Q WHERE uid=%d", zNewPw, g.userUid
        );
        fossil_free(zNewPw);
        zChngPw = mprintf(
           "UPDATE user"
           "   SET pw=shared_secret(%Q,%Q,"
           "        (SELECT value FROM config WHERE name='project-code'))"
           " WHERE login=%Q",
           zNew1, g.zLogin, g.zLogin
        );

        if( login_group_sql(zChngPw, "<p>", "</p>\n", &zErr) ){


          zErrMsg = mprintf("<span class=\"loginError\">%s</span>", zErr);
          fossil_free(zErr);
        }else{
          redirect_to_g();
          return;
        }
      }
................................................................................
      "   AND cexpire>julianday('now')"
      "   AND constant_time_cmp(cookie,%Q)=0",
      zLogin, zHash
    );
    pStmt = 0;
    rc = sqlite3_prepare_v2(pOther, zSQL, -1, &pStmt, 0);
    if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){

      db_multi_exec(
        "UPDATE user SET cookie=%Q, cexpire=%.17g"
        " WHERE login=%Q",
        zHash, 
        sqlite3_column_double(pStmt, 0), zLogin
      );

      nXfer++;
    }
    sqlite3_finalize(pStmt);
  }
  sqlite3_close(pOther);
  fossil_free(zOtherRepo);
  return nXfer;
................................................................................
    blob_init(&sql, 0, 0);
    blob_append_sql(&sql,
       "INSERT INTO user(login,pw,cap,info,mtime)\n"
       "VALUES(%Q,%Q,%Q,"
       "'%q <%q>\nself-register from ip %q on '||datetime('now'),now())",
       zUserID, zPass, zStartPerms, zDName, zEAddr, g.zIpAddr);
    fossil_free(zPass);

    db_multi_exec("%s", blob_sql_text(&sql));

    uid = db_int(0, "SELECT uid FROM user WHERE login=%Q", zUserID);
    login_set_user_cookie(zUserID, uid, NULL, 0);
    if( doAlerts ){
      /* Also make the new user a subscriber. */
      Blob hdr, body;
      AlertSender *pSender;
      sqlite3_int64 id;   /* New subscriber Id */
................................................................................
    zSelfCode
  );
  while( db_step(&q)==SQLITE_ROW ){
    const char *zRepoName = db_column_text(&q, 1);
    if( file_size(zRepoName, ExtFILE)<0 ){
      /* Silently remove non-existent repositories from the login group. */
      const char *zLabel = db_column_text(&q, 0);

      db_multi_exec(
         "DELETE FROM config WHERE name GLOB 'peer-*-%q'",
         &zLabel[10]
      );

      continue;
    }
    rc = sqlite3_open_v2(
         zRepoName, &pPeer,
         SQLITE_OPEN_READWRITE,
         g.zVfsName
    );
................................................................................

  /* Create all the necessary CONFIG table entries on both the
  ** other repository and on our own repository.
  */
  zSelfProjCode = abbreviated_project_code(zSelfProjCode);
  zOtherProjCode = abbreviated_project_code(zOtherProjCode);
  db_begin_transaction();

  db_multi_exec(
    "DELETE FROM \"%w\".config WHERE name GLOB 'peer-*';"
    "INSERT INTO \"%w\".config(name,value) VALUES('peer-repo-%q',%Q);"
    "INSERT INTO \"%w\".config(name,value) "
    "  SELECT 'peer-name-%q', value FROM other.config"
    "   WHERE name='project-name';",
    zSelf,
................................................................................
  );
  db_multi_exec(
    "REPLACE INTO \"%w\".config(name,value)"
    "  SELECT name, value FROM other.config"
    "   WHERE name GLOB 'peer-*' OR name GLOB 'login-group-*'",
    zSelf
  );

  db_end_transaction(0);
  db_multi_exec("DETACH other");

  /* Propagate the changes to all other members of the login-group */
  zSql = mprintf(
    "BEGIN;"
    "REPLACE INTO config(name,value,mtime) VALUES('peer-name-%q',%Q,now());"
    "REPLACE INTO config(name,value,mtime) VALUES('peer-repo-%q',%Q,now());"
    "COMMIT;",
    zSelfProjCode, zSelfLabel, zSelfProjCode, zSelfRepo
  );

  login_group_sql(zSql, "<li> ", "</li>", pzErrMsg);

  fossil_free(zSql);
}

/*
** Leave the login group that we are currently part of.
*/
void login_group_leave(char **pzErrMsg){
................................................................................
    "DELETE FROM config WHERE name GLOB 'peer-*-%q';"
    "DELETE FROM config"
    " WHERE name='login-group-name'"
    "   AND (SELECT count(*) FROM config WHERE name GLOB 'peer-*')==0;",
    zProjCode
  );
  fossil_free(zProjCode);

  login_group_sql(zSql, "<li> ", "</li>", pzErrMsg);
  fossil_free(zSql);
  db_multi_exec(
    "DELETE FROM config "
    " WHERE name GLOB 'peer-*'"
    "    OR name GLOB 'login-group-*';"
  );

}

/*
** COMMAND: login-group*
**
** Usage: %fossil login-group
**    or: %fossil login-group join REPO [-name NAME]







>



>







 







>




>







 







>
>
>



<







>
|
>
>







 







>






>







 







>

>







 







>




>







 







>







 







>











>

>







 







>







>







291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
...
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
...
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
...
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
....
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
....
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
....
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
....
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
....
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
      "   AND length(cookie)>30",
      uid);
  if( zHash==0 ) zHash = db_text(0, "SELECT hex(randomblob(25))");
  zCookie = login_gen_user_cookie_value(zUsername, zHash);
  cgi_set_cookie(zCookieName, zCookie, login_cookie_path(),
                 bSessionCookie ? 0 : expires);
  record_login_attempt(zUsername, zIpAddr, 1);
  db_unprotect(PROTECT_USER);
  db_multi_exec("UPDATE user SET cookie=%Q,"
                "  cexpire=julianday('now')+%d/86400.0 WHERE uid=%d",
                zHash, expires, uid);
  db_protect_pop();
  fossil_free(zHash);
  if( zDest ){
    *zDest = zCookie;
  }else{
    free(zCookie);
  }
}
................................................................................
  if(!g.userUid){
    return;
  }else{
    const char *cookie = login_cookie_name();
    /* To logout, change the cookie value to an empty string */
    cgi_set_cookie(cookie, "",
                   login_cookie_path(), -86400);
    db_unprotect(PROTECT_USER);
    db_multi_exec("UPDATE user SET cookie=NULL, ipaddr=NULL, "
                  "  cexpire=0 WHERE uid=%d"
                  "  AND login NOT IN ('anonymous','nobody',"
                  "  'developer','reader')", g.userUid);
    db_protect_pop();
    cgi_replace_parameter(cookie, NULL);
    cgi_replace_parameter("anon", NULL);
  }
}

/*
** Return true if the prefix of zStr matches zPattern.  Return false if
................................................................................
           @ Your password is unchanged.
           @ </span></p>
        ;
      }else{
        char *zNewPw = sha1_shared_secret(zNew1, g.zLogin, 0);
        char *zChngPw;
        char *zErr;
        int rc;

        db_unprotect(PROTECT_USER);
        db_multi_exec(
           "UPDATE user SET pw=%Q WHERE uid=%d", zNewPw, g.userUid
        );

        zChngPw = mprintf(
           "UPDATE user"
           "   SET pw=shared_secret(%Q,%Q,"
           "        (SELECT value FROM config WHERE name='project-code'))"
           " WHERE login=%Q",
           zNew1, g.zLogin, g.zLogin
        );
        fossil_free(zNewPw);
        rc = login_group_sql(zChngPw, "<p>", "</p>\n", &zErr);
        db_protect_pop();
        if( rc ){
          zErrMsg = mprintf("<span class=\"loginError\">%s</span>", zErr);
          fossil_free(zErr);
        }else{
          redirect_to_g();
          return;
        }
      }
................................................................................
      "   AND cexpire>julianday('now')"
      "   AND constant_time_cmp(cookie,%Q)=0",
      zLogin, zHash
    );
    pStmt = 0;
    rc = sqlite3_prepare_v2(pOther, zSQL, -1, &pStmt, 0);
    if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
      db_unprotect(PROTECT_USER);
      db_multi_exec(
        "UPDATE user SET cookie=%Q, cexpire=%.17g"
        " WHERE login=%Q",
        zHash, 
        sqlite3_column_double(pStmt, 0), zLogin
      );
      db_protect_pop();
      nXfer++;
    }
    sqlite3_finalize(pStmt);
  }
  sqlite3_close(pOther);
  fossil_free(zOtherRepo);
  return nXfer;
................................................................................
    blob_init(&sql, 0, 0);
    blob_append_sql(&sql,
       "INSERT INTO user(login,pw,cap,info,mtime)\n"
       "VALUES(%Q,%Q,%Q,"
       "'%q <%q>\nself-register from ip %q on '||datetime('now'),now())",
       zUserID, zPass, zStartPerms, zDName, zEAddr, g.zIpAddr);
    fossil_free(zPass);
    db_unprotect(PROTECT_USER);
    db_multi_exec("%s", blob_sql_text(&sql));
    db_protect_pop();
    uid = db_int(0, "SELECT uid FROM user WHERE login=%Q", zUserID);
    login_set_user_cookie(zUserID, uid, NULL, 0);
    if( doAlerts ){
      /* Also make the new user a subscriber. */
      Blob hdr, body;
      AlertSender *pSender;
      sqlite3_int64 id;   /* New subscriber Id */
................................................................................
    zSelfCode
  );
  while( db_step(&q)==SQLITE_ROW ){
    const char *zRepoName = db_column_text(&q, 1);
    if( file_size(zRepoName, ExtFILE)<0 ){
      /* Silently remove non-existent repositories from the login group. */
      const char *zLabel = db_column_text(&q, 0);
      db_unprotect(PROTECT_CONFIG);
      db_multi_exec(
         "DELETE FROM config WHERE name GLOB 'peer-*-%q'",
         &zLabel[10]
      );
      db_protect_pop();
      continue;
    }
    rc = sqlite3_open_v2(
         zRepoName, &pPeer,
         SQLITE_OPEN_READWRITE,
         g.zVfsName
    );
................................................................................

  /* Create all the necessary CONFIG table entries on both the
  ** other repository and on our own repository.
  */
  zSelfProjCode = abbreviated_project_code(zSelfProjCode);
  zOtherProjCode = abbreviated_project_code(zOtherProjCode);
  db_begin_transaction();
  db_unprotect(PROTECT_CONFIG);
  db_multi_exec(
    "DELETE FROM \"%w\".config WHERE name GLOB 'peer-*';"
    "INSERT INTO \"%w\".config(name,value) VALUES('peer-repo-%q',%Q);"
    "INSERT INTO \"%w\".config(name,value) "
    "  SELECT 'peer-name-%q', value FROM other.config"
    "   WHERE name='project-name';",
    zSelf,
................................................................................
  );
  db_multi_exec(
    "REPLACE INTO \"%w\".config(name,value)"
    "  SELECT name, value FROM other.config"
    "   WHERE name GLOB 'peer-*' OR name GLOB 'login-group-*'",
    zSelf
  );
  db_protect_pop();
  db_end_transaction(0);
  db_multi_exec("DETACH other");

  /* Propagate the changes to all other members of the login-group */
  zSql = mprintf(
    "BEGIN;"
    "REPLACE INTO config(name,value,mtime) VALUES('peer-name-%q',%Q,now());"
    "REPLACE INTO config(name,value,mtime) VALUES('peer-repo-%q',%Q,now());"
    "COMMIT;",
    zSelfProjCode, zSelfLabel, zSelfProjCode, zSelfRepo
  );
  db_unprotect(PROTECT_CONFIG);
  login_group_sql(zSql, "<li> ", "</li>", pzErrMsg);
  db_protect_pop();
  fossil_free(zSql);
}

/*
** Leave the login group that we are currently part of.
*/
void login_group_leave(char **pzErrMsg){
................................................................................
    "DELETE FROM config WHERE name GLOB 'peer-*-%q';"
    "DELETE FROM config"
    " WHERE name='login-group-name'"
    "   AND (SELECT count(*) FROM config WHERE name GLOB 'peer-*')==0;",
    zProjCode
  );
  fossil_free(zProjCode);
  db_unprotect(PROTECT_CONFIG);
  login_group_sql(zSql, "<li> ", "</li>", pzErrMsg);
  fossil_free(zSql);
  db_multi_exec(
    "DELETE FROM config "
    " WHERE name GLOB 'peer-*'"
    "    OR name GLOB 'login-group-*';"
  );
  db_protect_pop();
}

/*
** COMMAND: login-group*
**
** Usage: %fossil login-group
**    or: %fossil login-group join REPO [-name NAME]

Changes to src/lookslike.c.

398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

/*
** COMMAND: test-looks-like-utf
**
** Usage:  %fossil test-looks-like-utf FILENAME
**
** Options:
**    -n|--limit <num> Repeat looks-like function <num> times, for
**                     performance measurement. Default = 1;
**    --utf8           Ignoring BOM and file size, force UTF-8 checking
**    --utf16          Ignoring BOM and file size, force UTF-16 checking
**
** FILENAME is the name of a file to check for textual content in the UTF-8
** and/or UTF-16 encodings.
*/







|







398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

/*
** COMMAND: test-looks-like-utf
**
** Usage:  %fossil test-looks-like-utf FILENAME
**
** Options:
**    -n|--limit N     Repeat looks-like function N times, for
**                     performance measurement. Default = 1;
**    --utf8           Ignoring BOM and file size, force UTF-8 checking
**    --utf16          Ignoring BOM and file size, force UTF-16 checking
**
** FILENAME is the name of a file to check for textual content in the UTF-8
** and/or UTF-16 encodings.
*/

Changes to src/main.c.

1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
....
1373
1374
1375
1376
1377
1378
1379

1380
1381
1382
1383
1384
1385
1386
1387
1388

1389
1390
1391
1392
1393
1394
1395
....
1798
1799
1800
1801
1802
1803
1804

1805
1806
1807
1808
1809
1810
1811
....
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
....
2635
2636
2637
2638
2639
2640
2641

2642
2643
2644
2645
2646
2647
2648
  blob_append(pOut, "UNICODE_COMMAND_LINE\n", -1);
#endif
#if defined(FOSSIL_DYNAMIC_BUILD)
  blob_append(pOut, "FOSSIL_DYNAMIC_BUILD\n", -1);
#else
  blob_append(pOut, "FOSSIL_STATIC_BUILD\n", -1);
#endif
#if defined(FOSSIL_LEGACY_ALLOW_SYMLINKS)
  blob_append(pOut, "FOSSIL_LEGACY_ALLOW_SYMLINKS\n", -1);
#endif
#if defined(HAVE_PLEDGE)
  blob_append(pOut, "HAVE_PLEDGE\n", -1);
#endif
#if defined(USE_MMAN_H)
  blob_append(pOut, "USE_MMAN_H\n", -1);
#endif
#if defined(USE_SEE)
................................................................................
    }else{
      g.zBaseURL = mprintf("http://%s%.*s", zHost, i, zCur);
      g.zTop = &g.zBaseURL[7+strlen(zHost)];
      g.zHttpsURL = mprintf("https://%s%.*s", zHost, i, zCur);
    }
  }
  if( db_is_writeable("repository") ){

    if( !db_exists("SELECT 1 FROM config WHERE name='baseurl:%q'", g.zBaseURL)){
      db_multi_exec("INSERT INTO config(name,value,mtime)"
                    "VALUES('baseurl:%q',1,now())", g.zBaseURL);
    }else{
      db_optional_sql("repository",
           "REPLACE INTO config(name,value,mtime)"
           "VALUES('baseurl:%q',1,now())", g.zBaseURL
      );
    }

  }
}

/*
** Send an HTTP redirect back to the designated Index Page.
*/
NORETURN void fossil_redirect_home(void){
................................................................................
    skin_use_draft(iSkin);
    zNewScript = mprintf("%T/draft%d", P("SCRIPT_NAME"), iSkin);
    if( g.zTop ) g.zTop = mprintf("%s/draft%d", g.zTop, iSkin);
    if( g.zBaseURL ) g.zBaseURL = mprintf("%s/draft%d", g.zBaseURL, iSkin);
    zPathInfo += 7;
    cgi_replace_parameter("PATH_INFO", zPathInfo);
    cgi_replace_parameter("SCRIPT_NAME", zNewScript);

  }

  /* If the content type is application/x-fossil or 
  ** application/x-fossil-debug, then a sync/push/pull/clone is
  ** desired, so default the PATH_INFO to /xfer
  */
  if( g.zContentType &&
................................................................................
**    redirect: REPO URL       Extract the "name" query parameter and search
**                             REPO for a check-in or ticket that matches the
**                             value of "name", then redirect to URL.  There
**                             can be multiple "redirect:" lines that are
**                             processed in order.  If the REPO is "*", then
**                             an unconditional redirect to URL is taken.
**
**     jsmode: VALUE           Specifies the delivery mode for JavaScript
**                             files. See the help text for the --jsmode
**                             flag of the http command.
**
** Most CGI files contain only a "repository:" line.  It is uncommon to
** use any other option.
**
** See also: [[http]], [[server]], [[winsrv]]
................................................................................
  fossil_binary_mode(g.httpOut);
  fossil_binary_mode(g.httpIn);
  g.zExtRoot = find_option("extroot",0,1);
  find_server_repository(2, 0);
  g.cgiOutput = 1;
  g.fNoHttpCompress = 1;
  g.fullHttpReply = 1;

  zIpAddr = cgi_ssh_remote_addr(0);
  if( zIpAddr && zIpAddr[0] ){
    g.fSshClient |= CGI_SSH_CLIENT;
    ssh_request_loop(zIpAddr, 0);
  }else{
    cgi_set_parameter("REMOTE_ADDR", "127.0.0.1");
    cgi_handle_http_request(0);







<
<
<







 







>









>







 







>







 







|







 







>







1225
1226
1227
1228
1229
1230
1231



1232
1233
1234
1235
1236
1237
1238
....
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
....
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
....
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
....
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
  blob_append(pOut, "UNICODE_COMMAND_LINE\n", -1);
#endif
#if defined(FOSSIL_DYNAMIC_BUILD)
  blob_append(pOut, "FOSSIL_DYNAMIC_BUILD\n", -1);
#else
  blob_append(pOut, "FOSSIL_STATIC_BUILD\n", -1);
#endif



#if defined(HAVE_PLEDGE)
  blob_append(pOut, "HAVE_PLEDGE\n", -1);
#endif
#if defined(USE_MMAN_H)
  blob_append(pOut, "USE_MMAN_H\n", -1);
#endif
#if defined(USE_SEE)
................................................................................
    }else{
      g.zBaseURL = mprintf("http://%s%.*s", zHost, i, zCur);
      g.zTop = &g.zBaseURL[7+strlen(zHost)];
      g.zHttpsURL = mprintf("https://%s%.*s", zHost, i, zCur);
    }
  }
  if( db_is_writeable("repository") ){
    db_unprotect(PROTECT_CONFIG);
    if( !db_exists("SELECT 1 FROM config WHERE name='baseurl:%q'", g.zBaseURL)){
      db_multi_exec("INSERT INTO config(name,value,mtime)"
                    "VALUES('baseurl:%q',1,now())", g.zBaseURL);
    }else{
      db_optional_sql("repository",
           "REPLACE INTO config(name,value,mtime)"
           "VALUES('baseurl:%q',1,now())", g.zBaseURL
      );
    }
    db_protect_pop();
  }
}

/*
** Send an HTTP redirect back to the designated Index Page.
*/
NORETURN void fossil_redirect_home(void){
................................................................................
    skin_use_draft(iSkin);
    zNewScript = mprintf("%T/draft%d", P("SCRIPT_NAME"), iSkin);
    if( g.zTop ) g.zTop = mprintf("%s/draft%d", g.zTop, iSkin);
    if( g.zBaseURL ) g.zBaseURL = mprintf("%s/draft%d", g.zBaseURL, iSkin);
    zPathInfo += 7;
    cgi_replace_parameter("PATH_INFO", zPathInfo);
    cgi_replace_parameter("SCRIPT_NAME", zNewScript);
    etag_cancel();
  }

  /* If the content type is application/x-fossil or 
  ** application/x-fossil-debug, then a sync/push/pull/clone is
  ** desired, so default the PATH_INFO to /xfer
  */
  if( g.zContentType &&
................................................................................
**    redirect: REPO URL       Extract the "name" query parameter and search
**                             REPO for a check-in or ticket that matches the
**                             value of "name", then redirect to URL.  There
**                             can be multiple "redirect:" lines that are
**                             processed in order.  If the REPO is "*", then
**                             an unconditional redirect to URL is taken.
**
**    jsmode: VALUE            Specifies the delivery mode for JavaScript
**                             files. See the help text for the --jsmode
**                             flag of the http command.
**
** Most CGI files contain only a "repository:" line.  It is uncommon to
** use any other option.
**
** See also: [[http]], [[server]], [[winsrv]]
................................................................................
  fossil_binary_mode(g.httpOut);
  fossil_binary_mode(g.httpIn);
  g.zExtRoot = find_option("extroot",0,1);
  find_server_repository(2, 0);
  g.cgiOutput = 1;
  g.fNoHttpCompress = 1;
  g.fullHttpReply = 1;
  g.sslNotAvailable = 1;  /* Avoid attempts to redirect */
  zIpAddr = cgi_ssh_remote_addr(0);
  if( zIpAddr && zIpAddr[0] ){
    g.fSshClient |= CGI_SSH_CLIENT;
    ssh_request_loop(zIpAddr, 0);
  }else{
    cgi_set_parameter("REMOTE_ADDR", "127.0.0.1");
    cgi_handle_http_request(0);

Changes to src/main.mk.

71
72
73
74
75
76
77

78
79
80
81
82
83
84
...
101
102
103
104
105
106
107


108
109
110
111
112
113
114
...
221
222
223
224
225
226
227

228
229

230
231


232


233
234
235
236
237
238
239
...
320
321
322
323
324
325
326

327
328
329
330
331
332
333
...
350
351
352
353
354
355
356


357
358
359
360
361
362
363
...
465
466
467
468
469
470
471

472
473
474
475
476
477
478
...
495
496
497
498
499
500
501


502
503
504
505
506
507
508
...
800
801
802
803
804
805
806

807
808
809
810
811
812
813
...
830
831
832
833
834
835
836


837
838
839
840
841
842
843
....
1362
1363
1364
1365
1366
1367
1368








1369
1370
1371
1372
1373
1374
1375
....
1602
1603
1604
1605
1606
1607
1608
















1609
1610
1611
1612
1613
1614
1615
  $(SRCDIR)/hook.c \
  $(SRCDIR)/http.c \
  $(SRCDIR)/http_socket.c \
  $(SRCDIR)/http_ssl.c \
  $(SRCDIR)/http_transport.c \
  $(SRCDIR)/import.c \
  $(SRCDIR)/info.c \

  $(SRCDIR)/json.c \
  $(SRCDIR)/json_artifact.c \
  $(SRCDIR)/json_branch.c \
  $(SRCDIR)/json_config.c \
  $(SRCDIR)/json_diff.c \
  $(SRCDIR)/json_dir.c \
  $(SRCDIR)/json_finfo.c \
................................................................................
  $(SRCDIR)/md5.c \
  $(SRCDIR)/merge.c \
  $(SRCDIR)/merge3.c \
  $(SRCDIR)/moderate.c \
  $(SRCDIR)/name.c \
  $(SRCDIR)/path.c \
  $(SRCDIR)/piechart.c \


  $(SRCDIR)/pivot.c \
  $(SRCDIR)/popen.c \
  $(SRCDIR)/pqueue.c \
  $(SRCDIR)/printf.c \
  $(SRCDIR)/publish.c \
  $(SRCDIR)/purge.c \
  $(SRCDIR)/rebuild.c \
................................................................................
  $(SRCDIR)/ci_edit.js \
  $(SRCDIR)/copybtn.js \
  $(SRCDIR)/default.css \
  $(SRCDIR)/diff.tcl \
  $(SRCDIR)/forum.js \
  $(SRCDIR)/fossil.bootstrap.js \
  $(SRCDIR)/fossil.confirmer.js \

  $(SRCDIR)/fossil.dom.js \
  $(SRCDIR)/fossil.fetch.js \

  $(SRCDIR)/fossil.page.fileedit.js \
  $(SRCDIR)/fossil.page.forumpost.js \


  $(SRCDIR)/fossil.page.wikiedit.js \


  $(SRCDIR)/fossil.storage.js \
  $(SRCDIR)/fossil.tabs.js \
  $(SRCDIR)/graph.js \
  $(SRCDIR)/href.js \
  $(SRCDIR)/login.js \
  $(SRCDIR)/markdown.md \
  $(SRCDIR)/menu.js \
................................................................................
  $(OBJDIR)/hook_.c \
  $(OBJDIR)/http_.c \
  $(OBJDIR)/http_socket_.c \
  $(OBJDIR)/http_ssl_.c \
  $(OBJDIR)/http_transport_.c \
  $(OBJDIR)/import_.c \
  $(OBJDIR)/info_.c \

  $(OBJDIR)/json_.c \
  $(OBJDIR)/json_artifact_.c \
  $(OBJDIR)/json_branch_.c \
  $(OBJDIR)/json_config_.c \
  $(OBJDIR)/json_diff_.c \
  $(OBJDIR)/json_dir_.c \
  $(OBJDIR)/json_finfo_.c \
................................................................................
  $(OBJDIR)/md5_.c \
  $(OBJDIR)/merge_.c \
  $(OBJDIR)/merge3_.c \
  $(OBJDIR)/moderate_.c \
  $(OBJDIR)/name_.c \
  $(OBJDIR)/path_.c \
  $(OBJDIR)/piechart_.c \


  $(OBJDIR)/pivot_.c \
  $(OBJDIR)/popen_.c \
  $(OBJDIR)/pqueue_.c \
  $(OBJDIR)/printf_.c \
  $(OBJDIR)/publish_.c \
  $(OBJDIR)/purge_.c \
  $(OBJDIR)/rebuild_.c \
................................................................................
 $(OBJDIR)/hook.o \
 $(OBJDIR)/http.o \
 $(OBJDIR)/http_socket.o \
 $(OBJDIR)/http_ssl.o \
 $(OBJDIR)/http_transport.o \
 $(OBJDIR)/import.o \
 $(OBJDIR)/info.o \

 $(OBJDIR)/json.o \
 $(OBJDIR)/json_artifact.o \
 $(OBJDIR)/json_branch.o \
 $(OBJDIR)/json_config.o \
 $(OBJDIR)/json_diff.o \
 $(OBJDIR)/json_dir.o \
 $(OBJDIR)/json_finfo.o \
................................................................................
 $(OBJDIR)/md5.o \
 $(OBJDIR)/merge.o \
 $(OBJDIR)/merge3.o \
 $(OBJDIR)/moderate.o \
 $(OBJDIR)/name.o \
 $(OBJDIR)/path.o \
 $(OBJDIR)/piechart.o \


 $(OBJDIR)/pivot.o \
 $(OBJDIR)/popen.o \
 $(OBJDIR)/pqueue.o \
 $(OBJDIR)/printf.o \
 $(OBJDIR)/publish.o \
 $(OBJDIR)/purge.o \
 $(OBJDIR)/rebuild.o \
................................................................................
	$(OBJDIR)/hook_.c:$(OBJDIR)/hook.h \
	$(OBJDIR)/http_.c:$(OBJDIR)/http.h \
	$(OBJDIR)/http_socket_.c:$(OBJDIR)/http_socket.h \
	$(OBJDIR)/http_ssl_.c:$(OBJDIR)/http_ssl.h \
	$(OBJDIR)/http_transport_.c:$(OBJDIR)/http_transport.h \
	$(OBJDIR)/import_.c:$(OBJDIR)/import.h \
	$(OBJDIR)/info_.c:$(OBJDIR)/info.h \

	$(OBJDIR)/json_.c:$(OBJDIR)/json.h \
	$(OBJDIR)/json_artifact_.c:$(OBJDIR)/json_artifact.h \
	$(OBJDIR)/json_branch_.c:$(OBJDIR)/json_branch.h \
	$(OBJDIR)/json_config_.c:$(OBJDIR)/json_config.h \
	$(OBJDIR)/json_diff_.c:$(OBJDIR)/json_diff.h \
	$(OBJDIR)/json_dir_.c:$(OBJDIR)/json_dir.h \
	$(OBJDIR)/json_finfo_.c:$(OBJDIR)/json_finfo.h \
................................................................................
	$(OBJDIR)/md5_.c:$(OBJDIR)/md5.h \
	$(OBJDIR)/merge_.c:$(OBJDIR)/merge.h \
	$(OBJDIR)/merge3_.c:$(OBJDIR)/merge3.h \
	$(OBJDIR)/moderate_.c:$(OBJDIR)/moderate.h \
	$(OBJDIR)/name_.c:$(OBJDIR)/name.h \
	$(OBJDIR)/path_.c:$(OBJDIR)/path.h \
	$(OBJDIR)/piechart_.c:$(OBJDIR)/piechart.h \


	$(OBJDIR)/pivot_.c:$(OBJDIR)/pivot.h \
	$(OBJDIR)/popen_.c:$(OBJDIR)/popen.h \
	$(OBJDIR)/pqueue_.c:$(OBJDIR)/pqueue.h \
	$(OBJDIR)/printf_.c:$(OBJDIR)/printf.h \
	$(OBJDIR)/publish_.c:$(OBJDIR)/publish.h \
	$(OBJDIR)/purge_.c:$(OBJDIR)/purge.h \
	$(OBJDIR)/rebuild_.c:$(OBJDIR)/rebuild.h \
................................................................................
$(OBJDIR)/info_.c:	$(SRCDIR)/info.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/info.c >$@

$(OBJDIR)/info.o:	$(OBJDIR)/info_.c $(OBJDIR)/info.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/info.o -c $(OBJDIR)/info_.c

$(OBJDIR)/info.h:	$(OBJDIR)/headers









$(OBJDIR)/json_.c:	$(SRCDIR)/json.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/json.c >$@

$(OBJDIR)/json.o:	$(OBJDIR)/json_.c $(OBJDIR)/json.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/json.o -c $(OBJDIR)/json_.c

................................................................................
$(OBJDIR)/piechart_.c:	$(SRCDIR)/piechart.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/piechart.c >$@

$(OBJDIR)/piechart.o:	$(OBJDIR)/piechart_.c $(OBJDIR)/piechart.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/piechart.o -c $(OBJDIR)/piechart_.c

$(OBJDIR)/piechart.h:	$(OBJDIR)/headers

















$(OBJDIR)/pivot_.c:	$(SRCDIR)/pivot.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/pivot.c >$@

$(OBJDIR)/pivot.o:	$(OBJDIR)/pivot_.c $(OBJDIR)/pivot.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/pivot.o -c $(OBJDIR)/pivot_.c








>







 







>
>







 







>


>


>
>

>
>







 







>







 







>
>







 







>







 







>
>







 







>







 







>
>







 







>
>
>
>
>
>
>
>







 







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







71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
...
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
...
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
...
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
...
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
...
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
...
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
...
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
....
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
....
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
  $(SRCDIR)/hook.c \
  $(SRCDIR)/http.c \
  $(SRCDIR)/http_socket.c \
  $(SRCDIR)/http_ssl.c \
  $(SRCDIR)/http_transport.c \
  $(SRCDIR)/import.c \
  $(SRCDIR)/info.c \
  $(SRCDIR)/interwiki.c \
  $(SRCDIR)/json.c \
  $(SRCDIR)/json_artifact.c \
  $(SRCDIR)/json_branch.c \
  $(SRCDIR)/json_config.c \
  $(SRCDIR)/json_diff.c \
  $(SRCDIR)/json_dir.c \
  $(SRCDIR)/json_finfo.c \
................................................................................
  $(SRCDIR)/md5.c \
  $(SRCDIR)/merge.c \
  $(SRCDIR)/merge3.c \
  $(SRCDIR)/moderate.c \
  $(SRCDIR)/name.c \
  $(SRCDIR)/path.c \
  $(SRCDIR)/piechart.c \
  $(SRCDIR)/pikchr.c \
  $(SRCDIR)/pikchrshow.c \
  $(SRCDIR)/pivot.c \
  $(SRCDIR)/popen.c \
  $(SRCDIR)/pqueue.c \
  $(SRCDIR)/printf.c \
  $(SRCDIR)/publish.c \
  $(SRCDIR)/purge.c \
  $(SRCDIR)/rebuild.c \
................................................................................
  $(SRCDIR)/ci_edit.js \
  $(SRCDIR)/copybtn.js \
  $(SRCDIR)/default.css \
  $(SRCDIR)/diff.tcl \
  $(SRCDIR)/forum.js \
  $(SRCDIR)/fossil.bootstrap.js \
  $(SRCDIR)/fossil.confirmer.js \
  $(SRCDIR)/fossil.copybutton.js \
  $(SRCDIR)/fossil.dom.js \
  $(SRCDIR)/fossil.fetch.js \
  $(SRCDIR)/fossil.numbered-lines.js \
  $(SRCDIR)/fossil.page.fileedit.js \
  $(SRCDIR)/fossil.page.forumpost.js \
  $(SRCDIR)/fossil.page.pikchrshow.js \
  $(SRCDIR)/fossil.page.wikiedit-wysiwyg-legacy.js \
  $(SRCDIR)/fossil.page.wikiedit.js \
  $(SRCDIR)/fossil.pikchr.js \
  $(SRCDIR)/fossil.popupwidget.js \
  $(SRCDIR)/fossil.storage.js \
  $(SRCDIR)/fossil.tabs.js \
  $(SRCDIR)/graph.js \
  $(SRCDIR)/href.js \
  $(SRCDIR)/login.js \
  $(SRCDIR)/markdown.md \
  $(SRCDIR)/menu.js \
................................................................................
  $(OBJDIR)/hook_.c \
  $(OBJDIR)/http_.c \
  $(OBJDIR)/http_socket_.c \
  $(OBJDIR)/http_ssl_.c \
  $(OBJDIR)/http_transport_.c \
  $(OBJDIR)/import_.c \
  $(OBJDIR)/info_.c \
  $(OBJDIR)/interwiki_.c \
  $(OBJDIR)/json_.c \
  $(OBJDIR)/json_artifact_.c \
  $(OBJDIR)/json_branch_.c \
  $(OBJDIR)/json_config_.c \
  $(OBJDIR)/json_diff_.c \
  $(OBJDIR)/json_dir_.c \
  $(OBJDIR)/json_finfo_.c \
................................................................................
  $(OBJDIR)/md5_.c \
  $(OBJDIR)/merge_.c \
  $(OBJDIR)/merge3_.c \
  $(OBJDIR)/moderate_.c \
  $(OBJDIR)/name_.c \
  $(OBJDIR)/path_.c \
  $(OBJDIR)/piechart_.c \
  $(OBJDIR)/pikchr_.c \
  $(OBJDIR)/pikchrshow_.c \
  $(OBJDIR)/pivot_.c \
  $(OBJDIR)/popen_.c \
  $(OBJDIR)/pqueue_.c \
  $(OBJDIR)/printf_.c \
  $(OBJDIR)/publish_.c \
  $(OBJDIR)/purge_.c \
  $(OBJDIR)/rebuild_.c \
................................................................................
 $(OBJDIR)/hook.o \
 $(OBJDIR)/http.o \
 $(OBJDIR)/http_socket.o \
 $(OBJDIR)/http_ssl.o \
 $(OBJDIR)/http_transport.o \
 $(OBJDIR)/import.o \
 $(OBJDIR)/info.o \
 $(OBJDIR)/interwiki.o \
 $(OBJDIR)/json.o \
 $(OBJDIR)/json_artifact.o \
 $(OBJDIR)/json_branch.o \
 $(OBJDIR)/json_config.o \
 $(OBJDIR)/json_diff.o \
 $(OBJDIR)/json_dir.o \
 $(OBJDIR)/json_finfo.o \
................................................................................
 $(OBJDIR)/md5.o \
 $(OBJDIR)/merge.o \
 $(OBJDIR)/merge3.o \
 $(OBJDIR)/moderate.o \
 $(OBJDIR)/name.o \
 $(OBJDIR)/path.o \
 $(OBJDIR)/piechart.o \
 $(OBJDIR)/pikchr.o \
 $(OBJDIR)/pikchrshow.o \
 $(OBJDIR)/pivot.o \
 $(OBJDIR)/popen.o \
 $(OBJDIR)/pqueue.o \
 $(OBJDIR)/printf.o \
 $(OBJDIR)/publish.o \
 $(OBJDIR)/purge.o \
 $(OBJDIR)/rebuild.o \
................................................................................
	$(OBJDIR)/hook_.c:$(OBJDIR)/hook.h \
	$(OBJDIR)/http_.c:$(OBJDIR)/http.h \
	$(OBJDIR)/http_socket_.c:$(OBJDIR)/http_socket.h \
	$(OBJDIR)/http_ssl_.c:$(OBJDIR)/http_ssl.h \
	$(OBJDIR)/http_transport_.c:$(OBJDIR)/http_transport.h \
	$(OBJDIR)/import_.c:$(OBJDIR)/import.h \
	$(OBJDIR)/info_.c:$(OBJDIR)/info.h \
	$(OBJDIR)/interwiki_.c:$(OBJDIR)/interwiki.h \
	$(OBJDIR)/json_.c:$(OBJDIR)/json.h \
	$(OBJDIR)/json_artifact_.c:$(OBJDIR)/json_artifact.h \
	$(OBJDIR)/json_branch_.c:$(OBJDIR)/json_branch.h \
	$(OBJDIR)/json_config_.c:$(OBJDIR)/json_config.h \
	$(OBJDIR)/json_diff_.c:$(OBJDIR)/json_diff.h \
	$(OBJDIR)/json_dir_.c:$(OBJDIR)/json_dir.h \
	$(OBJDIR)/json_finfo_.c:$(OBJDIR)/json_finfo.h \
................................................................................
	$(OBJDIR)/md5_.c:$(OBJDIR)/md5.h \
	$(OBJDIR)/merge_.c:$(OBJDIR)/merge.h \
	$(OBJDIR)/merge3_.c:$(OBJDIR)/merge3.h \
	$(OBJDIR)/moderate_.c:$(OBJDIR)/moderate.h \
	$(OBJDIR)/name_.c:$(OBJDIR)/name.h \
	$(OBJDIR)/path_.c:$(OBJDIR)/path.h \
	$(OBJDIR)/piechart_.c:$(OBJDIR)/piechart.h \
	$(OBJDIR)/pikchr_.c:$(OBJDIR)/pikchr.h \
	$(OBJDIR)/pikchrshow_.c:$(OBJDIR)/pikchrshow.h \
	$(OBJDIR)/pivot_.c:$(OBJDIR)/pivot.h \
	$(OBJDIR)/popen_.c:$(OBJDIR)/popen.h \
	$(OBJDIR)/pqueue_.c:$(OBJDIR)/pqueue.h \
	$(OBJDIR)/printf_.c:$(OBJDIR)/printf.h \
	$(OBJDIR)/publish_.c:$(OBJDIR)/publish.h \
	$(OBJDIR)/purge_.c:$(OBJDIR)/purge.h \
	$(OBJDIR)/rebuild_.c:$(OBJDIR)/rebuild.h \
................................................................................
$(OBJDIR)/info_.c:	$(SRCDIR)/info.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/info.c >$@

$(OBJDIR)/info.o:	$(OBJDIR)/info_.c $(OBJDIR)/info.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/info.o -c $(OBJDIR)/info_.c

$(OBJDIR)/info.h:	$(OBJDIR)/headers

$(OBJDIR)/interwiki_.c:	$(SRCDIR)/interwiki.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/interwiki.c >$@

$(OBJDIR)/interwiki.o:	$(OBJDIR)/interwiki_.c $(OBJDIR)/interwiki.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/interwiki.o -c $(OBJDIR)/interwiki_.c

$(OBJDIR)/interwiki.h:	$(OBJDIR)/headers

$(OBJDIR)/json_.c:	$(SRCDIR)/json.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/json.c >$@

$(OBJDIR)/json.o:	$(OBJDIR)/json_.c $(OBJDIR)/json.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/json.o -c $(OBJDIR)/json_.c

................................................................................
$(OBJDIR)/piechart_.c:	$(SRCDIR)/piechart.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/piechart.c >$@

$(OBJDIR)/piechart.o:	$(OBJDIR)/piechart_.c $(OBJDIR)/piechart.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/piechart.o -c $(OBJDIR)/piechart_.c

$(OBJDIR)/piechart.h:	$(OBJDIR)/headers

$(OBJDIR)/pikchr_.c:	$(SRCDIR)/pikchr.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/pikchr.c >$@

$(OBJDIR)/pikchr.o:	$(OBJDIR)/pikchr_.c $(OBJDIR)/pikchr.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/pikchr.o -c $(OBJDIR)/pikchr_.c

$(OBJDIR)/pikchr.h:	$(OBJDIR)/headers

$(OBJDIR)/pikchrshow_.c:	$(SRCDIR)/pikchrshow.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/pikchrshow.c >$@

$(OBJDIR)/pikchrshow.o:	$(OBJDIR)/pikchrshow_.c $(OBJDIR)/pikchrshow.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/pikchrshow.o -c $(OBJDIR)/pikchrshow_.c

$(OBJDIR)/pikchrshow.h:	$(OBJDIR)/headers

$(OBJDIR)/pivot_.c:	$(SRCDIR)/pivot.c $(OBJDIR)/translate
	$(OBJDIR)/translate $(SRCDIR)/pivot.c >$@

$(OBJDIR)/pivot.o:	$(OBJDIR)/pivot_.c $(OBJDIR)/pivot.h $(SRCDIR)/config.h
	$(XTCC) -o $(OBJDIR)/pivot.o -c $(OBJDIR)/pivot_.c

Changes to src/makemake.tcl.

81
82
83
84
85
86
87

88
89
90
91
92
93
94
...
111
112
113
114
115
116
117


118
119
120
121
122
123
124
  hname
  hook
  http
  http_socket
  http_transport
  import
  info

  json
  json_artifact
  json_branch
  json_config
  json_diff
  json_dir
  json_finfo
................................................................................
  md5
  merge
  merge3
  moderate
  name
  path
  piechart


  pivot
  popen
  pqueue
  printf
  publish
  purge
  rebuild







>







 







>
>







81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
  hname
  hook
  http
  http_socket
  http_transport
  import
  info
  interwiki
  json
  json_artifact
  json_branch
  json_config
  json_diff
  json_dir
  json_finfo
................................................................................
  md5
  merge
  merge3
  moderate
  name
  path
  piechart
  pikchr
  pikchrshow
  pivot
  popen
  pqueue
  printf
  publish
  purge
  rebuild

Changes to src/manifest.c.

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
...
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
....
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
....
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832

1833
1834
1835
1836
1837
1838
1839
....
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065

2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
....
2678
2679
2680
2681
2682
2683
2684



2685
2686
2687
2688
2689
2690
2691
  if( z[-2]=='\r' && z[-3]=='\n' ) return 1;
  return 0;
}

/*
** Remove the PGP signature from the artifact, if there is one.
*/
static void remove_pgp_signature(char **pz, int *pn){
  char *z = *pz;
  int n = *pn;
  int i;
  if( strncmp(z, "-----BEGIN PGP SIGNED MESSAGE-----", 34)!=0 ) return;
  for(i=34; i<n && !after_blank_line(z+i); i++){}
  if( i>=n ) return;
  z += i;
  n -= i;
................................................................................
    blob_reset(pContent);
    blob_appendf(pErr, "%s", n ? "not terminated with \\n" : "zero-length");
    return 0;
  }

  /* Strip off the PGP signature if there is one.
  */
  remove_pgp_signature(&z, &n);

  /* Verify that the first few characters of the artifact look like
  ** a control artifact.
  */
  if( n<10 || z[0]<'A' || z[0]>'Z' || z[1]!=' ' ){
    blob_reset(pContent);
    blob_appendf(pErr, "line 1 not recognized");
................................................................................
  if( pRid ) *pRid = rid;
  p = manifest_get(rid, CFTYPE_MANIFEST, 0);
  if( p==0 ){
    fossil_fatal("cannot parse manifest for check-in: %s", zName);
  }
  return p;
}










































/*
** COMMAND: test-parse-manifest
**
** Usage: %fossil test-parse-manifest FILENAME ?N?
**
** Parse the manifest(s) given on the command-line and report any
................................................................................
** errors.  If the N argument is given, run the parsing N times.
*/
void manifest_test_parse_cmd(void){
  Manifest *p;
  Blob b;
  int i;
  int n = 1;

  db_find_and_open_repository(0,0);
  verify_all_options();
  if( g.argc!=3 && g.argc!=4 ){
    usage("FILENAME");
  }
  blob_read_from_file(&b, g.argv[2], ExtFILE);
  if( g.argc>3 ) n = atoi(g.argv[3]);



  for(i=0; i<n; i++){
    Blob b2;
    Blob err;
    blob_copy(&b2, &b);
    blob_zero(&err);
    p = manifest_parse(&b2, 0, &err);

    if( p==0 ) fossil_print("ERROR: %s\n", blob_str(&err));









    blob_reset(&err);
    manifest_destroy(p);
  }
  blob_reset(&b);
}

/*
** COMMAND: test-parse-all-blobs
**
** Usage: %fossil test-parse-all-blobs [--limit N]
**
** Parse all entries in the BLOB table that are believed to be non-data
** artifacts and report any errors.  Run this test command on historical
** repositories after making any changes to the manifest_parse()
** implementation to confirm that the changes did not break anything.
**
** If the --limit N argument is given, parse no more than N blobs







*/
void manifest_test_parse_all_blobs_cmd(void){
  Manifest *p;
  Blob err;
  Stmt q;
  int nTest = 0;
  int nErr = 0;
  int N = 1000000000;

  const char *z;
  db_find_and_open_repository(0, 0);
  z = find_option("limit", 0, 1);
  if( z ) N = atoi(z);

  verify_all_options();



  db_prepare(&q, "SELECT DISTINCT objid FROM EVENT");

  while( (N--)>0 && db_step(&q)==SQLITE_ROW ){
    int id = db_column_int(&q,0);
    fossil_print("Checking %d       \r", id);
    nTest++;
    fflush(stdout);
    blob_init(&err, 0, 0);

















    p = manifest_get(id, CFTYPE_ANY, &err);
    if( p==0 ){
      fossil_print("%d ERROR: %s\n", id, blob_str(&err));
      nErr++;

    }
    blob_reset(&err);
    manifest_destroy(p);
  }
  db_finalize(&q);
  fossil_print("%d tests with %d errors\n", nTest, nErr);
}
................................................................................
    if( nParent>mxParent ) goto reparent_abort;
    for(j=HNAME_MIN; z[j]>' '; j++){}
    if( !hname_validate(z, j) ) goto reparent_abort;
    if( z[j]==0 ) break;
    z[j] = 0;
    i += j;
  }
  if( !db_exists("SELECT 1 FROM plink WHERE cid=%d AND pid=%d",
                 rid, uuid_to_rid(azParent[0],0))
  ){
    p = manifest_get(rid, CFTYPE_MANIFEST, 0);
  }
  if( p!=0 ){
    db_multi_exec(
       "DELETE FROM plink WHERE cid=%d;"
       "DELETE FROM mlink WHERE mid=%d;",
       rid, rid
    );
    manifest_add_checkin_linkages(rid,p,nParent,azParent);
  }
  manifest_destroy(p);

reparent_abort:
  fossil_free(azParent);
  fossil_free(zCopy);
}

/*
** Setup to do multiple manifest_crosslink() calls.
................................................................................
** the project are imported into a different Fossil project, the manifest
** file will not be interpreted as a control artifact in that other project.
**
** Normally it is sufficient to simply append the extra line of text.
** However, if the manifest is PGP signed then the extra line has to be
** inserted before the PGP signature (thus invalidating the signature).
*/
void sterilize_manifest(Blob *p){
  char *z, *zOrig;
  int n, nOrig;
  static const char zExtraLine[] =
      "# Remove this line to create a well-formed manifest.\n";


  z = zOrig = blob_materialize(p);
  n = nOrig = blob_size(p);
  remove_pgp_signature(&z, &n);
  if( z==zOrig ){
    blob_append(p, zExtraLine, -1);
  }else{
    int iEnd;
    Blob copy;
    memcpy(&copy, p, sizeof(copy));
    blob_init(p, 0, 0);
    iEnd = (int)(&z[n] - zOrig);
    blob_append(p, zOrig, iEnd);
    blob_append(p, zExtraLine, -1);
    blob_append(p, &zOrig[iEnd], -1);
    blob_zero(&copy);
  }
}

/*
** This is the comparison function used to sort the tag array.
................................................................................
      db_multi_exec(
        "REPLACE INTO event(type,mtime,objid,user,comment)"
        "VALUES('f',%.17g,%d,%Q,'%q: %q')",
        p->rDate, rid, p->zUser, zFType, zTitle
      );
      fossil_free(zTitle);
    }



  }
  db_end_transaction(0);
  if( permitHooks ){
    rc = xfer_run_common_script();
    if( rc==TH_OK ){
      rc = xfer_run_script(zScript, zUuid, 0);
    }







|
|







 







|







 







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







 







>
|






>
>
>






>
|
>
>
>
>
>
>
>
>
>









|






|
>
>
>
>
>
>
>








>




>

>
>
>
|
>






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







 







<
<
<
|
<







<
|
>







 







|



|
>



|

|







|







 







>
>
>







287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
...
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
....
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
....
1898
1899
1900
1901
1902
1903
1904



1905

1906
1907
1908
1909
1910
1911
1912

1913
1914
1915
1916
1917
1918
1919
1920
1921
....
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
....
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
  if( z[-2]=='\r' && z[-3]=='\n' ) return 1;
  return 0;
}

/*
** Remove the PGP signature from the artifact, if there is one.
*/
static void remove_pgp_signature(const char **pz, int *pn){
  const char *z = *pz;
  int n = *pn;
  int i;
  if( strncmp(z, "-----BEGIN PGP SIGNED MESSAGE-----", 34)!=0 ) return;
  for(i=34; i<n && !after_blank_line(z+i); i++){}
  if( i>=n ) return;
  z += i;
  n -= i;
................................................................................
    blob_reset(pContent);
    blob_appendf(pErr, "%s", n ? "not terminated with \\n" : "zero-length");
    return 0;
  }

  /* Strip off the PGP signature if there is one.
  */
  remove_pgp_signature((const char**)&z, &n);

  /* Verify that the first few characters of the artifact look like
  ** a control artifact.
  */
  if( n<10 || z[0]<'A' || z[0]>'Z' || z[1]!=' ' ){
    blob_reset(pContent);
    blob_appendf(pErr, "line 1 not recognized");
................................................................................
  if( pRid ) *pRid = rid;
  p = manifest_get(rid, CFTYPE_MANIFEST, 0);
  if( p==0 ){
    fossil_fatal("cannot parse manifest for check-in: %s", zName);
  }
  return p;
}

/*
** The input blob is text that may or may not be a valid Fossil
** control artifact of some kind.  This routine returns true if
** the input is a well-formed control artifact and false if it
** is not.
**
** This routine is optimized to return false quickly and with minimal
** work in the common case where the input is some random file.
*/
int manifest_is_well_formed(const char *zIn, int nIn){
  int i;
  int iRes;
  Manifest *pManifest;
  Blob copy, errmsg;
  remove_pgp_signature(&zIn, &nIn);

  /* Check to see that the file begins with a "card" */
  if( nIn<3 ) return 0;
  if( zIn[0]<'A' || zIn[0]>'M' || zIn[1]!=' ' ) return 0;

  /* Check to see that the first card is followed by one more card */
  for(i=2; i<nIn && zIn[i]!='\n'; i++){}
  if( i>=nIn-3 ) return 0;
  i++;
  if( !fossil_isupper(zIn[i]) || zIn[i]<zIn[0] || zIn[i+1]!=' ' ) return 0;

  /* The checks above will eliminate most random inputs.  If these
  ** quick checks pass, then we could be dealing with a well-formed
  ** control artifact.  Make a copy, and run it through the official
  ** artifact parser.  This is the slow path, but it is rarely taken.
  */
  blob_init(&copy, 0, 0);
  blob_init(&errmsg, 0, 0);
  blob_append(&copy, zIn, nIn);
  pManifest = manifest_parse(&copy, 0, &errmsg);
  iRes = pManifest!=0;  
  manifest_destroy(pManifest);
  blob_reset(&errmsg);
  return iRes;
}

/*
** COMMAND: test-parse-manifest
**
** Usage: %fossil test-parse-manifest FILENAME ?N?
**
** Parse the manifest(s) given on the command-line and report any
................................................................................
** errors.  If the N argument is given, run the parsing N times.
*/
void manifest_test_parse_cmd(void){
  Manifest *p;
  Blob b;
  int i;
  int n = 1;
  int isWF;
  db_find_and_open_repository(OPEN_SUBSTITUTE|OPEN_OK_NOT_FOUND,0);
  verify_all_options();
  if( g.argc!=3 && g.argc!=4 ){
    usage("FILENAME");
  }
  blob_read_from_file(&b, g.argv[2], ExtFILE);
  if( g.argc>3 ) n = atoi(g.argv[3]);
  isWF = manifest_is_well_formed(blob_buffer(&b), blob_size(&b));
  fossil_print("manifest_is_well_formed() reports the input %s\n",
       isWF ? "is ok" : "contains errors");
  for(i=0; i<n; i++){
    Blob b2;
    Blob err;
    blob_copy(&b2, &b);
    blob_zero(&err);
    p = manifest_parse(&b2, 0, &err);
    if( p==0 ){
      fossil_print("ERROR: %s\n", blob_str(&err));
    }else if( i==0 || (n==2 && i==1) ){
      fossil_print("manifest_parse() worked\n");
    }else if( i==n-1 ){
      fossil_print("manifest_parse() worked %d more times\n", n-1);
    }
    if( (p==0 && isWF) || (p!=0 && !isWF) ){
      fossil_print("ERROR: manifest_is_well_formed() and "
                   "manifest_parse() disagree!\n");
    }
    blob_reset(&err);
    manifest_destroy(p);
  }
  blob_reset(&b);
}

/*
** COMMAND: test-parse-all-blobs
**
** Usage: %fossil test-parse-all-blobs ?OPTIONS?
**
** Parse all entries in the BLOB table that are believed to be non-data
** artifacts and report any errors.  Run this test command on historical
** repositories after making any changes to the manifest_parse()
** implementation to confirm that the changes did not break anything.
**
** Options:
**
**   --limit N            Parse no more than N artifacts before stopping.
**   --wellformed         Use all BLOB table entries as input, not just
**                        those entries that are believed to be valid
**                        artifacts, and verify that the result the
**                        manifest_is_well_formed() agrees with the
**                        result of manifest_parse().
*/
void manifest_test_parse_all_blobs_cmd(void){
  Manifest *p;
  Blob err;
  Stmt q;
  int nTest = 0;
  int nErr = 0;
  int N = 1000000000;
  int bWellFormed;
  const char *z;
  db_find_and_open_repository(0, 0);
  z = find_option("limit", 0, 1);
  if( z ) N = atoi(z);
  bWellFormed = find_option("wellformed",0,0)!=0;
  verify_all_options();
  if( bWellFormed ){
    db_prepare(&q, "SELECT rid FROM blob ORDER BY rid");
  }else{
    db_prepare(&q, "SELECT DISTINCT objid FROM EVENT ORDER BY objid");
  }
  while( (N--)>0 && db_step(&q)==SQLITE_ROW ){
    int id = db_column_int(&q,0);
    fossil_print("Checking %d       \r", id);
    nTest++;
    fflush(stdout);
    blob_init(&err, 0, 0);
    if( bWellFormed ){
      Blob content;
      int isWF;
      content_get(id, &content);
      isWF = manifest_is_well_formed(blob_buffer(&content),blob_size(&content));
      p = manifest_parse(&content, id, &err);
      if( isWF && p==0 ){
        fossil_print("%d ERROR: manifest_is_well_formed() reported true "
                     "but manifest_parse() reports an error: %s\n",
                     id, blob_str(&err));
        nErr++;
      }else if( !isWF && p!=0 ){
        fossil_print("%d ERROR: manifest_is_well_formed() reported false "
                     "but manifest_parse() found nothing wrong.\n", id);
        nErr++;
      }
    }else{            
      p = manifest_get(id, CFTYPE_ANY, &err);
      if( p==0 ){
        fossil_print("%d ERROR: %s\n", id, blob_str(&err));
        nErr++;
      }
    }
    blob_reset(&err);
    manifest_destroy(p);
  }
  db_finalize(&q);
  fossil_print("%d tests with %d errors\n", nTest, nErr);
}
................................................................................
    if( nParent>mxParent ) goto reparent_abort;
    for(j=HNAME_MIN; z[j]>' '; j++){}
    if( !hname_validate(z, j) ) goto reparent_abort;
    if( z[j]==0 ) break;
    z[j] = 0;
    i += j;
  }



  p = manifest_get(rid, CFTYPE_MANIFEST, 0);

  if( p!=0 ){
    db_multi_exec(
       "DELETE FROM plink WHERE cid=%d;"
       "DELETE FROM mlink WHERE mid=%d;",
       rid, rid
    );
    manifest_add_checkin_linkages(rid,p,nParent,azParent);

    manifest_destroy(p);
  }
reparent_abort:
  fossil_free(azParent);
  fossil_free(zCopy);
}

/*
** Setup to do multiple manifest_crosslink() calls.
................................................................................
** the project are imported into a different Fossil project, the manifest
** file will not be interpreted as a control artifact in that other project.
**
** Normally it is sufficient to simply append the extra line of text.
** However, if the manifest is PGP signed then the extra line has to be
** inserted before the PGP signature (thus invalidating the signature).
*/
void sterilize_manifest(Blob *p, int eType){
  char *z, *zOrig;
  int n, nOrig;
  static const char zExtraLine[] =
      "# Remove this line to create a well-formed Fossil %s.\n";
  const char *zType = eType==CFTYPE_MANIFEST ? "manifest" : "control artifact";

  z = zOrig = blob_materialize(p);
  n = nOrig = blob_size(p);
  remove_pgp_signature((const char **)&z, &n);
  if( z==zOrig ){
    blob_appendf(p, zExtraLine/*works-like:"%s"*/, zType);
  }else{
    int iEnd;
    Blob copy;
    memcpy(&copy, p, sizeof(copy));
    blob_init(p, 0, 0);
    iEnd = (int)(&z[n] - zOrig);
    blob_append(p, zOrig, iEnd);
    blob_appendf(p, zExtraLine/*works-like:"%s"*/, zType);
    blob_append(p, &zOrig[iEnd], -1);
    blob_zero(&copy);
  }
}

/*
** This is the comparison function used to sort the tag array.
................................................................................
      db_multi_exec(
        "REPLACE INTO event(type,mtime,objid,user,comment)"
        "VALUES('f',%.17g,%d,%Q,'%q: %q')",
        p->rDate, rid, p->zUser, zFType, zTitle
      );
      fossil_free(zTitle);
    }
    if( p->zWiki[0] ){
      backlink_extract(p->zWiki, p->zMimetype, rid, BKLNK_FORUM, p->rDate, 1);
    }
  }
  db_end_transaction(0);
  if( permitHooks ){
    rc = xfer_run_common_script();
    if( rc==TH_OK ){
      rc = xfer_run_script(zScript, zUuid, 0);
    }

Changes to src/markdown.c.

368
369
370
371
372
373
374




375
376
377
378
379
380
381
....
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
  /* a valid tag can't be shorter than 3 chars */
  if( size<3 ) return 0;

  /* begins with a '<' optionally followed by '/', followed by letter */
  if( data[0]!='<' ) return 0;
  i = (data[1]=='/') ? 2 : 1;
  if( (data[i]<'a' || data[i]>'z') &&  (data[i]<'A' || data[i]>'Z') ){




    return 0;
  }

  /* scheme test */
  *autolink = MKDA_NOT_AUTOLINK;
  if( size>6
   && fossil_strnicmp(data+1, "http", 4)==0
................................................................................
    /* (because it is only the optional end separator) */
    if( total && end<=beg ) continue;

    /* fallback on default alignment if not explicit */
    if( align==0 && aligns && col<align_size ) align = aligns[col];

    /* render cells */
    if( cells && end>beg ){
      parse_table_cell(cells, rndr, data+beg, end-beg, align|flags);
    }

    col++;
  }

  /* render the whole row and clean up */







>
>
>
>







 







|







368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
....
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
  /* a valid tag can't be shorter than 3 chars */
  if( size<3 ) return 0;

  /* begins with a '<' optionally followed by '/', followed by letter */
  if( data[0]!='<' ) return 0;
  i = (data[1]=='/') ? 2 : 1;
  if( (data[i]<'a' || data[i]>'z') &&  (data[i]<'A' || data[i]>'Z') ){
    if( data[1]=='!' && size>=7 && data[2]=='-' && data[3]=='-' ){
      for(i=6; i<size && (data[i]!='>'||data[i-1]!='-'|| data[i-2]!='-');i++){}
      if( i<size ) return i;
    }
    return 0;
  }

  /* scheme test */
  *autolink = MKDA_NOT_AUTOLINK;
  if( size>6
   && fossil_strnicmp(data+1, "http", 4)==0
................................................................................
    /* (because it is only the optional end separator) */
    if( total && end<=beg ) continue;

    /* fallback on default alignment if not explicit */
    if( align==0 && aligns && col<align_size ) align = aligns[col];

    /* render cells */
    if( cells && end>=beg ){
      parse_table_cell(cells, rndr, data+beg, end-beg, align|flags);
    }

    col++;
  }

  /* render the whole row and clean up */

Changes to src/markdown.md.

42
43
44
45
46
47
48
49
50
51
52
53

54
55
56
57
58
59
60
...
105
106
107
108
109
110
111
112

113
114
115

116
117
118
119
120
121
122
...
128
129
130
131
132
133
134
















135
136
137
138
139
140
141
...
150
151
152
153
154
155
156




> If **URL** begins with "http:", "https:', "ftp:' or "mailto:",
> it may optionally be written **\<URL\>** (format 4).
> Other **URL** formats include:
> <ul>
> <li>  A relative pathname.
> <li>  A pathname starting with "/" in which case the Fossil server
>      URL prefix is prepended
> <li>  A wiki page name, or a wiki page name preceded by "wiki:"
> <li> An artifact or ticket hash or hash prefix
> <li>  A date and time stamp: "YYYY-MM-DD HH:MM:SS" or a subset that
>      includes at least the day of the month.</ul>


> In format 8, then the URL becomes the display text.  This is useful for
> hyperlinks that refer to wiki pages and check-in and ticket hashes.

## Fonts ##

> *   _\*italic\*_
................................................................................
> 3. Surround the block by <tt>\`\`\`</tt> (three or more) or <tt>\~\~\~</tt> either at the
> left margin or indented no more than three spaces. The first word
> on that same line (if any) is used in a “`language-WORD`” CSS style in
> the HTML rendering of that code block and is intended for use by
> code syntax highlighters. Thus <tt>\`\`\`c</tt> would mark a block of code
> in the C programming language. Text to be rendered inside the code block
> should therefore start on the next line, not be cuddled up with the
> backticks or tildes.


> With the standard skins, verbatim text is rendered in a fixed-width font,
> but that is purely a presentation matter, controlled by the skin’s CSS.


## Tables ##

>
    | Header 1     | Header 2    | Header 3      |
    ----------------------------------------------
    | Row 1 Col 1  | Row 1 Col 2 | Row 1 Col 3   |
................................................................................

> Placing **:** at the left, both, or right sides of a cell gives left-aligned,
> centered, or right-aligned text, respectively.  By default, header cells are
> centered, and body cells are left-aligned.

> The leftmost or rightmost **\|** is required only if the first or last column,
> respectively, contains at least one blank cell.

















## Miscellaneous ##

> *   In-line images are made using **\!\[alt-text\]\(image-URL\)**.
> *   Use HTML for advanced formatting such as forms.
> *   **\<!--** HTML-style comments **-->** are supported.
> *   Escape special characters (ex: **\[** **\(** **\|** **\***)
................................................................................
> *  In hyperlinks, if the URL begins with **/** then the root of the Fossil
>    repository is prepended.  This allows for repository-relative hyperlinks.
> *  For documents that begin with a top-level heading (ex: **# heading #**),
>    the heading is omitted from the body of the document and becomes the
>    document title displayed at the top of the Fossil page.

[daringfireball.net]: http://daringfireball.net/projects/markdown/syntax










|

|

|
>







 







|
>



>







 







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







 







>
>
>
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
...
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
...
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
...
169
170
171
172
173
174
175
176
177
178

> If **URL** begins with "http:", "https:', "ftp:' or "mailto:",
> it may optionally be written **\<URL\>** (format 4).
> Other **URL** formats include:
> <ul>
> <li>  A relative pathname.
> <li>  A pathname starting with "/" in which case the Fossil server
>       URL prefix is prepended
> <li>  A wiki page name, or a wiki page name preceded by "wiki:"
> <li>  An artifact or ticket hash or hash prefix
> <li>  A date and time stamp: "YYYY-MM-DD HH:MM:SS" or a subset that
>       includes at least the day of the month.
> <li>  An [interwiki link](#intermap) of the form "<i>Tag</i><b>:</b><i>PageName</i>"</ul>

> In format 8, then the URL becomes the display text.  This is useful for
> hyperlinks that refer to wiki pages and check-in and ticket hashes.

## Fonts ##

> *   _\*italic\*_
................................................................................
> 3. Surround the block by <tt>\`\`\`</tt> (three or more) or <tt>\~\~\~</tt> either at the
> left margin or indented no more than three spaces. The first word
> on that same line (if any) is used in a “`language-WORD`” CSS style in
> the HTML rendering of that code block and is intended for use by
> code syntax highlighters. Thus <tt>\`\`\`c</tt> would mark a block of code
> in the C programming language. Text to be rendered inside the code block
> should therefore start on the next line, not be cuddled up with the
> backticks or tildes.  See the "Diagrams" section below for the case where
> "`language-WORD`" is "pikchr".

> With the standard skins, verbatim text is rendered in a fixed-width font,
> but that is purely a presentation matter, controlled by the skin’s CSS.


## Tables ##

>
    | Header 1     | Header 2    | Header 3      |
    ----------------------------------------------
    | Row 1 Col 1  | Row 1 Col 2 | Row 1 Col 3   |
................................................................................

> Placing **:** at the left, both, or right sides of a cell gives left-aligned,
> centered, or right-aligned text, respectively.  By default, header cells are
> centered, and body cells are left-aligned.

> The leftmost or rightmost **\|** is required only if the first or last column,
> respectively, contains at least one blank cell.

## Diagrams ##

>
~~~~~
~~~ pikchr
oval "Start" fit; arrow; box "Hello, World!" fit; arrow; oval "Done" fit
~~~
~~~~~

> Formatted using [Pikchr](https://pikchr.org/home), resulting in:

>
~~~ pikchr
oval "Start" fit; arrow; box "Hello, World!" fit; arrow; oval "Done" fit
~~~

## Miscellaneous ##

> *   In-line images are made using **\!\[alt-text\]\(image-URL\)**.
> *   Use HTML for advanced formatting such as forms.
> *   **\<!--** HTML-style comments **-->** are supported.
> *   Escape special characters (ex: **\[** **\(** **\|** **\***)
................................................................................
> *  In hyperlinks, if the URL begins with **/** then the root of the Fossil
>    repository is prepended.  This allows for repository-relative hyperlinks.
> *  For documents that begin with a top-level heading (ex: **# heading #**),
>    the heading is omitted from the body of the document and becomes the
>    document title displayed at the top of the Fossil page.

[daringfireball.net]: http://daringfireball.net/projects/markdown/syntax

<a name="intermap"></a>
## Interwiki Tag Map

Changes to src/markdown_html.c.

27
28
29
30
31
32
33









34
35
36
37
38
39
40
...
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
...
321
322
323
324
325
326
327











































328
329
330
331
332
333
334
...
360
361
362
363
364
365
366




367
368

369
370
371
372
373
374
375
...
510
511
512
513
514
515
516



517
518
519
520
521
void markdown_to_html(
  struct Blob *input_markdown,
  struct Blob *output_title,
  struct Blob *output_body);

#endif /* INTERFACE */











/* INTER_BLOCK -- skip a line between block level elements */
#define INTER_BLOCK(ob) \
  do { if( blob_size(ob)>0 ) blob_append_char(ob, '\n'); } while (0)

/* BLOB_APPEND_LITERAL -- append a string literal to a blob */
#define BLOB_APPEND_LITERAL(blob, literal) \
................................................................................
  INTER_BLOCK(ob);
  BLOB_APPEND_LITERAL(ob, "</div>\n");
}

static void html_blockhtml(struct Blob *ob, struct Blob *text, void *opaque){
  char *data = blob_buffer(text);
  size_t size = blob_size(text);
  Blob *title = (Blob*)opaque;
  while( size>0 && fossil_isspace(data[0]) ){ data++; size--; }
  while( size>0 && fossil_isspace(data[size-1]) ){ size--; }
  /* If the first raw block is an <h1> element, then use it as the title. */
  if( blob_size(ob)<=PROLOG_SIZE
   && size>9
   && title!=0
   && sqlite3_strnicmp("<h1",data,3)==0
................................................................................

static void html_header(
  struct Blob *ob,
  struct Blob *text,
  int level,
  void *opaque
){
  struct Blob *title = opaque;
  /* The first header at the beginning of a text is considered as
   * a title and not output. */
  if( blob_size(ob)<=PROLOG_SIZE && title!=0 && blob_size(title)==0 ){
    BLOB_APPEND_BLOB(title, text);
    return;
  }
  INTER_BLOCK(ob);
................................................................................
    html_escape(ob, blob_buffer(link)+7, blob_size(link)-7);
  }else{
    html_escape(ob, blob_buffer(link), blob_size(link));
  }
  BLOB_APPEND_LITERAL(ob, "</a>");
  return 1;
}












































/* Invoked for `...` blocks where there are nSep grave accents in a
** row that serve as the delimiter.  According to CommonMark:
**
**   *  https://spec.commonmark.org/0.29/#fenced-code-blocks
**   *  https://spec.commonmark.org/0.29/#code-spans
**
................................................................................
      int k, j;
      i++;
      for(k=0; k<i && fossil_isspace(z[k]); k++){}
      if( k==i ){
        blob_appendf(ob, "<pre><code>%#h</code></pre>", n-i, z+i);
      }else{
        for(j=k+1; j<i && !fossil_isspace(z[j]); j++){}




        blob_appendf(ob, "<pre><code class='language-%#h'>%#h</code></pre>",
                          j-k, z+k, n-i, z+i);

      }
    }
  }
  return 1;
}

static int html_double_emphasis(
................................................................................
    0,    /* entity */
    html_normal_text,

    /* misc. parameters */
    "*_", /* emph_chars */
    0     /* opaque */
  };



  html_renderer.opaque = output_title;
  if( output_title ) blob_reset(output_title);
  blob_reset(output_body);
  markdown(output_body, input_markdown, &html_renderer);
}







>
>
>
>
>
>
>
>
>







 







|







 







|







 







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







 







>
>
>
>
|
|
>







 







>
>
>
|




27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
...
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
...
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
...
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
...
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
...
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
void markdown_to_html(
  struct Blob *input_markdown,
  struct Blob *output_title,
  struct Blob *output_body);

#endif /* INTERFACE */

/*
** An instance of the following structure is passed through the
** "opaque" pointer.
*/
typedef struct MarkdownToHtml MarkdownToHtml;
struct MarkdownToHtml {
  Blob *output_title;     /* Store the title here */
};


/* INTER_BLOCK -- skip a line between block level elements */
#define INTER_BLOCK(ob) \
  do { if( blob_size(ob)>0 ) blob_append_char(ob, '\n'); } while (0)

/* BLOB_APPEND_LITERAL -- append a string literal to a blob */
#define BLOB_APPEND_LITERAL(blob, literal) \
................................................................................
  INTER_BLOCK(ob);
  BLOB_APPEND_LITERAL(ob, "</div>\n");
}

static void html_blockhtml(struct Blob *ob, struct Blob *text, void *opaque){
  char *data = blob_buffer(text);
  size_t size = blob_size(text);
  Blob *title = ((MarkdownToHtml*)opaque)->output_title;
  while( size>0 && fossil_isspace(data[0]) ){ data++; size--; }
  while( size>0 && fossil_isspace(data[size-1]) ){ size--; }
  /* If the first raw block is an <h1> element, then use it as the title. */
  if( blob_size(ob)<=PROLOG_SIZE
   && size>9
   && title!=0
   && sqlite3_strnicmp("<h1",data,3)==0
................................................................................

static void html_header(
  struct Blob *ob,
  struct Blob *text,
  int level,
  void *opaque
){
  struct Blob *title = ((MarkdownToHtml*)opaque)->output_title;
  /* The first header at the beginning of a text is considered as
   * a title and not output. */
  if( blob_size(ob)<=PROLOG_SIZE && title!=0 && blob_size(title)==0 ){
    BLOB_APPEND_BLOB(title, text);
    return;
  }
  INTER_BLOCK(ob);
................................................................................
    html_escape(ob, blob_buffer(link)+7, blob_size(link)-7);
  }else{
    html_escape(ob, blob_buffer(link), blob_size(link));
  }
  BLOB_APPEND_LITERAL(ob, "</a>");
  return 1;
}

/*
** The nSrc bytes at zSrc[] are Pikchr input text (allegedly).  Process that
** text and insert the result in place of the original.
*/
void pikchr_to_html(
  Blob *ob,                     /* Write the generated SVG here */
  const char *zSrc, int nSrc,   /* The Pikchr source text */
  const char *zArg, int nArg    /* Addition arguments */
){
  int pikFlags = PIKCHR_PROCESS_NONCE
    | PIKCHR_PROCESS_DIV
    | PIKCHR_PROCESS_SRC
    | PIKCHR_PROCESS_ERR_PRE;
  Blob bSrc = empty_blob;

  while( nArg>0 ){
    int i;
    for(i=0; i<nArg && !fossil_isspace(zArg[i]); i++){}
    if( i==6 && strncmp(zArg, "center", 6)==0 ){
      pikFlags |= PIKCHR_PROCESS_DIV_CENTER;
    }else if( i==6 && strncmp(zArg, "indent", 6)==0 ){
      pikFlags |= PIKCHR_PROCESS_DIV_INDENT;
    }else if( i==10 && strncmp(zArg, "float-left", 10)==0 ){
      pikFlags |= PIKCHR_PROCESS_DIV_FLOAT_LEFT;
    }else if( i==11 && strncmp(zArg, "float-right", 11)==0 ){
      pikFlags |= PIKCHR_PROCESS_DIV_FLOAT_RIGHT;
    }else if( i==6 && strncmp(zArg, "toggle", 6)==0 ){
      pikFlags |= PIKCHR_PROCESS_DIV_TOGGLE;
    }else if( i==6 && strncmp(zArg, "source", 6)==0 ){
      pikFlags |= PIKCHR_PROCESS_DIV_SOURCE;
    }else if( i==13 && strncmp(zArg, "source-inline", 13)==0 ){
      pikFlags |= PIKCHR_PROCESS_DIV_SOURCE_INLINE;
    }
    while( i<nArg && fossil_isspace(zArg[i]) ){ i++; }
    zArg += i;
    nArg -= i;
  }
  blob_append(&bSrc, zSrc, nSrc)
    /*have to dup input to ensure a NUL-terminated source string */;
  pikchr_process(blob_str(&bSrc), pikFlags, 0, ob);
  blob_reset(&bSrc);
}

/* Invoked for `...` blocks where there are nSep grave accents in a
** row that serve as the delimiter.  According to CommonMark:
**
**   *  https://spec.commonmark.org/0.29/#fenced-code-blocks
**   *  https://spec.commonmark.org/0.29/#code-spans
**
................................................................................
      int k, j;
      i++;
      for(k=0; k<i && fossil_isspace(z[k]); k++){}
      if( k==i ){
        blob_appendf(ob, "<pre><code>%#h</code></pre>", n-i, z+i);
      }else{
        for(j=k+1; j<i && !fossil_isspace(z[j]); j++){}
        if( j-k==6 && strncmp(z+k,"pikchr",6)==0 ){
          while( j<i && fossil_isspace(z[j]) ){ j++; }
          pikchr_to_html(ob, z+i, n-i, z+j, i-j);
        }else{
          blob_appendf(ob, "<pre><code class='language-%#h'>%#h</code></pre>",
                            j-k, z+k, n-i, z+i);
        }
      }
    }
  }
  return 1;
}

static int html_double_emphasis(
................................................................................
    0,    /* entity */
    html_normal_text,

    /* misc. parameters */
    "*_", /* emph_chars */
    0     /* opaque */
  };
  MarkdownToHtml context;
  memset(&context, 0, sizeof(context));
  context.output_title = output_title;
  html_renderer.opaque = &context;
  if( output_title ) blob_reset(output_title);
  blob_reset(output_body);
  markdown(output_body, input_markdown, &html_renderer);
}

Changes to src/merge3.c.

136
137
138
139
140
141
142
143
144
145
146
147
148































149
150
151
152
153
154
155
...
164
165
166
167
168
169
170


















171
172
173
174
175
176
177
...
267
268
269
270
271
272
273

274

275

276

277

278

279

280
281
282
283
284
285
286
...
317
318
319
320
321
322
323
324

325
326
327

328
329
330
331
332
333
334
}

/*
** Text of boundary markers for merge conflicts.
*/
static const char *const mergeMarker[] = {
 /*123456789 123456789 123456789 123456789 123456789 123456789 123456789*/
  "<<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<<<<\n",
  "||||||| COMMON ANCESTOR content follows ||||||||||||||||||||||||||||\n",
  "======= MERGED IN content follows ==================================\n",
  ">>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
};

































/*
** Do a three-way merge.  Initialize pOut to contain the result.
**
** The merge is an edit against pV2.  Both pV1 and pV2 have a
** common origin at pPivot.  Apply the changes of pPivot ==> pV1
** to pV2.
................................................................................
  int *aC2;              /* Changes from pPivot to pV2 */
  int i1, i2;            /* Index into aC1[] and aC2[] */
  int nCpy, nDel, nIns;  /* Number of lines to copy, delete, or insert */
  int limit1, limit2;    /* Sizes of aC1[] and aC2[] */
  int nConflict = 0;     /* Number of merge conflicts seen so far */

  blob_zero(pOut);         /* Merge results stored in pOut */



















  /* Compute the edits that occur from pPivot => pV1 (into aC1)
  ** and pPivot => pV2 (into aC2).  Each of the aC1 and aC2 arrays is
  ** an array of integer triples.  Within each triple, the first integer
  ** is the number of lines of text to copy directly from the pivot,
  ** the second integer is the number of lines of text to omit from the
  ** pivot, and the third integer is the number of lines of text that are
................................................................................
      int sz = 1;    /* Size of the conflict in lines */
      nConflict++;
      while( !ends_at_CPY(&aC1[i1], sz) || !ends_at_CPY(&aC2[i2], sz) ){
        sz++;
      }
      DEBUG( printf("CONFLICT %d\n", sz); )
      blob_append(pOut, mergeMarker[0], -1);

      i1 = output_one_side(pOut, pV1, aC1, i1, sz);

      blob_append(pOut, mergeMarker[1], -1);

      blob_copy_lines(pOut, pPivot, sz);

      blob_append(pOut, mergeMarker[2], -1);

      i2 = output_one_side(pOut, pV2, aC2, i2, sz);

      blob_append(pOut, mergeMarker[3], -1);

   }

    /* If we are finished with an edit triple, advance to the next
    ** triple.
    */
    if( i1<limit1 && aC1[i1]==0 && aC1[i1+1]==0 && aC1[i1+2]==0 ) i1+=3;
    if( i2<limit2 && aC2[i2]==0 && aC2[i2+1]==0 && aC2[i2+2]==0 ) i2+=3;
................................................................................
  int n = blob_size(p) - len + 1;
  assert( len==(int)strlen(mergeMarker[1]) );
  assert( len==(int)strlen(mergeMarker[2]) );
  assert( len==(int)strlen(mergeMarker[3]) );
  assert( count(mergeMarker)==4 );
  for(i=0; i<n; ){
    for(j=0; j<4; j++){
      if( memcmp(&z[i], mergeMarker[j], len)==0 ) return 1;

    }
    while( i<n && z[i]!='\n' ){ i++; }
    while( i<n && z[i]=='\n' ){ i++; }

  }
  return 0;
}

/*
** Return true if the named file contains an unresolved merge marker line.
*/







|
|
|
|


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







 







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







 







>

>

>

>

>

>

>







 







|
>


<
>







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
...
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
...
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
...
373
374
375
376
377
378
379
380
381
382
383

384
385
386
387
388
389
390
391
}

/*
** Text of boundary markers for merge conflicts.
*/
static const char *const mergeMarker[] = {
 /*123456789 123456789 123456789 123456789 123456789 123456789 123456789*/
  "<<<<<<< BEGIN MERGE CONFLICT: local copy shown first <<<<<<<<<<<<<<<",
  "||||||| COMMON ANCESTOR content follows ||||||||||||||||||||||||||||",
  "======= MERGED IN content follows ==================================",
  ">>>>>>> END MERGE CONFLICT >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
};

/*
** Return true if the input blob contains any CR/LF pairs on the first
** ten lines. This should be enough to detect files that use mainly CR/LF
** line endings without causing a performance impact for LF only files.
*/
int contains_crlf(Blob *p){
  int i;
  int j = 0;
  const int maxL = 10;             /* Max lines to check */
  const char *z = blob_buffer(p);
  int n = blob_size(p)+1;
  for(i=1; i<n; ){
    if( z[i-1]=='\r' && z[i]=='\n' ) return 1;
    while( i<n && z[i]!='\n' ){ i++; }
    j++;
    if( j>maxL ) return 0;
  }
  return 0;
}

/*
** Ensure that the text in pBlob ends with a new line.
** If useCrLf is true adds "\r\n" otherwise '\n'.
*/
void ensure_line_end(Blob *pBlob, int useCrLf){
  if( pBlob->nUsed<=0 ) return;
  if( pBlob->aData[pBlob->nUsed-1]!='\n' ){
    if( useCrLf ) blob_append_char(pBlob, '\r');
    blob_append_char(pBlob, '\n');
  }
}

/*
** Do a three-way merge.  Initialize pOut to contain the result.
**
** The merge is an edit against pV2.  Both pV1 and pV2 have a
** common origin at pPivot.  Apply the changes of pPivot ==> pV1
** to pV2.
................................................................................
  int *aC2;              /* Changes from pPivot to pV2 */
  int i1, i2;            /* Index into aC1[] and aC2[] */
  int nCpy, nDel, nIns;  /* Number of lines to copy, delete, or insert */
  int limit1, limit2;    /* Sizes of aC1[] and aC2[] */
  int nConflict = 0;     /* Number of merge conflicts seen so far */

  blob_zero(pOut);         /* Merge results stored in pOut */
  
  /* If both pV1 and pV2 start with a UTF-8 byte-order-mark (BOM),
  ** keep it in the output. This should be secure enough not to cause
  ** unintended changes to the merged file and consistent with what
  ** users are using in their source files.
  */
  if( starts_with_utf8_bom(pV1, 0) && starts_with_utf8_bom(pV2, 0) ){
    blob_append(pOut, (char*)get_utf8_bom(0), -1);
  }

  /* Check once to see if both pV1 and pV2 contains CR/LF endings.
  ** If true, CR/LF pair will be used later to append the
  ** boundary markers for merge conflicts.
  */
  int useCrLf = 0;
  if( contains_crlf(pV1) && contains_crlf(pV2) ){
    useCrLf = 1;
  }

  /* Compute the edits that occur from pPivot => pV1 (into aC1)
  ** and pPivot => pV2 (into aC2).  Each of the aC1 and aC2 arrays is
  ** an array of integer triples.  Within each triple, the first integer
  ** is the number of lines of text to copy directly from the pivot,
  ** the second integer is the number of lines of text to omit from the
  ** pivot, and the third integer is the number of lines of text that are
................................................................................
      int sz = 1;    /* Size of the conflict in lines */
      nConflict++;
      while( !ends_at_CPY(&aC1[i1], sz) || !ends_at_CPY(&aC2[i2], sz) ){
        sz++;
      }
      DEBUG( printf("CONFLICT %d\n", sz); )
      blob_append(pOut, mergeMarker[0], -1);
      ensure_line_end(pOut, useCrLf);
      i1 = output_one_side(pOut, pV1, aC1, i1, sz);
      ensure_line_end(pOut, useCrLf);
      blob_append(pOut, mergeMarker[1], -1);
      ensure_line_end(pOut, useCrLf);
      blob_copy_lines(pOut, pPivot, sz);
      ensure_line_end(pOut, useCrLf);
      blob_append(pOut, mergeMarker[2], -1);
      ensure_line_end(pOut, useCrLf);
      i2 = output_one_side(pOut, pV2, aC2, i2, sz);
      ensure_line_end(pOut, useCrLf);
      blob_append(pOut, mergeMarker[3], -1);
      ensure_line_end(pOut, useCrLf);
   }

    /* If we are finished with an edit triple, advance to the next
    ** triple.
    */
    if( i1<limit1 && aC1[i1]==0 && aC1[i1+1]==0 && aC1[i1+2]==0 ) i1+=3;
    if( i2<limit2 && aC2[i2]==0 && aC2[i2+1]==0 && aC2[i2+2]==0 ) i2+=3;
................................................................................
  int n = blob_size(p) - len + 1;
  assert( len==(int)strlen(mergeMarker[1]) );
  assert( len==(int)strlen(mergeMarker[2]) );
  assert( len==(int)strlen(mergeMarker[3]) );
  assert( count(mergeMarker)==4 );
  for(i=0; i<n; ){
    for(j=0; j<4; j++){
      if( (memcmp(&z[i], mergeMarker[j], len)==0)
          && (i+1==n || z[i+len]=='\n' || z[i+len]=='\r') ) return 1;
    }
    while( i<n && z[i]!='\n' ){ i++; }

    while( i<n && (z[i]=='\n' || z[i]=='\r') ){ i++; }
  }
  return 0;
}

/*
** Return true if the named file contains an unresolved merge marker line.
*/

Changes to src/mkbuiltin.c.

60
61
62
63
64
65
66

67
68
69
70
71
72
73
..
97
98
99
100
101
102
103

104
105
106
107
108
109
110
...
277
278
279
280
281
282
283

284

285
286
287
288
289
290
291
...
348
349
350
351
352
353
354

355
356
357
358
359
360
361
362
363

364
365
366
367
368
369
370
  }
  got = fread(z, 1, nByte, in);
  fclose(in);
  z[got] = 0;
  return z;
}


/*
** Try to compress a javascript file by removing unnecessary whitespace.
**
** Warning:  This compression routine does not necessarily work for any
** arbitrary Javascript source file.  But it should work ok for the
** well-behaved source files in this project.
*/
................................................................................
      continue;
    }
    z[j++] = c;
  }
  z[j] = 0;
  *pn = j;
}


/*
** There is an instance of the following for each file translated.
*/
typedef struct Resource Resource;
struct Resource {
  char *zName;
................................................................................
  ResourceList resList;
  Resource *aRes;
  int nRes;
  unsigned char *pData;
  int nErr = 0;
  int nSkip;
  int nPrefix = 0;

  int nName;


  if( argc==1 ){
    fprintf(stderr, "usage\t:%s "
      "[--prefix path] [--reslist file] [resource-file1 ...]\n",
       argv[0]
    );
    return 1;
................................................................................
    /* Skip initial lines beginning with # */
    nSkip = 0;
    while( pData[nSkip]=='#' ){
      while( pData[nSkip]!=0 && pData[nSkip]!='\n' ){ nSkip++; }
      if( pData[nSkip]=='\n' ) nSkip++;
    }


    /* Compress javascript source files */
    nName = (int)strlen(aRes[i].zName);
    if( (nName>3 && strcmp(&aRes[i].zName[nName-3],".js")==0)
     || (nName>7  && strcmp(&aRes[i].zName[nName-7], "/js.txt")==0)
    ){
      int x = sz-nSkip;
      compressJavascript(pData+nSkip, &x);
      sz = x + nSkip;
    }


    aRes[i].nByte = sz - nSkip;
    aRes[i].idx = i;
    printf("/* Content of file %s */\n", aRes[i].zName);
    printf("static const unsigned char bidata%d[%d] = {\n  ",
           i, sz+1-nSkip);
    for(j=nSkip, n=0; j<=sz; j++){







>







 







>







 







>

>







 







>









>







60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
..
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
...
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
...
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
  }
  got = fread(z, 1, nByte, in);
  fclose(in);
  z[got] = 0;
  return z;
}

#ifndef FOSSIL_DEBUG
/*
** Try to compress a javascript file by removing unnecessary whitespace.
**
** Warning:  This compression routine does not necessarily work for any
** arbitrary Javascript source file.  But it should work ok for the
** well-behaved source files in this project.
*/
................................................................................
      continue;
    }
    z[j++] = c;
  }
  z[j] = 0;
  *pn = j;
}
#endif /* FOSSIL_DEBUG */

/*
** There is an instance of the following for each file translated.
*/
typedef struct Resource Resource;
struct Resource {
  char *zName;
................................................................................
  ResourceList resList;
  Resource *aRes;
  int nRes;
  unsigned char *pData;
  int nErr = 0;
  int nSkip;
  int nPrefix = 0;
#ifndef FOSSIL_DEBUG
  int nName;
#endif

  if( argc==1 ){
    fprintf(stderr, "usage\t:%s "
      "[--prefix path] [--reslist file] [resource-file1 ...]\n",
       argv[0]
    );
    return 1;
................................................................................
    /* Skip initial lines beginning with # */
    nSkip = 0;
    while( pData[nSkip]=='#' ){
      while( pData[nSkip]!=0 && pData[nSkip]!='\n' ){ nSkip++; }
      if( pData[nSkip]=='\n' ) nSkip++;
    }

#ifndef FOSSIL_DEBUG
    /* Compress javascript source files */
    nName = (int)strlen(aRes[i].zName);
    if( (nName>3 && strcmp(&aRes[i].zName[nName-3],".js")==0)
     || (nName>7  && strcmp(&aRes[i].zName[nName-7], "/js.txt")==0)
    ){
      int x = sz-nSkip;
      compressJavascript(pData+nSkip, &x);
      sz = x + nSkip;
    }
#endif

    aRes[i].nByte = sz - nSkip;
    aRes[i].idx = i;
    printf("/* Content of file %s */\n", aRes[i].zName);
    printf("static const unsigned char bidata%d[%d] = {\n  ",
           i, sz+1-nSkip);
    for(j=nSkip, n=0; j<=sz; j++){

Changes to src/mkindex.c.

88
89
90
91
92
93
94

95
96
97
98
99
100
101
...
246
247
248
249
250
251
252


253
254
255
256
257
258
259
...
339
340
341
342
343
344
345


346
347
348
349
350
351
352
...
475
476
477
478
479
480
481
482
483
484
485

486
487
488
489
490
491
492
#define CMDFLAG_WEBPAGE     0x0008      /* Web pages */
#define CMDFLAG_COMMAND     0x0010      /* A command */
#define CMDFLAG_SETTING     0x0020      /* A setting */
#define CMDFLAG_VERSIONABLE 0x0040      /* A versionable setting */
#define CMDFLAG_BLOCKTEXT   0x0080      /* Multi-line text setting */
#define CMDFLAG_BOOLEAN     0x0100      /* A boolean setting */
#define CMDFLAG_RAWCONTENT  0x0200      /* Do not interpret webpage content */

/**************************************************************************/

/*
** Each entry looks like this:
*/
typedef struct Entry {
  int eType;        /* CMDFLAG_* values */
................................................................................
      aEntry[nUsed].iWidth = 0;
      aEntry[nUsed].eType |= CMDFLAG_BOOLEAN;
    }else if( j==10 && strncmp(&zLine[i], "block-text", j)==0 ){
      aEntry[nUsed].eType &= ~(CMDFLAG_BOOLEAN);
      aEntry[nUsed].eType |= CMDFLAG_BLOCKTEXT;
    }else if( j==11 && strncmp(&zLine[i], "versionable", j)==0 ){
      aEntry[nUsed].eType |= CMDFLAG_VERSIONABLE;


    }else if( j>6 && strncmp(&zLine[i], "width=", 6)==0 ){
      aEntry[nUsed].iWidth = atoi(&zLine[i+6]);
    }else if( j>8 && strncmp(&zLine[i], "default=", 8)==0 ){
      aEntry[nUsed].zDflt = string_dup(&zLine[i+8], j-8);
    }else if( j>9 && strncmp(&zLine[i], "variable=", 9)==0 ){
      aEntry[nUsed].zVar = string_dup(&zLine[i+9], j-9);
    }else{
................................................................................
      return;
    }
    i += 4;
    if( !fossil_isspace(zLine[i]) ) goto page_skip;
    while( fossil_isspace(zLine[i]) ){ i++; }
    for(j=0; fossil_isident(zLine[i+j]); j++){}
    if( j==0 ) goto page_skip;


  }
  for(k=nHelp-1; k>=0 && fossil_isspace(zHelp[k]); k--){}
  nHelp = k+1;
  zHelp[nHelp] = 0;
  for(k=0; k<nHelp && fossil_isspace(zHelp[k]); k++){}
  if( k<nHelp ){
    z = string_dup(&zHelp[k], nHelp-k);
................................................................................
    }
    printf("  { \"%s\",%*s", z, (int)(20-strlen(z)), "");
    if( zVar ){
      printf(" \"%s\",%*s", zVar, (int)(15-strlen(zVar)), "");
    }else{
      printf(" 0,%*s", 16, "");
    }
    printf(" %3d, %d, %d, \"%s\"%*s },\n",
      aEntry[i].iWidth,
      (aEntry[i].eType & CMDFLAG_VERSIONABLE)!=0,
      (aEntry[i].eType & CMDFLAG_BLOCKTEXT)!=0,

      zDef, (int)(10-strlen(zDef)), ""
    );
    if( aEntry[i].zIf ){
      printf("#endif\n");
    }
  }
  printf("{0,0,0,0,0,0}};\n");







>







 







>
>







 







>
>







 







|



>







88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
...
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
...
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
...
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#define CMDFLAG_WEBPAGE     0x0008      /* Web pages */
#define CMDFLAG_COMMAND     0x0010      /* A command */
#define CMDFLAG_SETTING     0x0020      /* A setting */
#define CMDFLAG_VERSIONABLE 0x0040      /* A versionable setting */
#define CMDFLAG_BLOCKTEXT   0x0080      /* Multi-line text setting */
#define CMDFLAG_BOOLEAN     0x0100      /* A boolean setting */
#define CMDFLAG_RAWCONTENT  0x0200      /* Do not interpret webpage content */
#define CMDFLAG_SENSITIVE   0x0400      /* Security-sensitive setting */
/**************************************************************************/

/*
** Each entry looks like this:
*/
typedef struct Entry {
  int eType;        /* CMDFLAG_* values */
................................................................................
      aEntry[nUsed].iWidth = 0;
      aEntry[nUsed].eType |= CMDFLAG_BOOLEAN;
    }else if( j==10 && strncmp(&zLine[i], "block-text", j)==0 ){
      aEntry[nUsed].eType &= ~(CMDFLAG_BOOLEAN);
      aEntry[nUsed].eType |= CMDFLAG_BLOCKTEXT;
    }else if( j==11 && strncmp(&zLine[i], "versionable", j)==0 ){
      aEntry[nUsed].eType |= CMDFLAG_VERSIONABLE;
    }else if( j==9 && strncmp(&zLine[i], "sensitive", j)==0 ){
      aEntry[nUsed].eType |= CMDFLAG_SENSITIVE;
    }else if( j>6 && strncmp(&zLine[i], "width=", 6)==0 ){
      aEntry[nUsed].iWidth = atoi(&zLine[i+6]);
    }else if( j>8 && strncmp(&zLine[i], "default=", 8)==0 ){
      aEntry[nUsed].zDflt = string_dup(&zLine[i+8], j-8);
    }else if( j>9 && strncmp(&zLine[i], "variable=", 9)==0 ){
      aEntry[nUsed].zVar = string_dup(&zLine[i+9], j-9);
    }else{
................................................................................
      return;
    }
    i += 4;
    if( !fossil_isspace(zLine[i]) ) goto page_skip;
    while( fossil_isspace(zLine[i]) ){ i++; }
    for(j=0; fossil_isident(zLine[i+j]); j++){}
    if( j==0 ) goto page_skip;
  }else{
    j = 0;
  }
  for(k=nHelp-1; k>=0 && fossil_isspace(zHelp[k]); k--){}
  nHelp = k+1;
  zHelp[nHelp] = 0;
  for(k=0; k<nHelp && fossil_isspace(zHelp[k]); k++){}
  if( k<nHelp ){
    z = string_dup(&zHelp[k], nHelp-k);
................................................................................
    }
    printf("  { \"%s\",%*s", z, (int)(20-strlen(z)), "");
    if( zVar ){
      printf(" \"%s\",%*s", zVar, (int)(15-strlen(zVar)), "");
    }else{
      printf(" 0,%*s", 16, "");
    }
    printf(" %3d, %d, %d, %d, \"%s\"%*s },\n",
      aEntry[i].iWidth,
      (aEntry[i].eType & CMDFLAG_VERSIONABLE)!=0,
      (aEntry[i].eType & CMDFLAG_BLOCKTEXT)!=0,
      (aEntry[i].eType & CMDFLAG_SENSITIVE)!=0,
      zDef, (int)(10-strlen(zDef)), ""
    );
    if( aEntry[i].zIf ){
      printf("#endif\n");
    }
  }
  printf("{0,0,0,0,0,0}};\n");

Changes to src/moderate.c.

157
158
159
160
161
162
163

164
165
166
167
168
169
170
...
219
220
221
222
223
224
225

226
227
    "INSERT OR IGNORE INTO unclustered VALUES(%d);"
    "INSERT OR IGNORE INTO unsent VALUES(%d);",
    rid, rid, rid
  );
  db_multi_exec("DELETE FROM modreq WHERE objid=%d", rid);
  admin_log("Approved moderation of rid %c-%d.", class, rid);
  if( class!='a' ) search_doc_touch(class, rid, 0);

  db_end_transaction(0);
}

/*
** WEBPAGE: modreq
**
** Show all pending moderation request
................................................................................
    "(SELECT login FROM user)"
  );
  while( db_step(&q)==SQLITE_ROW ){
    int const objid = db_column_int(&q, 0);
    moderation_disapprove(objid);
  }
  db_finalize(&q);

  db_end_transaction(0);
}







>







 







>


157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
...
220
221
222
223
224
225
226
227
228
229
    "INSERT OR IGNORE INTO unclustered VALUES(%d);"
    "INSERT OR IGNORE INTO unsent VALUES(%d);",
    rid, rid, rid
  );
  db_multi_exec("DELETE FROM modreq WHERE objid=%d", rid);
  admin_log("Approved moderation of rid %c-%d.", class, rid);
  if( class!='a' ) search_doc_touch(class, rid, 0);
  setup_incr_cfgcnt();
  db_end_transaction(0);
}

/*
** WEBPAGE: modreq
**
** Show all pending moderation request
................................................................................
    "(SELECT login FROM user)"
  );
  while( db_step(&q)==SQLITE_ROW ){
    int const objid = db_column_int(&q, 0);
    moderation_disapprove(objid);
  }
  db_finalize(&q);
  setup_incr_cfgcnt();
  db_end_transaction(0);
}

Added src/pikchr.c.