[test] Set tests involving [ZN] timezone picture to %test:pending as this is not yet correctly implemented

xquery version "3.0";

module namespace fd="http://exist-db.org/xquery/test/format-dates";

declare namespace test="http://exist-db.org/xquery/xqsuite";

declare
    %test:args("2012-06-26")
    %test:assertEquals("26.6.2012")
    %test:args("2012-06-01")
    %test:assertEquals("1.6.2012")
function fd:simple-date($date as xs:date) {
    format-date($date, "[D].[M].[Y]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26.06.2012")
    %test:args("2012-06-01")
    %test:assertEquals("01.06.2012")
function fd:simple-format($date as xs:date) {
    format-date($date, "[D00].[M01].[Y0]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26.6.2012")
    %test:args("2012-06-01")
    %test:assertEquals("1.6.2012")
function fd:format-month-numeric-width($date as xs:date) {
    format-date($date, "[D,1-2].[M,*-*].[Y,*]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26 JUN 2012")
    %test:args("1970-10-07")
    %test:assertEquals("07 OCT 1970")
function fd:format-month-string-width-caps($date as xs:date) {
    format-date($date, "[D01] [MN,*-3] [Y0001]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26 Jun 2012")
    %test:args("1970-10-07")
    %test:assertEquals("07 Oct 1970")
function fd:format-month-string-width-title($date as xs:date) {
    format-date($date, "[D01] [MNn,*-3] [Y0001]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("Tuesday, June 26, 2012")
    %test:args("1970-10-07")
    %test:assertEquals("Wednesday, October 7, 1970")
function fd:format-names($date as xs:date) {
    format-date($date, "[FNn], [MNn] [D], [Y]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("Tue Jun 26 2012")
    %test:args("1970-10-07")
    %test:assertEquals("Wed Oct 7 1970")
function fd:format-names-width($date as xs:date) {
    format-date($date, "[FNn,*-3] [MNn,*-3] [D] [Y]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("Tuesday, June 26th, 2012")
    %test:args("2012-06-01")
    %test:assertEquals("Friday, June 1st, 2012")
    %test:args("2012-06-02")
    %test:assertEquals("Saturday, June 2nd, 2012")
    %test:args("2012-06-03")
    %test:assertEquals("Sunday, June 3rd, 2012")
function fd:format-ordinal($date as xs:date) {
    format-date($date, "[FNn], [MNn] [D0o], [Y]")
};

declare
    %test:args("2002-12-31")
    %test:assertEquals("[2002-12-31]")
function fd:format-square-brackets($date as xs:date) {
    format-date($date, "[[[Y0001]-[M01]-[D01]]]")
};

declare
    %test:args("2012-06-26T23:14:22.566+02:00")
    %test:assertEquals("11:14 pm on Tuesday, June 26th, 2012")
function fd:format-dateTime($date as xs:dateTime) {
    format-dateTime($date, "[h00]:[m00] [P] on [FNn], [MNn] [D1o], [Y]")
};

declare
    %test:args("2012-06-26+02:00")
    %test:assertEquals("20120626GMT+02:00")
function fd:format-date-z($date as xs:date) {
    format-date($date, "[Y0001][M01][D01][z]")
};

declare
    %test:args("2012-06-26+02:00")
    %test:assertEquals("20120626+02:00")
function fd:format-date-Z($date as xs:date) {
    format-date($date, "[Y0001][M01][D01][Z]")
};

declare
    %test:args("2012-06-26T23:14:22.566+02:00")
    %test:assertEquals("20120626231422GMT+02:00")
function fd:format-dateTime-z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("GMT-10:00")
function fd:format-dateTime-z-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("GMT-05:00")
function fd:format-dateTime-z-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("GMT+00:00")
function fd:format-dateTime-z-zero($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("GMT+05:30")
function fd:format-dateTime-z-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("GMT+13:00")
function fd:format-dateTime-z-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T23:14:22.566+02:00")
    %test:assertEquals("20120626231422+02:00")
function fd:format-dateTime-Z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-05:00")
function fd:format-dateTime-Z-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+00:00")
function fd:format-dateTime-Z-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-Z-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T23:14:22.566")
    %test:assertEquals("20120626231422")
function fd:format-dateTime-no-tz-z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][z]")
};

declare
    %test:args("2012-06-26T23:14:22.566")
    %test:assertEquals("20120626231422")
function fd:format-dateTime-no-tz-Z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10")
function fd:format-dateTime-Z0-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-5")
function fd:format-dateTime-Z0-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+0")
function fd:format-dateTime-Z0-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+5:30")
function fd:format-dateTime-Z0-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13")
function fd:format-dateTime-Z0-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z0-00-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-5:00")
function fd:format-dateTime-Z0-00-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+0:00")
function fd:format-dateTime-Z0-00-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+5:30")
function fd:format-dateTime-Z0-00-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z0-00-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z00-00-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-05:00")
function fd:format-dateTime-Z00-00-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+00:00")
function fd:format-dateTime-Z00-00-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-Z00-00-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z00-00-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-1000")
function fd:format-dateTime-Z0000-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-0500")
function fd:format-dateTime-Z0000-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+0000")
function fd:format-dateTime-Z0000-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+0530")
function fd:format-dateTime-Z0000-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+1300")
function fd:format-dateTime-Z0000-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z00-00t-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-05:00")
function fd:format-dateTime-Z00-00t-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("Z")
function fd:format-dateTime-Z00-00t-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-Z00-00t-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z00-00t-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("W")
function fd:format-dateTime-ZZ-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("R")
function fd:format-dateTime-ZZ-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("Z")
function fd:format-dateTime-ZZ-zero($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-ZZ-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-ZZ-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("HST")
function fd:format-dateTime-ZN-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("EST")
function fd:format-dateTime-ZN-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("GMT")
function fd:format-dateTime-ZN-zero($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("IST")
function fd:format-dateTime-ZN-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-ZN-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("06:00 EST")
function fd:format-dateTime-ZN-NY-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("12:00 EST")
function fd:format-dateTime-ZN-NY-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("07:00 EST")
function fd:format-dateTime-ZN-NY-zero($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("01:30 EST")
function fd:format-dateTime-ZN-NY-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:pending("[ZN] is not yet supported")
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("18:00 EST")
function fd:format-dateTime-ZN-NY-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:args("17:45:50")
    %test:assertEquals("17:45:50")
    %test:args("09:45:50")
    %test:assertEquals("09:45:50")
function fd:simple-time($time as xs:time) {
    format-time($time, "[H00]:[m00]:[s]")
};

declare
    %test:args("17:45:50")
    %test:assertEquals("05:45 pm")
    %test:args("09:45:50")
    %test:assertEquals("09:45 am")
function fd:time-am-pm($time as xs:time) {
    format-time($time, "[h00]:[m00] [P]")
};

declare
    %test:assertError
function fd:date-format-in-format-time() {
    format-time(current-time(), "[Y]")
};

declare
    %test:assertError
function fd:time-format-in-format-date() {
    format-date(current-dateTime(), "[H]")
};

declare
    %test:args("2012-06-27T10:21:55.082+02:00")
    %test:assertEquals("Mittwoch, 27. Juni 2012")
    %test:args("1970-10-07T10:21:55.082+02:00")
    %test:assertEquals("Mittwoch, 7. Oktober 1970")
function fd:language($date as xs:dateTime) {
    format-date($date, "[FNn], [D1o] [MNn] [Y]", "de", (), ())
};

declare
    %test:args("2012-06-27T10:21:55.082+02:00")
    %test:assertEquals("Среда, 27 Июня 2012")
    %test:args("1970-10-07T10:21:55.082+02:00")
    %test:assertEquals("Среда, 7 Октября 1970")
function fd:language-ru($date as xs:dateTime) {
    format-date($date, "[FNn], [D1o] [MNn] [Y]", "ru", (), ())
};

xquery version "3.0";

module namespace fd="http://exist-db.org/xquery/test/format-dates";

declare namespace test="http://exist-db.org/xquery/xqsuite";

declare
    %test:args("2012-06-26")
    %test:assertEquals("26.6.2012")
    %test:args("2012-06-01")
    %test:assertEquals("1.6.2012")
function fd:simple-date($date as xs:date) {
    format-date($date, "[D].[M].[Y]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26.06.2012")
    %test:args("2012-06-01")
    %test:assertEquals("01.06.2012")
function fd:simple-format($date as xs:date) {
    format-date($date, "[D00].[M01].[Y0]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26.6.2012")
    %test:args("2012-06-01")
    %test:assertEquals("1.6.2012")
function fd:format-month-numeric-width($date as xs:date) {
    format-date($date, "[D,1-2].[M,*-*].[Y,*]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26 JUN 2012")
    %test:args("1970-10-07")
    %test:assertEquals("07 OCT 1970")
function fd:format-month-string-width-caps($date as xs:date) {
    format-date($date, "[D01] [MN,*-3] [Y0001]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("26 Jun 2012")
    %test:args("1970-10-07")
    %test:assertEquals("07 Oct 1970")
function fd:format-month-string-width-title($date as xs:date) {
    format-date($date, "[D01] [MNn,*-3] [Y0001]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("Tuesday, June 26, 2012")
    %test:args("1970-10-07")
    %test:assertEquals("Wednesday, October 7, 1970")
function fd:format-names($date as xs:date) {
    format-date($date, "[FNn], [MNn] [D], [Y]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("Tue Jun 26 2012")
    %test:args("1970-10-07")
    %test:assertEquals("Wed Oct 7 1970")
function fd:format-names-width($date as xs:date) {
    format-date($date, "[FNn,*-3] [MNn,*-3] [D] [Y]")
};

declare
    %test:args("2012-06-26")
    %test:assertEquals("Tuesday, June 26th, 2012")
    %test:args("2012-06-01")
    %test:assertEquals("Friday, June 1st, 2012")
    %test:args("2012-06-02")
    %test:assertEquals("Saturday, June 2nd, 2012")
    %test:args("2012-06-03")
    %test:assertEquals("Sunday, June 3rd, 2012")
function fd:format-ordinal($date as xs:date) {
    format-date($date, "[FNn], [MNn] [D0o], [Y]")
};

declare
    %test:args("2002-12-31")
    %test:assertEquals("[2002-12-31]")
function fd:format-square-brackets($date as xs:date) {
    format-date($date, "[[[Y0001]-[M01]-[D01]]]")
};

declare
    %test:args("2012-06-26T23:14:22.566+02:00")
    %test:assertEquals("11:14 pm on Tuesday, June 26th, 2012")
function fd:format-dateTime($date as xs:dateTime) {
    format-dateTime($date, "[h00]:[m00] [P] on [FNn], [MNn] [D1o], [Y]")
};

declare
    %test:args("2012-06-26+02:00")
    %test:assertEquals("20120626GMT+02:00")
function fd:format-date-z($date as xs:date) {
    format-date($date, "[Y0001][M01][D01][z]")
};

declare
    %test:args("2012-06-26+02:00")
    %test:assertEquals("20120626+02:00")
function fd:format-date-Z($date as xs:date) {
    format-date($date, "[Y0001][M01][D01][Z]")
};

declare
    %test:args("2012-06-26T23:14:22.566+02:00")
    %test:assertEquals("20120626231422GMT+02:00")
function fd:format-dateTime-z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("GMT-10:00")
function fd:format-dateTime-z-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("GMT-05:00")
function fd:format-dateTime-z-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("GMT+00:00")
function fd:format-dateTime-z-zero($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("GMT+05:30")
function fd:format-dateTime-z-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("GMT+13:00")
function fd:format-dateTime-z-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[z]")
};

declare
    %test:args("2012-06-26T23:14:22.566+02:00")
    %test:assertEquals("20120626231422+02:00")
function fd:format-dateTime-Z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-05:00")
function fd:format-dateTime-Z-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+00:00")
function fd:format-dateTime-Z-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-Z-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z]")
};

declare
    %test:args("2012-06-26T23:14:22.566")
    %test:assertEquals("20120626231422")
function fd:format-dateTime-no-tz-z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][z]")
};

declare
    %test:args("2012-06-26T23:14:22.566")
    %test:assertEquals("20120626231422")
function fd:format-dateTime-no-tz-Z($date as xs:dateTime) {
    format-dateTime($date, "[Y0001][M01][D01][H01][m01][s01][Z]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10")
function fd:format-dateTime-Z0-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-5")
function fd:format-dateTime-Z0-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+0")
function fd:format-dateTime-Z0-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+5:30")
function fd:format-dateTime-Z0-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13")
function fd:format-dateTime-Z0-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z0-00-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-5:00")
function fd:format-dateTime-Z0-00-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+0:00")
function fd:format-dateTime-Z0-00-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+5:30")
function fd:format-dateTime-Z0-00-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z0-00-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z00-00-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-05:00")
function fd:format-dateTime-Z00-00-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+00:00")
function fd:format-dateTime-Z00-00-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-Z00-00-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z00-00-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-1000")
function fd:format-dateTime-Z0000-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-0500")
function fd:format-dateTime-Z0000-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("+0000")
function fd:format-dateTime-Z0000-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+0530")
function fd:format-dateTime-Z0000-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+1300")
function fd:format-dateTime-Z0000-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z0000]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("-10:00")
function fd:format-dateTime-Z00-00t-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("-05:00")
function fd:format-dateTime-Z00-00t-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("Z")
function fd:format-dateTime-Z00-00t-zero($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-Z00-00t-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-Z00-00t-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[Z00:00t]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("W")
function fd:format-dateTime-ZZ-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("R")
function fd:format-dateTime-ZZ-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("Z")
function fd:format-dateTime-ZZ-zero($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("+05:30")
function fd:format-dateTime-ZZ-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-ZZ-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZZ]")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("HST")
function fd:format-dateTime-ZN-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("EST")
function fd:format-dateTime-ZN-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("GMT")
function fd:format-dateTime-ZN-zero($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("IST")
function fd:format-dateTime-ZN-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("+13:00")
function fd:format-dateTime-ZN-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[ZN]", (), (), "us")
};

declare
    %test:args("2012-06-26T12:00:00.000-10:00")
    %test:assertEquals("06:00 EST")
function fd:format-dateTime-ZN-NY-negative-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:args("2012-06-26T12:00:00.000-05:00")
    %test:assertEquals("12:00 EST")
function fd:format-dateTime-ZN-NY-negative-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:args("2012-06-26T12:00:00.000+00:00")
    %test:assertEquals("07:00 EST")
function fd:format-dateTime-ZN-NY-zero($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:args("2012-06-26T12:00:00.000+05:30")
    %test:assertEquals("01:30 EST")
function fd:format-dateTime-ZN-NY-positive-single-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:args("2012-06-26T12:00:00.000+13:00")
    %test:assertEquals("18:00 EST")
function fd:format-dateTime-ZN-NY-positive-double-digit($date as xs:dateTime) {
    format-dateTime($date, "[H00]:[M00] [ZN]", (), (), "America/New_York")
};

declare
    %test:args("17:45:50")
    %test:assertEquals("17:45:50")
    %test:args("09:45:50")
    %test:assertEquals("09:45:50")
function fd:simple-time($time as xs:time) {
    format-time($time, "[H00]:[m00]:[s]")
};

declare
    %test:args("17:45:50")
    %test:assertEquals("05:45 pm")
    %test:args("09:45:50")
    %test:assertEquals("09:45 am")
function fd:time-am-pm($time as xs:time) {
    format-time($time, "[h00]:[m00] [P]")
};

declare
    %test:assertError
function fd:date-format-in-format-time() {
    format-time(current-time(), "[Y]")
};

declare
    %test:assertError
function fd:time-format-in-format-date() {
    format-date(current-dateTime(), "[H]")
};

declare
    %test:args("2012-06-27T10:21:55.082+02:00")
    %test:assertEquals("Mittwoch, 27. Juni 2012")
    %test:args("1970-10-07T10:21:55.082+02:00")
    %test:assertEquals("Mittwoch, 7. Oktober 1970")
function fd:language($date as xs:dateTime) {
    format-date($date, "[FNn], [D1o] [MNn] [Y]", "de", (), ())
};

declare
    %test:args("2012-06-27T10:21:55.082+02:00")
    %test:assertEquals("Среда, 27 Июня 2012")
    %test:args("1970-10-07T10:21:55.082+02:00")
    %test:assertEquals("Среда, 7 Октября 1970")
function fd:language-ru($date as xs:dateTime) {
    format-date($date, "[FNn], [D1o] [MNn] [Y]", "ru", (), ())
};


Clicking on "Logout" led to an empty page. Take the user back to the login
page instead.

svn path=/trunk/eXist-1.0/; revision=3535

xquery version "1.0";

(:
    Main module of the database administration interface.
:)
declare namespace admin="http://exist-db.org/xquery/admin-interface";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace xdb="http://exist-db.org/xquery/xmldb";

import module namespace status="http://exist-db.org/xquery/admin-interface/status" at "status.xqm";
import module namespace browse="http://exist-db.org/xquery/admin-interface/browse" at "browse.xqm";
import module namespace users="http://exist-db.org/xquery/admin-interface/users" at "users.xqm";
import module namespace shut="http://exist-db.org/xquery/admin-interface/shutdown" at "shutdown.xqm";
import module namespace setup="http://exist-db.org/xquery/admin-interface/setup" at "setup.xqm";

(:
    Display the version and user info in the top right corner
:)
declare function admin:info-header($user as xs:string) as element() {

Version: {util:system-property("product-version")}

Build: {util:system-property("product-build")}

User: { $user}

};

(:
    Select the page to show. Every page is defined in its own module
:)
declare function admin:panel($user as xs:string, $pass as xs:string?) as element() {
    let $panel := request:get-parameter("panel", "status")
    return
        if($panel eq "browse") then
            browse:main($user, $pass)
        else if($panel eq "users") then
            users:main($user, $pass)
        else if($panel eq "shutdown") then
            shut:main($user, $pass)
        else if($panel eq "setup") then
            setup:main()
        else
            status:main()
};

(:
    Main function: display login form if no credentials have been supplied
    or logout is selected.

    $credentials is either an empty sequence or a pair (user, password).
:)
declare function admin:main($credentials as xs:string*) as element()+ {
    if(empty($credentials)) then
        admin:display-login-form()
    else
        admin:panel($credentials[1], $credentials[2])
};

(:~
    Display the login form.
:)
declare function admin:display-login-form() as element() {

Login

This is a protected resource. Only registered database users can log
        in. If you have not set up any users, login as "admin" and leave the
        password field empty. For testing purposes, you may also log in as
        "guest" with password "guest".

        <form action="{session:encode-url(request:get-uri())}">

                    Please Login

                    Username:
                    <input name="user" type="text" size="20"/>

                    Password:
                    <input name="pass" type="password" size="20"/>

                    <input type="submit"/>

        </form>

};

(:~  Try to authenticate the user name and password from
    the current HTTP session. Returns a pair of (user, password)
    on success, an empty sequence otherwise.
:)
declare function admin:checkUser() as xs:string* {
    let $user := session:get-attribute("user") ,
        $pass := session:get-attribute("password"),
        $login := xdb:authenticate("xmldb:exist:///db", $user, $pass)
    return
        if($login) then
            ($user, $pass)
        else
            ()
};

(:~
    Process user and password passed from the login form.
    Returns a pair of (user, password) if the credentials are
    valid, an empty sequence if not.
:)
declare function admin:doLogin($user as xs:string) as xs:string* {
    let $pass := request:get-parameter("pass", ""),
        $login := session:set-current-user($user, $pass)
    return
        if($login) then
            ($user, $pass)
        else
            ()
};

(:~
    Authenticate the user
:)
declare function admin:login() as xs:string* {
    let $userParam := request:get-parameter("user", ())
    return
        if($userParam) then
            admin:doLogin($userParam)
        else
            admin:checkUser()
};

session:create(),
let $logout := request:get-parameter("logout", ()),
    $s := if($logout) then session:invalidate() else session:create(),
    $credentials := admin:login(),
    $user := if(exists($credentials)) then $credentials[1] else "not logged in"
return

            <title>eXist Database Administration</title>
            <link type="text/css" href="admin.css" rel="stylesheet"/>

                {admin:info-header($user)}

Select a Page

Home

System Status

Browse Collections

Manage Users

Examples and Documentation Setup

Shutdown

Logout

                        Logged in as: {$user}

                {admin:main($credentials)}

xquery version "1.0";

(:
    Main module of the database administration interface.
:)
declare namespace admin="http://exist-db.org/xquery/admin-interface";
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace xdb="http://exist-db.org/xquery/xmldb";

import module namespace status="http://exist-db.org/xquery/admin-interface/status" at "status.xqm";
import module namespace browse="http://exist-db.org/xquery/admin-interface/browse" at "browse.xqm";
import module namespace users="http://exist-db.org/xquery/admin-interface/users" at "users.xqm";
import module namespace shut="http://exist-db.org/xquery/admin-interface/shutdown" at "shutdown.xqm";
import module namespace setup="http://exist-db.org/xquery/admin-interface/setup" at "setup.xqm";

(:
    Display the version and user info in the top right corner
:)
declare function admin:info-header($user as xs:string) as element() {

Version: {util:system-property("product-version")}

Build: {util:system-property("product-build")}

User: { $user}

};

(:
    Select the page to show. Every page is defined in its own module
:)
declare function admin:panel($user as xs:string, $pass as xs:string?) as element() {
    let $panel := request:get-parameter("panel", "status")
    return
        if($panel eq "browse") then
            browse:main($user, $pass)
        else if($panel eq "users") then
            users:main($user, $pass)
        else if($panel eq "shutdown") then
            shut:main($user, $pass)
        else if($panel eq "setup") then
            setup:main()
        else
            status:main()
};

(:
    Main function: display login form if no credentials have been supplied
    or logout is selected.

    $credentials is either an empty sequence or a pair (user, password).
:)
declare function admin:main($credentials as xs:string*) as element()+ {
    if(empty($credentials)) then
        admin:display-login-form()
    else
        admin:panel($credentials[1], $credentials[2])
};

(:~
    Display the login form.
:)
declare function admin:display-login-form() as element() {

Login

This is a protected resource. Only registered database users can log
        in. If you have not set up any users, login as "admin" and leave the
        password field empty. For testing purposes, you may also log in as
        "guest" with password "guest".

        <form action="{session:encode-url(request:get-uri())}">

                    Please Login

                    Username:
                    <input name="user" type="text" size="20"/>

                    Password:
                    <input name="pass" type="password" size="20"/>

                    <input type="submit"/>

        </form>

};

(:~  Try to authenticate the user name and password from
    the current HTTP session. Returns a pair of (user, password)
    on success, an empty sequence otherwise.
:)
declare function admin:checkUser() as xs:string* {
    let $user := session:get-attribute("user") ,
        $pass := session:get-attribute("password"),
        $login := xdb:authenticate("xmldb:exist:///db", $user, $pass)
    return
        if($login) then
            ($user, $pass)
        else
            ()
};

(:~
    Process user and password passed from the login form.
    Returns a pair of (user, password) if the credentials are
    valid, an empty sequence if not.
:)
declare function admin:doLogin($user as xs:string) as xs:string* {
    let $pass := request:get-parameter("pass", ""),
        $login := session:set-current-user($user, $pass)
    return
        if($login) then
            ($user, $pass)
        else
            ()
};

(:~
    Authenticate the user
:)
declare function admin:login() as xs:string* {
    let $userParam := request:get-parameter("user", ())
    return
        if($userParam) then
            admin:doLogin($userParam)
        else
            admin:checkUser()
};

if(request:get-parameter("logout", ()))then
(
    session:invalidate()
)
else
(
    session:create(),
    let $credentials := admin:login(),
    $user := if(exists($credentials)) then $credentials[1] else "not logged in" return

                <title>eXist Database Administration</title>
                <link type="text/css" href="admin.css" rel="stylesheet"/>

                    {admin:info-header($user)}

Select a Page

Home

System Status

Browse Collections

Manage Users

Examples Setup

Shutdown

Logout

                            Logged in as: {$user}

                    {admin:main($credentials)}

)


Added further order by example

Added further order by example

xquery version "3.0";

declare namespace other = "http://other";

declare variable $local:straight-var1 := 'one';

declare %private variable $local:private-var := 'secret';
declare %public variable $local:public-var := 'not-secret';
declare %other:annotation('param1', "param2") variable $local:some-var := 'anything';

declare variable $local:straight-var2 := 'two';

(: Simple Map Operator example :)
declare function local:word-count($elms as element()*) as xs:integer {
	sum($elms ! count(tokenize(., '\s+')))
};

declare function local:add($a, $b) {
	$a + $b
};

declare function local:dispatch($node as node()) as item()* {
    typeswitch($node)
        case text() return $node
        case comment() return $node
        case element(bill) return local:bill($node)
        case element(btitle) return local:btitle($node)
        case element(section-id) return local:section-id($node)
        case element(bill-text) return local:bill-text($node)
        case element(strike) return local:strike($node)
        default return local:passthru($node)
};

(: `switch` expression example :)
declare function local:noise($animal) {
	let $duck := "Duck",
	$quack := "Quack"
	return
		switch ($animal)
			case "Cow" return "Moo"
			case 'Cat' return 'Meow'
			case $duck return $quack
			default return "What's that odd noise?"
};

(: `group by` expression with binding example :)
declare function local:a-to-z() {
	let $data as element()* := (
		<item>Apples</item>,
		<item>Bananas</item>,
		<item>Apricots</item>,
		<item>Pears</item>,
		<item>Brambles</item>
	) return
		<GroupedItems>{
			for $item in $data
			group by $key := upper-case(substring($item, 1, 1))
			order by $key
			return
				<Group key="{$key}">{$item}</Group>
		}</GroupedItems>
};

(: `group by` expression example :)
declare function local:plays-by-character() {
	let $plays := (
		document {
			<play>
				<title>Hamlet</title>
				<characters>
					<character>Hamlet</character>
					<character>Claudius</character>
					<character>Polonius</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Francisco</character>
					<character>Reynaldo</character>
				</characters>
			</play>
		},
		document {
			<play>
				<title>Rosenkrantz and Guildenstern are Dead</title>
				<characters>
					<character>Alfred</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Hamlet</character>
					<character>Claudius</character>
				</characters>
			</play>
		}
	) return

		for $play in $plays/play
		let $title := $play/title
		for $character in $play/characters/character
		group by $character
		return
			<character name="{$character}">
			{
				$title ! <play>{ . }</play>
     		}
			</character>
};

declare
	%other:a
	%private
	%other:b('1')
	%other:c("1", "2", "3", "4")
function local:very-annotated() {
	let $thing := "thing"
	return
		$thing
};

declare %public function local:slightly-annotated() {
	let $nothing := ()
	return
		$nothing
};

declare function local:ordered() {
	for $hit in doc("/db/doc-with-indexes.xml")//tei:p[other:query(., $search-expression)]
	let $score as xs:float := other:score($hit)
	order by $score descending
	return (

Score: {$score}:
,
		other:summarize($hit, <config width="40"/>)
	)
};

declare function local:merge-simple($a as xs:string+, $b as xs:string+) as xs:string+ {
	($a, $b)
};

(: higher order function example 1 :)
declare function local:apply($func, $value) {
	$func($value)
};

(: higher order function example 2 :)
declare function local:apply-all($func, $list) {
	$list ! $func(.)
};

(: higher order function example 3 :)
declare function local:apply-all-long($func as function(xs:string) as xs:string, $list) {
	$list ! $func(.)
};

(: higher order function example 4 :)
declare function local:merge($func as function(xs:string+, xs:string+) as xs:string+, $a as xs:string+, $b as xs:string+) as xs:string+ {
	$func($a, $b)
};

let $to-upper := upper-case#1
let $to-upper-long as function(xs:string) as xs:string := upper-case#1
return
    <case>
    {
        local:apply-all($to-upper, ("Hello", "world!")) ! <upper>{.}</upper>,
        local:apply-all-long(lower-case#1, ("Hello", "world!")) ! <lower>{.}</lower>
    }
    </case>

xquery version "3.0";

declare namespace other = "http://other";

declare variable $local:straight-var1 := 'one';

declare %private variable $local:private-var := 'secret';
declare %public variable $local:public-var := 'not-secret';
declare %other:annotation('param1', "param2") variable $local:some-var := 'anything';

declare variable $local:straight-var2 := 'two';

(: Simple Map Operator example :)
declare function local:word-count($elms as element()*) as xs:integer {
	sum($elms ! count(tokenize(., '\s+')))
};

declare function local:add($a, $b) {
	$a + $b
};

declare function local:dispatch($node as node()) as item()* {
    typeswitch($node)
        case text() return $node
        case comment() return $node
        case element(bill) return local:bill($node)
        case element(btitle) return local:btitle($node)
        case element(section-id) return local:section-id($node)
        case element(bill-text) return local:bill-text($node)
        case element(strike) return local:strike($node)
        default return local:passthru($node)
};

(: `switch` expression example :)
declare function local:noise($animal) {
	let $duck := "Duck",
	$quack := "Quack"
	return
		switch ($animal)
			case "Cow" return "Moo"
			case 'Cat' return 'Meow'
			case $duck return $quack
			default return "What's that odd noise?"
};

(: `group by` expression with binding example :)
declare function local:a-to-z() {
	let $data as element()* := (
		<item>Apples</item>,
		<item>Bananas</item>,
		<item>Apricots</item>,
		<item>Pears</item>,
		<item>Brambles</item>
	) return
		<GroupedItems>{
			for $item in $data
			group by $key := upper-case(substring($item, 1, 1))
			order by $key
			return
				<Group key="{$key}">{$item}</Group>
		}</GroupedItems>
};

(: `group by` expression example :)
declare function local:plays-by-character() {
	let $plays := (
		document {
			<play>
				<title>Hamlet</title>
				<characters>
					<character>Hamlet</character>
					<character>Claudius</character>
					<character>Polonius</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Francisco</character>
					<character>Reynaldo</character>
				</characters>
			</play>
		},
		document {
			<play>
				<title>Rosenkrantz and Guildenstern are Dead</title>
				<characters>
					<character>Alfred</character>
					<character>Rosencrantz</character>
					<character>Guildenstern</character>
					<character>Hamlet</character>
					<character>Claudius</character>
				</characters>
			</play>
		}
	) return

		for $play in $plays/play
		let $title := $play/title
		for $character in $play/characters/character
		group by $character
		return
			<character name="{$character}">
			{
				$title ! <play>{ . }</play>
     		}
			</character>
};

declare
	%other:a
	%private
	%other:b('1')
	%other:c("1", "2", "3", "4")
function local:very-annotated() {
	let $thing := "thing"
	return
		$thing
};

declare %public function local:slightly-annotated() {
	let $nothing := ()
	return
		$nothing
};

declare function local:merge-simple($a as xs:string+, $b as xs:string+) as xs:string+ {
	($a, $b)
};

(: higher order function example 1 :)
declare function local:apply($func, $value) {
	$func($value)
};

(: higher order function example 2 :)
declare function local:apply-all($func, $list) {
	$list ! $func(.)
};

(: higher order function example 3 :)
declare function local:apply-all-long($func as function(xs:string) as xs:string, $list) {
	$list ! $func(.)
};

(: higher order function example 4 :)
declare function local:merge($func as function(xs:string+, xs:string+) as xs:string+, $a as xs:string+, $b as xs:string+) as xs:string+ {
	$func($a, $b)
};

let $to-upper := upper-case#1
let $to-upper-long as function(xs:string) as xs:string := upper-case#1
return
    <case>
    {
        local:apply-all($to-upper, ("Hello", "world!")) ! <upper>{.}</upper>,
        local:apply-all-long(lower-case#1, ("Hello", "world!")) ! <lower>{.}</lower>
    }
    </case>


[apidoc] Support generating the MarkLogic 8.0 apidoc function signatures.

(:
 : Copyright (C) 2020 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "3.1";

declare namespace apidoc = "http://marklogic.com/xdmp/apidoc";
declare namespace map = "http://www.w3.org/2005/xpath-functions/map";
declare namespace xhtml = "http://www.w3.org/1999/xhtml";

declare variable $apidoc as element(apidoc:apidoc) :=
    typeswitch (.)
    case xs:string return fn:parse-xml(.)/element()
    case document-node() return ./element()
    default return .;

declare variable $language as xs:string := "xquery"; (: xquery | javascript | rest :)

declare function local:apidoc-language($doc as element()) as xs:string {
    ($doc/@class, "xquery")[1]
};

(: namespaces -------------------------------------------------------------- :)

declare variable $module-namespaces := map:merge(
    for $import in $apidoc//apidoc:module/apidoc:summary//(*:p|*:pre)
    let $match := fn:analyze-string(($import/*:code, $import)[1], "import module (namespace\s*([a-z0-9]+)\s*=\s*)?""([^""]+)""")/fn:match[1]
    let $prefix := $import/ancestor::apidoc:module/@lib
    let $namespace := $match/fn:group[@nr = "3"]/string()
    where exists($namespace)
    return map:entry($prefix, $namespace)
);

declare variable $xquery-namespaces := map {
    "local": "http://www.w3.org/2005/xquery-local-functions",
    "fn": "http://www.w3.org/2005/xpath-functions",
    "xml": "http://www.w3.org/XML/1998/namespace",
    "xs": "http://www.w3.org/2001/XMLSchema",
    "xsi": "http://www.w3.org/2001/XMLSchema-instance"
};

declare variable $marklogic-5-builtin := map {
    "cts": "http://marklogic.com/cts",
    "dbg": "http://marklogic.com/xdmp/dbg",
    "dir": "http://marklogic.com/xdmp/directory",
    "error": "http://marklogic.com/xdmp/error",
    "map": "http://marklogic.com/xdmp/map",
    "math": "http://marklogic.com/xdmp/math",
    "prof": "http://marklogic.com/xdmp/profile",
    "sec": "http://marklogic.com/security",
    "spell": "http://marklogic.com/xdmp/spell",
    "xdmp": "http://marklogic.com/xdmp"
};

declare variable $marklogic-6-builtin := map {
    "err": "http://www.w3.org/2005/xqt-error"
};

declare variable $marklogic-7-builtin := map {
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "sc": "http://marklogic.com/xdmp/schema-components",
    "sql": "http://marklogic.com/xdmp/sql"
};

declare variable $marklogic-additional := map {
    "as": "http://marklogic.com/xdmp/assignments",
    "db": "http://marklogic.com/xdmp/database",
    "dg": "xdmp:document-get",
    "cl": "http://marklogic.com/xdmp/clusters",
    "exsl": "http://exslt.org/common",
    "extusr": "http://marklogic.com/xdmp/external/user",
    "gr": "http://marklogic.com/xdmp/group",
    "list": "http://marklogic.com/manage/package/list",
    "mt": "http://marklogic.com/xdmp/mimetypes",
    "pkg": "http://marklogic.com/manage/package",
    "s": "http://www.w3.org/2009/xpath-functions/analyze-string",
    "x509": "http://marklogic.com/xdmp/x509",
    "xdt": "http://www.w3.org/2004/10/xpath-datatypes",
    "xi": "http://www.w3.org/2001/XInclude"
};

declare variable $namespaces := map:merge((
    $module-namespaces,
    $xquery-namespaces,
    $marklogic-5-builtin,
    $marklogic-6-builtin,
    $marklogic-7-builtin,
    $marklogic-additional,
    ()
));

(: functions --------------------------------------------------------------- :)

(: Several functions in the apidocs have duplicate parameter names in some versions, so fix these. :)
declare variable $param-fixes := map {
    "fn:subtract-dateTimes-yielding-dayTimeDuration": ("srcval1", "srcval2"),
    "fn:subtract-dateTimes-yielding-yearMonthDuration": ("srcval1", "srcval2"),
    "geo:region-contains": ("target", "region", "options"),
    "math:fmod": ("x", "y"),
    "math:rank": ("arg1", "arg2", "options")
};

declare variable $functions as element(apidoc:function)* := $apidoc//apidoc:function[
    local:function-language(.) = $language and not(@name = "")
];

declare function local:function-language($function as element(apidoc:function)) as xs:string {
    let $bucket := $function/@bucket
    return switch ($bucket)
    case "REST Resources API" return "rest"
    default return local:apidoc-language($function)
};

declare function local:function-name($function as element(apidoc:function)) as xs:string {
    ``[`{$function/@lib}`:`{$function/@name}`]``
};

declare function local:function-parameters($function as element(apidoc:function)) as xs:string* {
    let $names as xs:string* :=
        let $names := map:get($param-fixes, local:function-name($function))
        return if (exists($names)) then
            $names
        else
            $function/apidoc:params/apidoc:param[local:apidoc-language(.) = $language]/@name/string()
    return if (count($names) != count(distinct-values($names))) then
        fn:error(xs:QName("err:XQST0039"),``[Duplicate parameter name in `{local:function-name($function)}`]``)
    else
        $names
};

declare function local:function-parameter($function as element(apidoc:function), $name as xs:string) as element(apidoc:param) {
    let $names := map:get($param-fixes, local:function-name($function))
    return if (exists($names)) then
        let $i := fn:index-of($names, $name)
        return $function/apidoc:params/apidoc:param[$i]
    else
        $function/apidoc:params/apidoc:param[@name = $name and local:apidoc-language(.) = $language]
};

declare function local:function-parameter-type($function as element(apidoc:function), $name as xs:string) as xs:string {
    if ($function/@lib = "exsl" and $function/@name = "object-type") then
        "item()*" (: MarkLogic 7 and earlier docs have this as 'atomic type'. :)
    else
        let $type := local:function-parameter($function, $name)/@type/string()
        return switch ($type)
        case "binary())" return "binary()"
        case "xs:string)" return "xs:string"
        case "(element()|map:map)?" case "element()?|map:map?" return "(element()?|map:map?)"
        case "(cts:order|xs:string)*" return "(cts:order*|xs:string*)"
        default return replace($type, ",\.\.\.", "...")
};

declare function local:function-return-type($function as element(apidoc:function)) as xs:string {
    let $type := normalize-space($function/apidoc:return[local:apidoc-language(.) = $language])
    return switch ($type)
    case "An XML representation of the certificate." return "element()?"
    case "element())" case "Element()" return "element()"
    case "element()|map:map" return "(element()|map:map)"
    case "xs:unsignedLong)" return "xs:unsignedLong"
    case "pkgins:install($pkgname)" return "element(pkg:install-status)"
    case "pkgins:revert($ticket)" return "element(pkg:revert-status)"
    case "The return data type is the data type of the date argument" return "item()"
    case "" return
        switch (local:function-name($function))
        case "admin:appserver-set-output-indent-tabs" return "element(configuration)"
        default return ""
    default return $type
};

declare function local:function-xquery-signatures($function as element(apidoc:function)) as xs:string* {
    let $name := local:function-name($function)
    let $params :=
        for $name in local:function-parameters($function)
        let $type := local:function-parameter-type($function, $name)
        return ``[$`{$name}` as `{$type}`]``
    let $type := local:function-return-type($function)
    return if ($type = "") then
        ``[declare function `{$name}`(`{string-join($params, ", ")}`) external;]``
    else
        ``[declare function `{$name}`(`{string-join($params, ", ")}`) as `{$type}` external;]``
};

(: query ------------------------------------------------------------------- :)

for $prefix in map:keys($namespaces)
let $namespace := map:get($namespaces, $prefix)
order by $prefix
return ``[declare namespace `{$prefix}` = "`{$namespace}`";]``
,
for $function in $functions
order by $function/@lib, $function/@name
return local:function-xquery-signatures($function)

(:
 : Copyright (C) 2020 Reece H. Dunn
 :
 : Licensed under the Apache License, Version 2.0 (the "License");
 : you may not use this file except in compliance with the License.
 : You may obtain a copy of the License at
 :
 : http://www.apache.org/licenses/LICENSE-2.0
 :
 : Unless required by applicable law or agreed to in writing, software
 : distributed under the License is distributed on an "AS IS" BASIS,
 : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 : See the License for the specific language governing permissions and
 : limitations under the License.
 :)
xquery version "3.1";

declare namespace apidoc = "http://marklogic.com/xdmp/apidoc";
declare namespace map = "http://www.w3.org/2005/xpath-functions/map";
declare namespace xhtml = "http://www.w3.org/1999/xhtml";

declare variable $apidoc as element(apidoc:apidoc) :=
    typeswitch (.)
    case xs:string return fn:parse-xml(.)/element()
    case document-node() return ./element()
    default return .;

declare variable $language as xs:string := "xquery"; (: xquery | rest :)

(: namespaces -------------------------------------------------------------- :)

declare variable $module-namespaces := map:merge(
    for $import in $apidoc//apidoc:module/apidoc:summary/(*:p|*:pre)
    let $match := fn:analyze-string(($import/*:code, $import)[1], "import module (namespace\s*([a-z0-9]+)\s*=\s*)?""([^""]+)""")/fn:match[1]
    let $prefix := $import/ancestor::apidoc:module/@lib
    let $namespace := $match/fn:group[@nr = "3"]/string()
    where exists($namespace)
    return map:entry($prefix, $namespace)
);

declare variable $xquery-namespaces := map {
    "local": "http://www.w3.org/2005/xquery-local-functions",
    "fn": "http://www.w3.org/2005/xpath-functions",
    "xml": "http://www.w3.org/XML/1998/namespace",
    "xs": "http://www.w3.org/2001/XMLSchema",
    "xsi": "http://www.w3.org/2001/XMLSchema-instance"
};

declare variable $marklogic-5-builtin := map {
    "cts": "http://marklogic.com/cts",
    "dbg": "http://marklogic.com/xdmp/dbg",
    "dir": "http://marklogic.com/xdmp/directory",
    "error": "http://marklogic.com/xdmp/error",
    "map": "http://marklogic.com/xdmp/map",
    "math": "http://marklogic.com/xdmp/math",
    "prof": "http://marklogic.com/xdmp/profile",
    "sec": "http://marklogic.com/security",
    "spell": "http://marklogic.com/xdmp/spell",
    "xdmp": "http://marklogic.com/xdmp"
};

declare variable $marklogic-6-builtin := map {
    "err": "http://www.w3.org/2005/xqt-error"
};

declare variable $marklogic-7-builtin := map {
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "sc": "http://marklogic.com/xdmp/schema-components",
    "sql": "http://marklogic.com/xdmp/sql"
};

declare variable $marklogic-additional := map {
    "as": "http://marklogic.com/xdmp/assignments",
    "db": "http://marklogic.com/xdmp/database",
    "dg": "xdmp:document-get",
    "cl": "http://marklogic.com/xdmp/clusters",
    "exsl": "http://exslt.org/common",
    "gr": "http://marklogic.com/xdmp/group",
    "list": "http://marklogic.com/manage/package/list",
    "mt": "http://marklogic.com/xdmp/mimetypes",
    "pkg": "http://marklogic.com/manage/package",
    "s": "http://www.w3.org/2009/xpath-functions/analyze-string",
    "x509": "http://marklogic.com/xdmp/x509",
    "xdt": "http://www.w3.org/2004/10/xpath-datatypes",
    "xi": "http://www.w3.org/2001/XInclude"
};

declare variable $namespaces := map:merge((
    $module-namespaces,
    $xquery-namespaces,
    $marklogic-5-builtin,
    $marklogic-6-builtin,
    $marklogic-7-builtin,
    $marklogic-additional,
    ()
));

(: functions --------------------------------------------------------------- :)

(: Several functions in the apidocs have duplicate parameter names in some versions, so fix these. :)
declare variable $param-fixes := map {
    "fn:subtract-dateTimes-yielding-dayTimeDuration": ("srcval1", "srcval2"),
    "fn:subtract-dateTimes-yielding-yearMonthDuration": ("srcval1", "srcval2"),
    "math:fmod": ("x", "y"),
    "math:rank": ("arg1", "arg2", "options")
};

declare variable $functions as element(apidoc:function)* := $apidoc//apidoc:function[
    local:function-language(.) = $language and not(@name = "")
];

declare function local:function-language($function as element(apidoc:function)) as xs:string {
    let $bucket := $function/@bucket
    return switch ($bucket)
    case "REST Resources API" return "rest"
    default return "xquery"
};

declare function local:function-name($function as element(apidoc:function)) as xs:string {
    ``[`{$function/@lib}`:`{$function/@name}`]``
};

declare function local:function-parameters($function as element(apidoc:function)) as xs:string* {
    let $names as xs:string* :=
        let $names := map:get($param-fixes, local:function-name($function))
        return if (exists($names)) then
            $names
        else
            $function/apidoc:params/apidoc:param/@name/string()
    return if (count($names) != count(distinct-values($names))) then
        fn:error(xs:QName("err:XQST0039"),``[Duplicate parameter name in `{local:function-name($function)}`]``)
    else
        $names
};

declare function local:function-parameter($function as element(apidoc:function), $name as xs:string) as element(apidoc:param) {
    let $names := map:get($param-fixes, local:function-name($function))
    return if (exists($names)) then
        let $i := fn:index-of($names, $name)
        return $function/apidoc:params/apidoc:param[$i]
    else
        $function/apidoc:params/apidoc:param[@name = $name]
};

declare function local:function-parameter-type($function as element(apidoc:function), $name as xs:string) as xs:string {
    if ($function/@lib = "exsl" and $function/@name = "object-type") then
        "item()*" (: MarkLogic 7 and earlier docs have this as 'atomic type'. :)
    else
        let $type := local:function-parameter($function, $name)/@type/string()
        return switch ($type)
        case "binary())" return "binary()"
        case "xs:string)" return "xs:string"
        default return replace($type, ",\.\.\.", "...")
};

declare function local:function-return-type($function as element(apidoc:function)) as xs:string {
    let $type := normalize-space($function/apidoc:return)
    return switch ($type)
    case "An XML representation of the certificate." return "element()?"
    case "element())" return "element()"
    case "xs:unsignedLong)" return "xs:unsignedLong"
    case "pkgins:install($pkgname)" return "element(pkg:install-status)"
    case "pkgins:revert($ticket)" return "element(pkg:revert-status)"
    case "The return data type is the data type of the date argument" return "item()"
    default return $type
};

declare function local:function-xquery-signatures($function as element(apidoc:function)) as xs:string* {
    let $name := local:function-name($function)
    let $params :=
        for $name in local:function-parameters($function)
        let $type := local:function-parameter-type($function, $name)
        return ``[$`{$name}` as `{$type}`]``
    let $type := local:function-return-type($function)
    return ``[declare function `{$name}`(`{string-join($params, ", ")}`) as `{$type}` external;]``
};

(: query ------------------------------------------------------------------- :)

for $prefix in map:keys($namespaces)
let $namespace := map:get($namespaces, $prefix)
order by $prefix
return ``[declare namespace `{$prefix}` = "`{$namespace}`";]``
,
for $function in $functions
order by $function/@lib, $function/@name
return local:function-xquery-signatures($function)


xquery scoping collChunks and chapter/letter/vol alignments with string-lengths and text snips


Fix visualize script

Fix visualize script

xquery version "3.1";

module namespace pogues="http://xml.insee.fr/schema/applis/pogues";
declare namespace pogmod = "http://id.insee.fr/apps/pogues-model";
declare namespace request = "http://exist-db.org/xquery/request";
declare namespace xmldb = "http://exist-db.org/xquery/xmldb";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare namespace rest="http://exquery.org/ns/restxq";
declare namespace functx = "http://www.functx.com";
declare namespace compression = "http://exist-db.org/xquery/compression";
declare namespace ngram = "http://exist-db.org/xquery/ngram";
declare namespace xf="http://www.w3.org/2002/xforms";
declare namespace xhtml="http://www.w3.org/1999/xhtml";
declare namespace http="http://expath.org/ns/http-client";
import module namespace common="http://www.insee.fr/collectes/commonstromae/common" at "/db/restxq/common/commonStromae.xqm";

(:************ Vizualise Questionnaire  *************:)

declare
%rest:GET
%rest:path("/visualize")
function pogues:get-visualize()  as item()+{
    let $mess:=<resultat><xqm>{'/visualize'}</xqm><message>{"It's work"}</message></resultat>
    return (common:rest-response(200),$mess)
};

(:************ Vizualise Questionnaire  *************:)

declare
  %rest:POST("{$body}")
  %rest:path("/visualize/{$dataCollection}/{$model}")
function pogues:post-publish ($body as node()*, $dataCollection as xs:string*, $model as xs:string*)
{
let $dataCollection := lower-case($dataCollection)
let $orbeon-root := '/db/orbeon/fr'
let $dataCollection-root := concat($orbeon-root,'/',$dataCollection)
let $model-root := concat($dataCollection-root,'/',$model)
let $model-form-folder := concat($model-root,'/form')
let $model-data-folder := concat($model-root,'/data')
let $model-data-init-folder := concat($model-data-folder,'/init')

let $unite := xs:string('123456789')
let $collection := xs:string('15')
let $model-data-init-collection-folder := concat($model-data-init-folder,'/',$collection)

let $ip_orbeon := doc('/db/properties.xml')/properties/host_orbeon/ip/text()
let $port_orbeon := doc('/db/properties.xml')/properties/host_orbeon/port/text()
let $url := concat('http://',$ip_orbeon,':',$port_orbeon,'/rmesstromae/fr/',$dataCollection,'/', $model, '/new?unite-enquete=',$unite)

return
( common:create-collection-if-necessary($dataCollection-root),
  common:create-collection-if-necessary($model-root),
  common:create-collection-if-necessary($model-form-folder),
  common:create-collection-if-necessary($model-data-folder),
  common:create-collection-if-necessary($model-data-init-folder),
  common:create-collection-if-necessary($model-data-init-collection-folder),
  xmldb:store($model-form-folder, 'form.xhtml', $body),
  xmldb:store($model-data-init-collection-folder, '123456789.xml', doc(concat($model-form-folder,'/form.xhtml'))//xf:instance[@id='fr-form-instance']/form),
<rest:response>
    <http:response status="200">
    	<http:header name="Access-Control-Allow-Headers" value="Location, Content-Type" />
    	<http:header name="Access-Control-Allow-Origin" value="*" />
    </http:response>
</rest:response>,
    $url
  )
}
;

xquery version "3.1";

module namespace pogues="http://xml.insee.fr/schema/applis/pogues";
declare namespace pogmod = "http://id.insee.fr/apps/pogues-model";
declare namespace request = "http://exist-db.org/xquery/request";
declare namespace xmldb = "http://exist-db.org/xquery/xmldb";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare namespace rest="http://exquery.org/ns/restxq";
declare namespace functx = "http://www.functx.com";
declare namespace compression = "http://exist-db.org/xquery/compression";
declare namespace ngram = "http://exist-db.org/xquery/ngram";
declare namespace xf="http://www.w3.org/2002/xforms";
declare namespace xhtml="http://www.w3.org/1999/xhtml";
declare namespace http="http://expath.org/ns/http-client";
import module namespace common="http://www.insee.fr/collectes/commonstromae/common" at "/db/restxq/common/commonStromae.xqm";

(:************ Vizualise Questionnaire  *************:)

declare
%rest:GET
%rest:path("/visualize")
function pogues:get-visualize()  as item()+{
    let $mess:=<resultat><xqm>{'/visualize'}</xqm><message>{"It's work"}</message></resultat>
    return (common:rest-response(200),$mess)
};

(:************ Vizualise Questionnaire  *************:)

declare
  %rest:POST("{$body}")
  %rest:path("/visualize/{$dataCollection}/{$model}")
function pogues:post-publish ($body as node()*, $dataCollection as xs:string*, $model as xs:string*)
{
let $dataCollection := lower-case($dataCollection)
let $orbeon-root := '/db/orbeon/fr'
let $dataCollection-root := concat($orbeon-root,'/',$dataCollection)
let $model-root := concat($dataCollection-root,'/',$model)
let $model-form-folder := concat($model-root,'/form')
let $model-data-folder := concat($model-root,'/data')
let $model-data-init-folder := concat($model-data-folder,'/init')
let $model-data-init-collection-folder := concat($model-data-init-folder,'/',$collection)

let $unite := xs:string('123456789')
let $collection := xs:string('15')

let $ip_orbeon := doc('/db/properties.xml')/properties/host_orbeon/ip/text()
let $port_orbeon := doc('/db/properties.xml')/properties/host_orbeon/port/text()
let $url := concat('http://',$ip_orbeon,':',$port_orbeon,'/rmesstromae/fr/',$dataCollection,'/', $model, '/new?unite-enquete=',$unite)

return
( common:create-collection-if-necessary($dataCollection-root),
  common:create-collection-if-necessary($model-root),
  common:create-collection-if-necessary($model-form-folder),
  common:create-collection-if-necessary($model-data-folder),
  common:create-collection-if-necessary($model-data-init-folder),
  common:create-collection-if-necessary($model-data-init-collection-folder),
  xmldb:store($model-form-folder, 'form.xhtml', $body),
  xmldb:store($model-data-init-collection-folder, '123456789.xml', doc(concat($model-form-folder,'/form.xhtml'))//xf:instance[@id='fr-form-instance']/form),
<rest:response>
    <http:response status="200">
    	<http:header name="Access-Control-Allow-Headers" value="Location, Content-Type" />
    	<http:header name="Access-Control-Allow-Origin" value="*" />
    </http:response>
</rest:response>,
    $url
  )
}
;


added self close in popup ; also single button selection in value domain

xquery version "1.0";

(: ~
: Module Name:             Relationship search popup
:
: Module Version           1.0
:
: Date                     15 jan 2008
:
: Copyright                The cagrid consortium
:
: Module overview          Finds a document to place on the end of a relationship
:
:)

(:~
:    @author Steve Harris
:    @version 1.0
~ :)

declare namespace request="http://exist-db.org/xquery/request";
declare namespace openMDR = "http://www.cagrid.org/schema/openMDR";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace exist = "http://exist.sourceforge.net/NS/exist";
declare namespace util="http://exist-db.org/xquery/util";

import module namespace
   lib-util="http://www.cagrid.org/xquery/library/util"
   at "../library/m-lib-util.xquery";

import module namespace
   administered-item="http://www.cagrid.org/xquery/library/administered-item"
   at "../library/m-administered-item.xquery";

import module namespace
  lib-forms="http://www.cagrid.org/xquery/library/forms"
  at "../edit/m-lib-forms.xquery";

import module namespace
  lib-rendering="http://www.cagrid.org/xquery/library/rendering"
  at "../web/m-lib-rendering.xquery";

declare function local:action-button($value as xs:string, $control as xs:string, $text as xs:string, $name as xs:string) as node()
{
   element input {
      attribute class {"cgButton"},
      attribute type {"button"},
      attribute name {"update"},
      attribute value {$text},
      attribute onclick {
         concat(
            "{window.opener.document.getElementById('", $control, "').value='",$value,"';",
            "window.opener.document.getElementById('", $control, "-div').innerHTML='",$name,"';","self.close();}")}
   }
};

declare function local:action-button($value as xs:string, $control as xs:string, $text as xs:string,
$name as xs:string, $form-name as xs:string) as node()
{
   element input {
      attribute class {"cgButton"},
      attribute type {"submit"},
      attribute name {"update"},
      attribute value {$text},

      if($form-name > '') then (
          attribute onclick {
             concat(
                "{window.opener.document.getElementById('", $control, "').value='",$value,"';",
                "window.opener.document.getElementById('", $control, "-div').innerHTML='",$name,"';",
                "window.opener.document.", $form-name, ".submit();", "self.close();}")}
      )
      else(
      attribute onclick {
         concat(
            "{window.opener.document.getElementById('", $control, "').value='",$value,"';",
            "window.opener.document.getElementById('", $control, "-div').innerHTML='",$name,"';","self.close();}")}
      )
   }
};

declare function local:cancel-button($form-name as xs:string, $control as xs:string, $value as xs:string, $text as xs:string) as node()
{
   element input {
      attribute class {"cgButton"},
      attribute type {"submit"},
      attribute name {"update"},
      attribute value {$text},
      util:log-system-out(concat("cbutton : ",session:get-attribute("old_cd_id")) ),
      if(session:get-attribute("old_cd_id") > '') then(
        attribute onclick {
            concat(
                "{window.opener.document.getElementById('", $control, "').value='",$value,"';",
                "window.opener.document.new_value_domain.submit();", "self.close();}") }
      )
      else(
        attribute onclick {
         concat(
            "{window.opener.document.getElementById('", $control, "').value='';",
            "window.opener.document.new_value_domain.submit();", "self.close();}") }
      )
   }
};
declare function local:popup-close($form-name as xs:string, $control as xs:string, $value as xs:string)
{
      if(session:get-attribute("old_cd_id") > '') then(
        attribute onunload {
            concat(
                "{window.opener.document.getElementById('", $control, "').value='", $value, "';",
                "window.opener.document.", $form-name, ".submit();}") }
      )
      else(
        attribute onunload {
         concat(
            "{window.opener.document.getElementById('", $control, "').value='';",
            "window.opener.document.", $form-name, ".submit();}") }
      )

};

declare option exist:serialize "media-type=text/html method=xhtml doctype-public=-//W3C//DTD XHTML 1.0 Transitional//EN doctype-system=http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd";

session:create(),
let $phrase as xs:string := xs:string(request:get-parameter("phrase", ""))
let $type as xs:string := xs:string(request:get-parameter("type", ""))
let $control as xs:string := xs:string(request:get-parameter("control", ""))
let $start as xs:integer := xs:integer(request:get-parameter("start", "1"))
let $count as xs:integer := xs:integer(request:get-parameter("count", "10"))
let $form-name as xs:string := xs:string(request:get-parameter("form-name", ""))

return

         <title>Searching for a {$type}</title>
                <link rel="stylesheet" href="../web/stylesheets/main.css" type="text/css"/>
                <link rel="stylesheet" href="../web/stylesheets/mdr.css" type="text/css"/>
                <link rel="stylesheet" href="../web/stylesheets/cagrid-style.css" type="text/css"/>
                <link rel="stylesheet" href="../classification/stylesheets/treeview.css" type="text/css"/>
                <link rel="search" type="application/opensearchdescription+xml" title="OpenMDR Data Element Search" href="../web/cde_search.xquery"/>

         {local:popup-close($form-name, $control, "Cancel")}
         <form name='select-item' class='cagridForm' action='popup-search-relationship.xquery'>
            <input type='hidden' name='type' value='{$type}'/>
            <input type='hidden' name='control' value='{$control}'/>

                  Search Phrase
                  <input type='text' name='phrase' value='{$phrase}'/>
                  <input type="submit" value="Submit query" class="cgButton"/>

               {
               let $documents := lib-util:search($type, $phrase)

               let $count-docs := count($documents)
               return
               (
                  for $document at $pos in $documents
                  let $id := lib-util:mdrElementId($document)
                  let $name := administered-item:preferred-name($document)
                  where $pos >= $start and $pos < $start + $count
                  return element tr {
                        element td {$id},
                        element td {$name},
                        element td {
                        local:action-button($id, $control, "use this document",$name, $form-name)
                        }
                     },

                        {
                        if ($start > 1)
                        then
                           start
                        else()
                        }

                     {
                     if ($start > 1)
                     then (
                       element a {
                           attribute href {
                              concat("popup-search-relationship.xquery?start=",
                                 $start - $count,
                                 "&control=",
                                 $control,
                                 "&phrase=",
                                 $phrase,
                                 "&type=",
                                 $type)
                                 },
                           'previous'
                           }
                        )
                     else()
                     }

                     {
                        if ($count-docs > $start + $ count)
                        then
                           element a {
                              attribute href {
                                 concat("popup-search-relationship.xquery?start=",
                                    $start+$count,
                                    "&control=",
                                    $control,
                                    "&phrase=",
                                    $phrase,
                                    "&type=",
                                    $type)
                                    },
                              'next'}
                        else ()
                        }

                  )
                  }

         </form>

xquery version "1.0";

(: ~
: Module Name:             Relationship search popup
:
: Module Version           1.0
:
: Date                     15 jan 2008
:
: Copyright                The cagrid consortium
:
: Module overview          Finds a document to place on the end of a relationship
:
:)

(:~
:    @author Steve Harris
:    @version 1.0
~ :)

declare namespace request="http://exist-db.org/xquery/request";
declare namespace openMDR = "http://www.cagrid.org/schema/openMDR";
declare namespace session="http://exist-db.org/xquery/session";

import module namespace
   lib-util="http://www.cagrid.org/xquery/library/util"
   at "../library/m-lib-util.xquery";

import module namespace
   administered-item="http://www.cagrid.org/xquery/library/administered-item"
   at "../library/m-administered-item.xquery";

import module namespace
  lib-forms="http://www.cagrid.org/xquery/library/forms"
  at "../edit/m-lib-forms.xquery";

import module namespace
  lib-rendering="http://www.cagrid.org/xquery/library/rendering"
  at "../web/m-lib-rendering.xquery";

declare function local:action-button($value as xs:string, $control as xs:string, $text as xs:string, $name as xs:string) as node()
{
   element input {
      attribute class {"cgButton"},
      attribute type {"button"},
      attribute name {"update"},
      attribute value {$text},
      attribute onclick {
         concat(
            "{window.opener.document.getElementById('", $control, "').value='",$value,"';",
            "window.opener.document.getElementById('", $control, "-div').innerHTML='",$name,"';",
            "self.close();}")}
   }
};

declare option exist:serialize "media-type=text/html method=xhtml doctype-public=-//W3C//DTD XHTML 1.0 Transitional//EN doctype-system=http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd";

session:create(),
let $phrase as xs:string := xs:string(request:get-parameter("phrase", ""))
let $type as xs:string := xs:string(request:get-parameter("type", ""))
let $control as xs:string := xs:string(request:get-parameter("control", ""))
let $start as xs:integer := xs:integer(request:get-parameter("start", "1"))
let $count as xs:integer := xs:integer(request:get-parameter("count", "10"))

return

         <title>Searching for a {$type}</title>
                <link rel="stylesheet" href="../web/stylesheets/main.css" type="text/css"/>
                <link rel="stylesheet" href="../web/stylesheets/mdr.css" type="text/css"/>
                <link rel="stylesheet" href="../web/stylesheets/cagrid-style.css" type="text/css"/>
                <link rel="stylesheet" href="../classification/stylesheets/treeview.css" type="text/css"/>
                <link rel="search" type="application/opensearchdescription+xml" title="OpenMDR Data Element Search" href="../web/cde_search.xquery"/>

         <form name='select-item' class='cagridForm' action='popup-search-relationship.xquery'>
            <input type='hidden' name='type' value='{$type}'/>
            <input type='hidden' name='control' value='{$control}'/>

                  Search Phrase
                  <input type='text' name='phrase' value='{$phrase}'/>
                  <input type="submit" value="Submit query" class="cgButton"/>

               {
               let $documents := lib-util:search($type, $phrase)

               let $count-docs := count($documents)
               return
               (
                  for $document at $pos in $documents
                  let $id := lib-util:mdrElementId($document)
                  let $name := administered-item:preferred-name($document)
                  where $pos >= $start and $pos < $start + $count
                  return element tr {
                        element td {$id},
                        element td {$name},
                        element td {
                        local:action-button($id, $control, "use this document",$name)
                        }
                     },

                        {
                        if ($start > 1)
                        then
                           start
                        else()
                        }

                     {
                     if ($start > 1)
                     then (
                       element a {
                           attribute href {
                              concat("popup-search-relationship.xquery?start=",
                                 $start - $count,
                                 "&control=",
                                 $control,
                                 "&phrase=",
                                 $phrase,
                                 "&type=",
                                 $type)
                                 },
                           'previous'
                           }
                        )
                     else()
                     }

                     {
                        if ($count-docs > $start + $ count)
                        then
                           element a {
                              attribute href {
                                 concat("popup-search-relationship.xquery?start=",
                                    $start+$count,
                                    "&control=",
                                    $control,
                                    "&phrase=",
                                    $phrase,
                                    "&type=",
                                    $type)
                                    },
                              'next'}
                        else ()
                        }

                  )
                  }

         </form>


fix for an accidential commit of the xqdoc script

module namespace xhtml = "http://www.zorba-xquery.com/modules/internal/xqdoc-xhtml";

import module namespace util = "http://www.zorba-xquery.com/zorba/util-functions";

declare namespace xqdoc = "http://www.xqdoc.org/1.0";

declare function xhtml:doc($xqdoc)
{
    {
        xhtml:header($xqdoc),
        xhtml:body($xqdoc)
    }
};

declare function xhtml:header($xqdoc)
{

        <title>Documentation for {xhtml:module-uri($xqdoc)}</title>
        <link rel="stylesheet" type="text/css" href="" />

};

declare function xhtml:body($xqdoc)
{

{xhtml:module-uri($xqdoc)}

        {
            xhtml:module-description($xqdoc/xqdoc:module),
            xhtml:module-variables($xqdoc/xqdoc:variables),
            xhtml:module-function-summary($xqdoc/xqdoc:functions),
            xhtml:module-functions($xqdoc/xqdoc:functions)
        }

};

declare function xhtml:module-uri($xqdoc) as xs:string
{
    $xqdoc/xqdoc:module/xqdoc:uri/text()
};

declare function xhtml:parameters($comment) {
    let $params := $comment/xqdoc:param
    return
        if (exists($params)) then (

Parameters:
,
            for $param in $params
            let $text := data($param)
            return
                if (starts-with($text, "$")) then
                    let $name := substring-before($text, " ")
                    let $description := substring-after($text, " ")
                    return

                            {$name}
                             -
                            {$description}

                else
                    ()
        ) else ()
};

declare function xhtml:errors($comment) {
    let $errors := $comment/xqdoc:error
    return
        if (exists($errors)) then (

Errors
,
            for $error in $errors
            return

                        {$error/node()}

        ) else ()
};

declare function xhtml:annotations($comment) {
    let $annotations := $comment/xqdoc:*[not((local-name(.) = ("description", "param", "return", "error")))]
    return
        for $annotation in $annotations
        return (

{
                let $annName := local-name($annotation)
                return
                    concat(upper-case(substring($annName, 1, 1)), substring($annName, 2), ":")
            }
,

{$annotation/node()}

        )
};

declare function xhtml:return($comment) {
    let $return := $comment/xqdoc:return
    return
        if (exists($return)) then (

Returns:
,

{$return/node()}

        ) else ()
};

declare function xhtml:description($comment)
{

{
        if($comment/xqdoc:description) then
           {$comment/xqdoc:description/node()}
        else
            "No description available."
     }

};

declare function xhtml:module-description($module)
{
    (
Module Description
,
     xhtml:description($module/xqdoc:comment),
     xhtml:annotations($module/xqdoc:comment))
};

declare function xhtml:module-variables($variables)
{
    if($variables/xqdoc:variable) then
        (
Variables
,
        for $variable in $variables/xqdoc:variable
        return (
{$variable/xqdoc:uri}
,
                xhtml:description($variable/xqdoc:comment),
                xhtml:annotations($variable/xqdoc:comment))
        )
    else
        ()
};

declare function xhtml:module-function-summary($functions)
{

Function Summary
,
    if(count($functions/xqdoc:function)) then

{
            for $function in $functions/xqdoc:function
            let $name := $function/xqdoc:name/text(),
                $signature := $function/xqdoc:signature/text(),
                $param-number := count(tokenize($signature, "\$")) - 1
            order by $name, $param-number
            return
                let $type := normalize-space(substring-after(substring-before($signature, "function"), "declare")),
                    $isExternal := ends-with($signature, "external"),
                    $paramsAndReturn :=
                        let $searchCrit := concat(":", $name)
                        return
                            if ($isExternal)
                                then normalize-space(substring-before(substring-after($signature, $searchCrit), "external"))
                                else normalize-space(substring-after($signature, $searchCrit))
                return

                        {$type}

{$name}{$paramsAndReturn}

        }

    else

No functions declared.

};

declare function xhtml:module-functions($functions) {
    if(count($functions/xqdoc:function)) then (

Functions
,
        for $function in $functions/xqdoc:function
        let $name := $function/xqdoc:name/text(),
            $signature := $function/xqdoc:signature/text(),
            $param-number := count(tokenize($signature, "\$")) - 1,
            $comment := $function/xqdoc:comment
        return (

{$name}
,

{xhtml:split-function-signature($signature)}
,
            xhtml:description($comment),
            xhtml:parameters($comment),
            xhtml:return($comment),
            xhtml:errors($comment),
            xhtml:annotations($comment),

)
         )
    else ()
};

declare function xhtml:split-function-signature($signature as xs:string) {
    let $line1 := substring-before($signature, "(")
    let $rest := substring-after($signature, "(")
    let $params :=
        (: if the function has parameter :)
        if (matches($rest, "\$")) then
            let $tmp := substring-before($rest, ") as ")
            return
                (: if we don't have a return type specified :)
                if ($tmp eq "") then
                    (: en external function declaration :)
                    if (ends-with($rest, ") external")) then
                        substring-before($rest, ") external")
                    (: no external function :)
                    else
                        $rest
                (: the return type is specified :)
                else
                    $tmp
        (: no parameters :)
        else
            ""
    let $after := substring-after($signature, concat($params, ")"))
    return (
        concat($line1, " ("),

,
        for $param at $pos in tokenize($params, "\$")
        where $pos > 1
        return (
            concat("            $", normalize-space($param)),

        ),
        concat(")", $after)
    )
};

module namespace xhtml = "http://www.zorba-xquery.com/modules/internal/xqdoc-xhtml";

import module namespace util = "http://www.zorba-xquery.com/zorba/util-functions";

declare namespace xqdoc = "http://www.xqdoc.org/1.0";

declare function xhtml:doc($xqdoc)
{
    {
        xhtml:header($xqdoc),
        xhtml:body($xqdoc)
    }
};

declare function xhtml:header($xqdoc)
{

        <title>Documentation for {xhtml:module-uri($xqdoc)}</title>
        <link rel="stylesheet" type="text/css" href="" />

};

declare function xhtml:body($xqdoc)
{

{xhtml:module-uri($xqdoc)}

        {
            xhtml:module-description($xqdoc/xqdoc:module),
            xhtml:module-variables($xqdoc/xqdoc:variables),
            xhtml:module-function-summary($xqdoc/xqdoc:functions),
            xhtml:module-functions($xqdoc/xqdoc:functions)
        }

};

declare function xhtml:module-uri($xqdoc) as xs:string
{
    $xqdoc/xqdoc:module/xqdoc:uri/text()
};

declare function xhtml:parameters($comment) {
    let $params := $comment/xqdoc:param
    return
        if (exists($params)) then (

Parameters:
,
            for $param in $params
            let $text := data($param)
            return
                if (starts-with($text, "$")) then
                    let $name := substring-before($text, " ")
                    let $description := substring-after($text, " ")
                    return

                            {$name}
                             -
                            {$description/node()}

                else
                    ()
        ) else ()
};

declare function xhtml:errors($comment) {
    let $errors := $comment/xqdoc:error
    return
        if (exists($errors)) then (

Errors
,
            for $error in $errors
            return

                        {$error/node()}

        ) else ()
};

declare function xhtml:annotations($comment) {
    let $annotations := $comment/xqdoc:*[not((local-name(.) = ("description", "param", "return", "error")))]
    return
        for $annotation in $annotations
        return (

{
                let $annName := local-name($annotation)
                return
                    concat(upper-case(substring($annName, 1, 1)), substring($annName, 2), ":")
            }
,

{$annotation/node()}

        )
};

declare function xhtml:return($comment) {
    let $return := $comment/xqdoc:return
    return
        if (exists($return)) then (

Returns:
,

{$return/node()}

        ) else ()
};

declare function xhtml:description($comment)
{

{
        if($comment/xqdoc:description) then
           {$comment/xqdoc:description/node()}
        else
            "No description available."
     }

};

declare function xhtml:module-description($module)
{
    (
Module Description
,
     xhtml:description($module/xqdoc:comment),
     xhtml:annotations($module/xqdoc:comment))
};

declare function xhtml:module-variables($variables)
{
    if($variables/xqdoc:variable) then
        (
Variables
,
        for $variable in $variables/xqdoc:variable
        return (
{$variable/xqdoc:uri}
,
                xhtml:description($variable/xqdoc:comment),
                xhtml:annotations($variable/xqdoc:comment))
        )
    else
        ()
};

declare function xhtml:module-function-summary($functions)
{

Function Summary
,
    if(count($functions/xqdoc:function)) then

{
            for $function in $functions/xqdoc:function
            let $name := $function/xqdoc:name/text(),
                $signature := $function/xqdoc:signature/text(),
                $param-number := count(tokenize($signature, "\$")) - 1
            order by $name, $param-number
            return
                let $type := normalize-space(substring-after(substring-before($signature, "function"), "declare")),
                    $isExternal := ends-with($signature, "external"),
                    $paramsAndReturn :=
                        let $searchCrit := concat(":", $name)
                        return
                            if ($isExternal)
                                then normalize-space(substring-before(substring-after($signature, $searchCrit), "external"))
                                else normalize-space(substring-after($signature, $searchCrit))
                return

                        {$type}

{$name}{$paramsAndReturn}

        }

    else

No functions declared.

};

declare function xhtml:module-functions($functions) {
    if(count($functions/xqdoc:function)) then (

Functions
,
        for $function in $functions/xqdoc:function
        let $name := $function/xqdoc:name/text(),
            $signature := $function/xqdoc:signature/text(),
            $param-number := count(tokenize($signature, "\$")) - 1,
            $comment := $function/xqdoc:comment
        return (

{$name}
,

{xhtml:split-function-signature($signature)}
,
            xhtml:description($comment),
            xhtml:parameters($comment),
            xhtml:return($comment),
            xhtml:errors($comment),
            xhtml:annotations($comment),

)
         )
    else ()
};

declare function xhtml:split-function-signature($signature as xs:string) {
    let $line1 := substring-before($signature, "(")
    let $rest := substring-after($signature, "(")
    let $params :=
        (: if the function has parameter :)
        if (matches($rest, "\$")) then
            let $tmp := substring-before($rest, ") as ")
            return
                (: if we don't have a return type specified :)
                if ($tmp eq "") then
                    (: en external function declaration :)
                    if (ends-with($rest, ") external")) then
                        substring-before($rest, ") external")
                    (: no external function :)
                    else
                        $rest
                (: the return type is specified :)
                else
                    $tmp
        (: no parameters :)
        else
            ""
    let $after := substring-after($signature, concat($params, ")"))
    return (
        concat($line1, " ("),

,
        for $param at $pos in tokenize($params, "\$")
        where $pos > 1
        return (
            concat("            $", normalize-space($param)),

        ),
        concat(")", $after)
    )
};