add media-type

add media-type

(:~
: trees as svg
: @author andy bunce
: @since sept 2012
:)

module namespace web = 'apb.hedge.web';
declare default function namespace 'apb.hedge.web';
import module namespace tree = 'apb.tree' at "hedgetree/treedraw.xqm";
declare namespace rest = 'http://exquery.org/ns/restxq';

(:~
: main page
:)
declare
%rest:GET %rest:path("hedge")
%output:method("html5")
%rest:form-param("hedge","{$hedge}")
%rest:form-param("url","{$url}")
function hedge($hedge,$url) {
	let $ehedge:=if($url) then "" else fn:encode-for-uri($hedge)
	let $xml:=getxml($hedge,$url)
	let $layout:=tree:layout($xml)
	let $svg:=tree:svg($layout)

	return

		<title>Drawing trees with XQuery and SVG</title>
		<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="description" content="tree xquery svg" />

Drawing trees with XQuery and SVG

Enter a  string representing a tree in the form below; use letters for nodes and () to enclose subnodes. Use {{...}} for multi character names. {{name|href}} will create a link. Examples: a(bcd(ef)),
                  another
		buggy: a(bcd)e(fgh).

 Or enter a Url to a xml document examples:
		sample1,
	hedgeweb
	remote

		 <form method="get" action="./hedge" style="background-color:#EEEEEE;padding:8px;">

		 <textarea name="hedge" rows="2" cols="80">{$hedge}</textarea>

Or enter the url to a node XML source
		 <input name="url"  value="{$url}" style="width:30em"/>

		 <button type="submit">Redraw</button>
		</form >

Inline SVG

{$svg}

Object referencing svg,
		( download svg)

		<object height="150" width="300" data="hedge/svg?hedge={$ehedge}&url={$url}"
		style="border:5px solid red;" type="image/svg+xml">
		SVG Here
		</object>

SVG xml

		 {fn:serialize($svg)}

Layout xml

		 {fn:serialize($layout)}

Tree xml

		 {fn:serialize($xml)}

About

 Source: @github:, Twitter:
     Tweet
.

};

(:~
: @param hedge
: @param url option location of node xml to use instead of hedge
: @param dl if present add header to force browser download
: @return svg for hedge with download option. cors header
:)
declare
%rest:GET %rest:path("hedge/svg")
%rest:form-param("hedge","{$hedge}")
%rest:form-param("url","{$url}")
%rest:form-param("dl","{$dl}")
%output:media-type("image/svg+xml")
function hedge-svg($hedge,$url,$dl) {
	let $xml:=getxml($hedge,$url)
	let $layout:=tree:layout($xml)
	let $svg:=tree:svg($layout)
	let $resp:=<rest:response>
            <http:response>
            <http:header name="Access-Control-Allow-Origin" value="*"/>
            {if($dl)
            then <http:header name="Content-Disposition" value='attachment;filename="hedge.svg"'/>
            else ()}
           </http:response>
       </rest:response>
	return ($resp,$svg)
};

(:~  use hedge or url :)
declare %private function getxml($hedge,$url){
 if($url) then
    try{fn:doc(fn:resolve-uri($url))/*} catch * { <node label="{$err:description}"/>}
else
	try{ tree:hedge2xml($hedge)} catch * { <node label="{$err:description}"/>}
};

(:~
: trees as svg
: @author andy bunce
: @since sept 2012
:)

module namespace web = 'apb.hedge.web';
declare default function namespace 'apb.hedge.web';
import module namespace tree = 'apb.tree' at "hedgetree/treedraw.xqm";
declare namespace rest = 'http://exquery.org/ns/restxq';

(:~
: main page
:)
declare
%rest:GET %rest:path("hedge")
%output:method("html5")
%rest:form-param("hedge","{$hedge}")
%rest:form-param("url","{$url}")
function hedge($hedge,$url) {
	let $ehedge:=if($url) then "" else fn:encode-for-uri($hedge)
	let $xml:=getxml($hedge,$url)
	let $layout:=tree:layout($xml)
	let $svg:=tree:svg($layout)

	return

		<title>Drawing trees with XQuery and SVG</title>
		<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta name="description" content="tree xquery svg" />

Drawing trees with XQuery and SVG

Enter a  string representing a tree in the form below; use letters for nodes and () to enclose subnodes. Use {{...}} for multi character names. {{name|href}} will create a link. Examples: a(bcd(ef)),
                  another
		buggy: a(bcd)e(fgh).

 Or enter a Url to a xml document examples:
		sample1,
	hedgeweb
	remote

		 <form method="get" action="./hedge" style="background-color:#EEEEEE;padding:8px;">

		 <textarea name="hedge" rows="2" cols="80">{$hedge}</textarea>

Or enter the url to a node XML source
		 <input name="url"  value="{$url}" style="width:30em"/>

		 <button type="submit">Redraw</button>
		</form >

Inline SVG

{$svg}

Object referencing svg,
		( download svg)

		<object height="150" width="300" data="hedge/svg?hedge={$ehedge}&url={$url}"
		style="border:5px solid red;" type="image/svg+xml">
		SVG Here
		</object>

SVG xml

		 {fn:serialize($svg)}

Layout xml

		 {fn:serialize($layout)}

Tree xml

		 {fn:serialize($xml)}

About

 Source: @github:, Twitter:
     Tweet
.

};

(:~ @return svg for hedge with download option. cors header
:)
declare
%rest:GET %rest:path("hedge/svg")
%rest:form-param("hedge","{$hedge}")
%rest:form-param("url","{$url}")
%rest:form-param("dl","{$dl}")
function hedge-svg($hedge,$url,$dl) {
	let $xml:=getxml($hedge,$url)
	let $layout:=tree:layout($xml)
	let $svg:=tree:svg($layout)
	let $resp:=<rest:response>
            <http:response>
            <http:header name="Access-Control-Allow-Origin" value="*"/>
            {if($dl)
            then <http:header name="Content-Disposition" value='attachment;filename="hedge.svg"'/>
            else ()}
           </http:response>
       </rest:response>
	return ($resp,$svg)
};

(:~  use hedge or url :)
declare %private function getxml($hedge,$url){
 if($url) then
    try{fn:doc(fn:resolve-uri($url))/*} catch * { <node label="{$err:description}"/>}
else
	try{ tree:hedge2xml($hedge)} catch * { <node label="{$err:description}"/>}
};


added documentation to private functions

jsoniq version "1.0";

(:
 : Copyright 2006-2012 The FLWOR Foundation.
 :
 : 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.
:)

(:~
 : This module provides the functions defined by the JSONiq specification,
 : chapter 8 (Function Library). JSONiq extends
 : the XQuery specification to also deal with JSON data natively. See
 :
 :     http://jsoniq.org/
 :
 : for details.
 :
 : @author Ghislain Fourny
 : @project JSONiq/Function Library
 :)
module namespace libjn = "http://jsoniq.org/function-library";

import module namespace jn = "http://jsoniq.org/functions";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 : This function dynamically builds an object, like the {||} syntax, except that
 : it does not throw an error upon pair collision. Instead, it accumulates them
 : into an array, if more than one.
 :
 : @param $items A sequence of items, the objects of which are going to be
 :        accumulated into a single object.
 : @return The accumulated object.
 :)
declare function libjn:accumulate($items as item()*) as object()
{
  {[ $items ]}
};

(:~
 : This function returns all arrays contained at any depth within a sequence of items.
 :
 : @param $items A sequence of items.
 : @return The descendant arrays of the input sequence.
 :)
declare function libjn:descendant-arrays($items as item()*) as array()*
{
  for $i in $items
  return libjn:descendant-arrays-priv($i)
};

(:~
 : Helper function for libjn:descendant-arrays()
 :
 : @param $i An item
 : @return The descendant arrays of the item
 :)
declare %private function libjn:descendant-arrays-priv($i as item()) as array()*
{
  typeswitch ($i)

  case object() return
    for $v in libjn:values($i)
    where $v instance of json-item()
    return libjn:descendant-arrays-priv($v)

  case array() return
    (
    $i,
    for $v in $i[]
    where $v instance of json-item()
    return libjn:descendant-arrays-priv($v)
    )

  default return
    ()
};

(:~
 : This function returns all objects contained at any depth within a sequence of items.
 :
 : @param $items A sequence of items.
 : @return The descendant objects of the input sequence.
 :)
declare function libjn:descendant-objects($items as item()*) as object()*
{
  for $i in $items
  return libjn:descendant-objects-priv($i)
};

(:~
 : Helper function for libjn:descendant-objects()
 :
 : @param $i An item
 : @return The descendant objects of the item
 :)
declare %private function libjn:descendant-objects-priv($i as item()) as object()*
{
  if ($i instance of object())
  then
    (
      $i,
      for $v in libjn:values($i)
      where $v instance of json-item()
      return libjn:descendant-objects-priv($v)
    )
  else if ($i instance of array())
  then
    (
      for $v in $i[]
      where $v instance of json-item()
      return libjn:descendant-objects-priv($v)
    )
  else
    ()
};

(:~
 : This function returns all pairs contained at any depth within an sequence of items.
 :
 : @param $o An object.
 : @return All direct and indirect descendant pairs.
 :)
declare function libjn:descendant-pairs($items as item()*) as object()*
{
  for $i in $items
  return libjn:descendant-pairs-priv($i)
};

(:~
 : Helper function for libjn:descendant-pairs()
 :
 : @param $i An item
 : @return The descendant pairs of the item
 :)
declare function libjn:descendant-pairs-priv($i as item()) as object()*
{
  typeswitch ($i)

  case $o as object() return
    for $k in jn:keys($o)
    return
      (
      { $k : $o($k) },
      libjn:descendant-pairs-priv($o($k))
      )

  case $a as array() return
    for $i in $a[]
    where $i instance of json-item()
    return libjn:descendant-pairs-priv($i)

  default return
    ()
};

(:~
 : This function returns the intersection of the objects contained in the
 : given sequence of items, aggregating values corresponding to the same key
 : into an array.
 :
 : @param $items A sequence of items.
 : @return The insersection of the objects contained in $items.
 :)
declare function libjn:intersect($items as item()*) as object()
{
  {|
    let $objects := $items[$$ instance of object()]
    for $key in keys(head($objects))
    where every $o in tail($objects)
          satisfies exists(index-of(keys($o), $key))
    return { $key : $objects.$key }
  |}
};

(:~
 : This functions returns all values of all objects contained in a sequence of items.
 :
 : @param $items A sequence of items.
 : @return The values inside the objects of the sequence.
 :)
declare function libjn:values($items as item()*) as item()*
{
  for $i in $items
  for $k in jn:keys($i)
  return ($i treat as object())($k)
};

jsoniq version "1.0";

(:
 : Copyright 2006-2012 The FLWOR Foundation.
 :
 : 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.
:)

(:~
 : This module provides the functions defined by the JSONiq specification,
 : chapter 8 (Function Library). JSONiq extends
 : the XQuery specification to also deal with JSON data natively. See
 :
 :     http://jsoniq.org/
 :
 : for details.
 :
 : @author Ghislain Fourny
 : @project JSONiq/Function Library
 :)
module namespace libjn = "http://jsoniq.org/function-library";

import module namespace jn = "http://jsoniq.org/functions";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 : This function dynamically builds an object, like the {||} syntax, except that
 : it does not throw an error upon pair collision. Instead, it accumulates them
 : into an array, if more than one.
 :
 : @param $items A sequence of items, the objects of which are going to be
 :        accumulated into a single object.
 : @return The accumulated object.
 :)
declare function libjn:accumulate($items as item()*) as object()
{
  {[ $items ]}
};

(:~
 : This function returns all arrays contained at any depth within a sequence of items.
 :
 : @param $items A sequence of items.
 : @return The descendant arrays of the input sequence.
 :)
declare function libjn:descendant-arrays($items as item()*) as array()*
{
  for $i in $items
  return libjn:descendant-arrays-priv($i)
};

(:~
 : Helper function for libjn:descendant-arrays()
 :)
declare %private function libjn:descendant-arrays-priv($i as item()) as array()*
{
  typeswitch ($i)

  case object() return
    for $v in libjn:values($i)
    where $v instance of json-item()
    return libjn:descendant-arrays-priv($v)

  case array() return
    (
    $i,
    for $v in $i[]
    where $v instance of json-item()
    return libjn:descendant-arrays-priv($v)
    )

  default return
    ()
};

(:~
 : This function returns all objects contained at any depth within a sequence of items.
 :
 : @param $items A sequence of items.
 : @return The descendant objects of the input sequence.
 :)
declare function libjn:descendant-objects($items as item()*) as object()*
{
  for $i in $items
  return libjn:descendant-objects-priv($i)
};

(:~
 : Helper function for libjn:descendant-objects()
 :)
declare %private function libjn:descendant-objects-priv($i as item()) as object()*
{
  if ($i instance of object())
  then
    (
      $i,
      for $v in libjn:values($i)
      where $v instance of json-item()
      return libjn:descendant-objects-priv($v)
    )
  else if ($i instance of array())
  then
    (
      for $v in $i[]
      where $v instance of json-item()
      return libjn:descendant-objects-priv($v)
    )
  else
    ()
};

(:~
 : This function returns all pairs contained at any depth within an sequence of items.
 :
 : @param $o An object.
 : @return All direct and indirect descendant pairs.
 :)
declare function libjn:descendant-pairs($items as item()*) as object()*
{
  for $i in $items
  return libjn:descendant-pairs-priv($i)
};

(:~
 : Helper function for libjn:descendant-pairs()
 :)
declare function libjn:descendant-pairs-priv($i as item()) as object()*
{
  typeswitch ($i)

  case $o as object() return
    for $k in jn:keys($o)
    return
      (
      { $k : $o($k) },
      libjn:descendant-pairs-priv($o($k))
      )

  case $a as array() return
    for $i in $a[]
    where $i instance of json-item()
    return libjn:descendant-pairs-priv($i)

  default return
    ()
};

(:~
 : This function returns the intersection of the objects contained in the
 : given sequence of items, aggregating values corresponding to the same key
 : into an array.
 :
 : @param $items A sequence of items.
 : @return The insersection of the objects contained in $items.
 :)
declare function libjn:intersect($items as item()*) as object()
{
  {|
    let $objects := $items[$$ instance of object()]
    for $key in keys(head($objects))
    where every $o in tail($objects)
          satisfies exists(index-of(keys($o), $key))
    return { $key : $objects.$key }
  |}
};

(:~
 : This functions returns all values of all objects contained in a sequence of items.
 :
 : @param $items A sequence of items.
 : @return The values inside the objects of the sequence.
 :)
declare function libjn:values($items as item()*) as item()*
{
  for $i in $items
  for $k in jn:keys($i)
  return ($i treat as object())($k)
};


Don't throw an error if the MarkLogic breakpoint cannot be set.

(:
 : 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 "1.0-ml";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "marklogic/6.0";

(: Add/remove a breakpoint for a request. :)

declare variable $requestId as xs:unsignedLong external;
declare variable $register as xs:boolean external;
declare variable $exprUri as xs:string external;
declare variable $exprLine as xs:nonNegativeInteger external;
declare variable $exprColumn as xs:nonNegativeInteger external;

let $status := dbg:status($requestId)/dbg:request/dbg:request-status
let $_ := if ($status = "running") then dbg:break($requestId) else ()

let $result := try {
    let $expr :=
        for $expressionId in dbg:line($requestId, $exprUri, $exprLine)
        let $expr := dbg:expr($requestId, $expressionId)
        where $expr/dbg:line eq $exprLine and $expr/dbg:column eq $exprColumn
        return $expr
    let $_ :=
        if (exists($expr)) then
            if ($register) then
                dbg:break($requestId, $expr[1]/dbg:expr-id)
            else
                dbg:clear($requestId, $expr[1]/dbg:expr-id)
        else ()
    return true()
} catch ($e) {
    (: Can throw a "Module not found" error. :)
    false()
}

let $_ := if ($status = "running") then dbg:continue($requestId) else ()
return $result

(:
 : 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 "1.0-ml";
declare namespace o = "http://reecedunn.co.uk/xquery/options";
declare option o:implementation "marklogic/6.0";

(: Add/remove a breakpoint for a request. :)

declare variable $requestId as xs:unsignedLong external;
declare variable $register as xs:boolean external;
declare variable $exprUri as xs:string external;
declare variable $exprLine as xs:nonNegativeInteger external;
declare variable $exprColumn as xs:nonNegativeInteger external;

let $status := dbg:status($requestId)/dbg:request/dbg:request-status
let $_ := if ($status = "running") then dbg:break($requestId) else ()

let $expr :=
    for $expressionId in dbg:line($requestId, $exprUri, $exprLine)
    let $expr := dbg:expr($requestId, $expressionId)
    where $expr/dbg:line eq $exprLine and $expr/dbg:column eq $exprColumn
    return $expr
let $_ :=
    if (exists($expr)) then
        if ($register) then
            dbg:break($requestId, $expr[1]/dbg:expr-id)
        else
            dbg:clear($requestId, $expr[1]/dbg:expr-id)
    else ()

let $_ := if ($status = "running") then dbg:continue($requestId) else ()
return exists($expr)


[tweak] tweaked repo manager ui

[tweak] tweaked repo manager ui

svn path=/trunk/eXist/; revision=12458

xquery version "1.0";

module namespace repomanager="http://exist-db.org/xquery/admin-interface/repo";

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";
import module namespace repo="http://exist-db.org/xquery/repo";

declare function repomanager:upload() as element()
{
    let $name := request:get-parameter("name", ()),
    $docName := if($name) then $name else request:get-uploaded-file-name("upload"),
    $file := request:get-uploaded-file-data("upload") return

Actions:

                {
                if (contains($docName,'.xar')) then
                    (
uploaded package: {$docName}
,

                    xdb:decode-uri(xs:anyURI(xdb:store('/db/system/repo', xdb:encode-uri($docName), $file)))
                    )
                else

Error uploading - Must be a valid Package archive (.xar file extension)

                }

};

declare function repomanager:activate() as element()
{
    let $name := request:get-parameter("name", ()),
    $hostname := request:get-hostname(),            (:  pkg-repo.jar needs http or file scheme :)
    $port := request:get-server-port()
     return

Actions:

activated package: {$name}

                {
                    repo:install(concat('http://',$hostname,':',$port,'/exist/rest/db/system/repo/',$name,'.xar'))
                }

};

declare function repomanager:deactivate() as element()
{
    let $name := request:get-parameter("name", ())
     return

Actions:

deactivated package: {$name}

                {
                    repo:remove($name)
                }

};

declare function repomanager:remove() as element()
{
    let $name := request:get-parameter("name", ())
     return

Actions:

removed package: {$name}

                {xmldb:remove('/db/system/repo',concat($name,'.xar'))}

};

declare function repomanager:process-action() as element()*
{
    let $action := request:get-parameter("action", ()) return
        util:catch("java.lang.Exception",
            if($action eq "remove") then
            (
                repomanager:remove()
            )
            else if($action eq "activate") then
            (
                repomanager:activate()
            )
            else if($action eq "deactivate") then
            (
                repomanager:deactivate()
            )
            else if($action eq "Upload Package") then
            (
                repomanager:upload()
            )else(),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

declare function repomanager:main() as element() {
    let $action := lower-case(request:get-parameter("action", "refresh"))

    return

Package Repository

            <form method="POST" enctype="multipart/form-data">

         { repomanager:process-action() }

                Package
                Date installed
                Installed
                Action

        {
         let $files := collection('/db/system/repo')/util:document-name(.)
         let $repos := repo:list()
         return

            for $file in $files
            let $package-name := substring-before($file,'.xar')
            let $installed := exists($repos[. eq $package-name])
            return

                {$package-name}
                {xmldb:last-modified('/db/system/repo', concat($package-name,'.xar'))}

                {if ($installed) then
                    {$installed}
                else
                    {$installed}
                }

                {
                if($installed) then
                  deactivate

                 else
                 ( activate,' | ',
                 remove
                 )
                }

            }

                        <input type="submit" name="action" value="Upload Package"/>
                        <input type="file" size="30" name="upload"/>

 You can find example .xar packages located under webapp/repo/packages

Note: link to eXist-db own public package repository coming soon ....

          </form>

};

xquery version "1.0";

module namespace repomanager="http://exist-db.org/xquery/admin-interface/repo";

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";
import module namespace repo="http://exist-db.org/xquery/repo";

declare function repomanager:upload() as element()
{
    let $name := request:get-parameter("name", ()),
    $docName := if($name) then $name else request:get-uploaded-file-name("upload"),
    $file := request:get-uploaded-file-data("upload") return

Actions:

                {
                if (contains($docName,'.xar')) then
                    (
uploaded package: {$docName}
,

                    xdb:decode-uri(xs:anyURI(xdb:store('/db/system/repo', xdb:encode-uri($docName), $file)))
                    )
                else

Error uploading - Must be a valid Package archive (.xar file extension)

                }

};

declare function repomanager:activate() as element()
{
    let $name := request:get-parameter("name", ()),
    $hostname := request:get-hostname(),            (:  pkg-repo.jar needs http or file scheme :)
    $port := request:get-server-port()
     return

Actions:

activated package: {$name}

                {
                    repo:install(concat('http://',$hostname,':',$port,'/exist/rest/db/system/repo/',$name,'.xar'))
                }

};

declare function repomanager:deactivate() as element()
{
    let $name := request:get-parameter("name", ())
     return

Actions:

deactivated package: {$name}

                {
                    repo:remove($name)
                }

};

declare function repomanager:remove() as element()
{
    let $name := request:get-parameter("name", ())
     return

Actions:

removed package: {$name}

                {xmldb:remove('/db/system/repo',concat($name,'.xar'))}

};

declare function repomanager:process-action() as element()*
{
    let $action := request:get-parameter("action", ()) return
        util:catch("java.lang.Exception",
            if($action eq "remove") then
            (
                repomanager:remove()
            )
            else if($action eq "activate") then
            (
                repomanager:activate()
            )
            else if($action eq "deactivate") then
            (
                repomanager:deactivate()
            )
            else if($action eq "Upload Package") then
            (
                repomanager:upload()
            )else(),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

declare function repomanager:main() as element() {
    let $action := lower-case(request:get-parameter("action", "refresh"))

    return

Package Repository

            <form method="POST" enctype="multipart/form-data">

         { repomanager:process-action() }

                Package
                Date installed
                Installed
                Action

        {
         let $files := collection('/db/system/repo')/util:document-name(.)
         let $repos := repo:list()
         return

            for $file in $files
            let $package-name := substring-before($file,'.xar')
            let $installed := exists($repos[. eq $package-name])
            return

                {$package-name}
                {xmldb:last-modified('/db/system/repo', concat($package-name,'.xar'))}

                {if ($installed) then
                    {$installed}
                else
                    {$installed}
                }

                {
                if($installed) then
                  deactivate

                 else
                 ( activate,' | ',
                 remove
                 )
                }

            }

                        <input type="submit" name="action" value="Upload Package"/>
                        <input type="file" size="30" name="upload"/>

note: link to eXist-db own public package repository coming soon ....

          </form>

};


fix typo in position attribute when updating hw otehr id

import module namespace csd = "urn:ihe:iti:csd:2013" at "../repo/csd_base_library.xqm";
import module namespace csd_blu = "https://github.com/his-interop/openinfoman/csd_blu" at "../repo/csd_base_library_updating.xqm";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)
let $provs0 := if (exists($careServicesRequest/otherID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@oid)) then csd:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $id := $provs1[1]/otherID[position() = $careServicesRequest/otherID/@position]
return
  if (count($provs1) = 1 and exists($id))
    then
    let $provs2 :=
    <provider oid="{$provs1[1]/@oid}">
      <otherID position="{$careServicesRequest/otherID/@position}"/>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs1[1]),
	if ($careServicesRequest/otherID/@code)
	  then
	    if (exists($id/@code))
	      then  (replace value of node $id/@code with $careServicesRequest/otherID/@code)
	      else (insert node  $careServicesRequest/otherID/@code into $id)
	  else (),
	if (exists($careServicesRequest/otherID/@assigningAuthorityName) )
	  then
	    if (exists($id/@assigningAuthorityName))
	      then replace value of node $id/@assigningAuthorityName with $careServicesRequest/otherID/@assigningAuthorityName
	      else insert node $careServicesRequest/otherID/@assigningAuthorityName into $id
	  else (),
	if (not(string($careServicesRequest/otherID) = ''))
	  then (replace value of node $id with string($careServicesRequest/otherID))
	  else (),
	csd_blu:wrap_updating_providers($provs2)
     )
  else 	csd_blu:wrap_updating_providers(())

import module namespace csd = "urn:ihe:iti:csd:2013" at "../repo/csd_base_library.xqm";
import module namespace csd_blu = "https://github.com/his-interop/openinfoman/csd_blu" at "../repo/csd_base_library_updating.xqm";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)
let $provs0 := if (exists($careServicesRequest/otherID)) then /CSD/providerDirectory/*  else ()
let $provs1 := if (exists($careServicesRequest/id/@oid)) then csd:filter_by_primary_id($provs0,$careServicesRequest/id) else ()
let $id := $provs1[1]/otherID[position() = $careServicesRequest/otherID/@position]
return
  if (count($provs1) = 1 and exists($id))
    then
    let $provs2 :=
    <provider oid="{$provs1[1]/@oid}">
      <otherID position="{$careServicesRequest/name/@position}"/>
    </provider>
    return
      (
	csd_blu:bump_timestamp($provs1[1]),
	if ($careServicesRequest/otherID/@code)
	  then
	    if (exists($id/@code))
	      then  (replace value of node $id/@code with $careServicesRequest/otherID/@code)
	      else (insert node  $careServicesRequest/otherID/@code into $id)
	  else (),
	if (exists($careServicesRequest/otherID/@assigningAuthorityName) )
	  then
	    if (exists($id/@assigningAuthorityName))
	      then replace value of node $id/@assigningAuthorityName with $careServicesRequest/otherID/@assigningAuthorityName
	      else insert node $careServicesRequest/otherID/@assigningAuthorityName into $id
	  else (),
	if (not(string($careServicesRequest/otherID) = ''))
	  then (replace value of node $id with string($careServicesRequest/otherID))
	  else (),
	csd_blu:wrap_updating_providers($provs2)
     )
  else 	csd_blu:wrap_updating_providers(())


*	Added a hardcoded session timeout of 3 minutes.

git-svn-id: b46a086423077f2361295c5ec15b0f9cbe8e278c@1841 b091869f-ef14-0410-ae3d-fae7310851ef

xquery version "1.0" encoding "UTF-8";

(:~
 : This module does login to the system, if it is allowed (of course :-))
 : @author José María Fernández
 :)

module namespace login="http://www.cnio.es/scombio/xcesc/1.0/xquery/login";

declare namespace xcesc="http://www.cnio.es/scombio/xcesc/1.0";

import module namespace util="http://exist-db.org/xquery/util";

import module namespace mgmt = 'http://www.cnio.es/scombio/xcesc/1.0/xquery/systemManagement' at 'xmldb:exist:///db/XCESC-logic/systemManagement.xqm';

declare variable $login:TOKEN_SEP as xs:string := ', ';
declare variable $login:KEYVAL_SEP as xs:string := '=';
declare variable $login:DIGEST_SEP as xs:string := ':';
declare variable $login:NONCE_KEY as xs:string := 'nonce';
declare variable $login:REALM_KEY as xs:string := 'realm';
declare variable $login:USER_KEY as xs:string := 'user';
declare variable $login:XCESC_USER_ID_KEY as xs:string := 'xcesc-user';
declare variable $login:RESPONSE_KEY as xs:string := 'response';

declare function login:generate-nonce($realm as xs:string,$nonce as xs:string)
	as xs:integer
{
	(: No session, no party :)
	session:invalidate(),
	session:create(),
	session:set-max-inactive-interval(180),
	session:set-attribute($login:NONCE_KEY,$nonce),
	session:set-attribute($login:REALM_KEY,$realm),
	response:set-header('XCESC-auth',
		string-join(
			(
				string-join(($login:NONCE_KEY,$nonce),$login:KEYVAL_SEP)
				,
				string-join(($login:REALM_KEY,$realm),$login:KEYVAL_SEP)
			)
			,
			$login:TOKEN_SEP
		)
	),
	401
};

declare function login:do-login-digest($user as xs:string, $realm as xs:string, $nonce as xs:string)
	as xs:string?
{
	(: We cannot follow if the user is not confirmed or it is disabled :)
	let $pass := mgmt:getActiveUserFromNickname($user)/@nickpass
	return
		if(exists($pass)) then (
			let $HA1 := util:hash(string-join(($user,$realm,$pass/string()),$login:DIGEST_SEP),'md5')
			return
				util:hash(string-join(($nonce,$HA1),$login:DIGEST_SEP),'md5')
		) else (
		)
};

xquery version "1.0" encoding "UTF-8";

(:~
 : This module does login to the system, if it is allowed (of course :-))
 : @author José María Fernández
 :)

module namespace login="http://www.cnio.es/scombio/xcesc/1.0/xquery/login";

declare namespace xcesc="http://www.cnio.es/scombio/xcesc/1.0";

import module namespace util="http://exist-db.org/xquery/util";

import module namespace mgmt = 'http://www.cnio.es/scombio/xcesc/1.0/xquery/systemManagement' at 'xmldb:exist:///db/XCESC-logic/systemManagement.xqm';

declare variable $login:TOKEN_SEP as xs:string := ', ';
declare variable $login:KEYVAL_SEP as xs:string := '=';
declare variable $login:DIGEST_SEP as xs:string := ':';
declare variable $login:NONCE_KEY as xs:string := 'nonce';
declare variable $login:REALM_KEY as xs:string := 'realm';
declare variable $login:USER_KEY as xs:string := 'user';
declare variable $login:XCESC_USER_ID_KEY as xs:string := 'xcesc-user';
declare variable $login:RESPONSE_KEY as xs:string := 'response';

declare function login:generate-nonce($realm as xs:string,$nonce as xs:string)
	as xs:integer
{
	(: No session, no party :)
	session:invalidate(),
	session:create(),
	session:set-attribute($login:NONCE_KEY,$nonce),
	session:set-attribute($login:REALM_KEY,$realm),
	response:set-header('XCESC-auth',
		string-join(
			(
				string-join(($login:NONCE_KEY,$nonce),$login:KEYVAL_SEP)
				,
				string-join(($login:REALM_KEY,$realm),$login:KEYVAL_SEP)
			)
			,
			$login:TOKEN_SEP
		)
	),
	401
};

declare function login:do-login-digest($user as xs:string, $realm as xs:string, $nonce as xs:string)
	as xs:string?
{
	(: We cannot follow if the user is not confirmed or it is disabled :)
	let $pass := mgmt:getActiveUserFromNickname($user)/@nickpass
	return
		if(exists($pass)) then (
			let $HA1 := util:hash(string-join(($user,$realm,$pass/string()),$login:DIGEST_SEP),'md5')
			return
				util:hash(string-join(($nonce,$HA1),$login:DIGEST_SEP),'md5')
		) else (
		)
};


Fixed typo in image/* mime type expression.

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

declare namespace atom="http://www.w3.org/2005/Atom";
<service xmlns="http://purl.org/atom/app#">
   <workspace title="{/atom:feed/atom:title}">
   {
     "
",
     let $current := substring-before(base-uri(/atom:feed),'/.feed.atom'),
         $current-path := substring-after($current,'/db')
        for $i in (collection($current)/atom:feed)
           let $path :=  substring-after(substring-before(base-uri($i),'/.feed.atom'),'/db')
              return ( <collection title="{$i/atom:title}" href="/atom/edit{$path}">
                         <accept>text/*,image/*,application/*</accept>
                       </collection>,
                       "
"
                     )
   }
   </workspace>
</service>

declare namespace atom="http://www.w3.org/2005/Atom";
<service xmlns="http://purl.org/atom/app#">
   <workspace title="{/atom:feed/atom:title}">
   {
     "
",
     let $current := substring-before(base-uri(/atom:feed),'/.feed.atom'),
         $current-path := substring-after($current,'/db')
        for $i in (collection($current)/atom:feed)
           let $path :=  substring-after(substring-before(base-uri($i),'/.feed.atom'),'/db')
              return ( <collection title="{$i/atom:title}" href="/atom/edit{$path}">
                         <accept>text/*,iamge/*,application/*</accept>
                       </collection>,
                       "
"
                     )
   }
   </workspace>
</service>


QXTS: changed report for w3c to match actual DB features

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

(: declare default element namespace "http://www.w3.org/2005/02/query-test-XQTSResult"; :)
declare option exist:serialize "method=xml indent=yes";
declare option exist:output-size-limit "-1";
declare namespace response="http://exist-db.org/xquery/response";

let $product-version := util:system-property("product-version")
let $product-build := util:system-property("product-build")
let $test-suite := doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/@version
let $dummy := response:set-header("Content-Disposition", concat(
	"attachment; filename="results_XQTS-" , $test-suite , "_eXist-" ,
	$product-version , '_' , $product-build , ".xml"" ) )

return
<test-suite-result>
        <implementation name="eXist-{$product-version}" version="{$product-build}" anonymous-result-column="false">

                <organization name="eXist Open Source native XML database"  website="http://www.exist-db.org" anonymous="false"/>

                <submittor name="eXist XQTS testsuite runner" email="xqts@exist-db.org"/>

                <description>

eXist is an Open Source native XML database featuring efficient,
                        index-based XQuery processing, automatic indexing, extensions for full-text
                        search,  XUpdate  support and tight integration with existing XML development tools.

                </description>

                <implementation-defined-items>

                </implementation-defined-items>

                <features>

                <feature name="Minimal Conformance" supported="true"/>
                <feature name="Schema Import" supported="false"/>
                <feature name="Schema Validation" supported="false"/>
                <feature name="Static Typing" supported="false"/>
                <feature name="Static Typing Extensions" supported="false"/>
                <feature name="Full Axis" supported="true"/>
                <feature name="Module" supported="true"/>
                <feature name="Serialization" supported="true"/>
                <feature name="Trivial XML Embedding" supported="false"/>
						  </features>

                <context-properties>

                </context-properties>

        </implementation>

        <syntax>XQuery</syntax>

        <test-run dateRun="{fn:current-dateTime()}">
                <test-suite version="{$test-suite}"/>
                <transformation>

No unusual transformations.

                </transformation>
                <comparison>

No unusual comparisons

                </comparison>
                <otherComments>

The test run took n seconds.

                </otherComments>
        </test-run>

{
		(: for $case in fn:collection(  '/db/XQTS' )//*:test-case :)
    for $case in fn:collection(  '/db/XQTS' )//test-case
    order by $case/@name
    return <test-case name="{$case/@name}" result="{$case/@result}" />
}
</test-suite-result>

(: declare default element namespace "http://www.w3.org/2005/02/query-test-XQTSResult"; :)
declare option exist:serialize "method=xml indent=yes";
declare option exist:output-size-limit "-1";
declare namespace response="http://exist-db.org/xquery/response";

let $product-version := util:system-property("product-version")
let $product-build := util:system-property("product-build")
let $test-suite := doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/@version
let $dummy := response:set-header("Content-Disposition", concat(
	"attachment; filename="results_XQTS-" , $test-suite , "_eXist-" ,
	$product-version , '_' , $product-build , ".xml"" ) )

return
<test-suite-result>
        <implementation name="eXist-{$product-version}" version="{$product-build}" anonymous-result-column="false">

                <organization name="eXist Open Source native XML database"  website="http://www.exist-db.org" anonymous="false"/>

                <submittor name="eXist XQTS testsuite runner" email="xqts@exist-db.org"/>

                <description>

eXist is an Open Source native XML database featuring efficient,
                        index-based XQuery processing, automatic indexing, extensions for full-text
                        search,  XUpdate  support and tight integration with existing XML development tools.

                </description>

                <implementation-defined-items>

                </implementation-defined-items>

                <features>
{ for $feature in doc('/db/XQTS/XQTSCatalog.xml')/*:test-suite/*:features/*:feature
							return
							<feature name="{$feature/@name}" supported="true"/>
						}</features>

                <context-properties>

                </context-properties>

        </implementation>

        <syntax>XQuery</syntax>

        <test-run dateRun="{fn:current-dateTime()}">
                <test-suite version="{$test-suite}"/>
                <transformation>

No unusual transformations.

                </transformation>
                <comparison>

No unusual comparisons

                </comparison>
                <otherComments>

The test run took n seconds.

                </otherComments>
        </test-run>

{
		(: for $case in fn:collection(  '/db/XQTS' )//*:test-case :)
    for $case in fn:collection(  '/db/XQTS' )//test-case
    order by $case/@name
    return <test-case name="{$case/@name}" result="{$case/@result}" />
}
</test-suite-result>


Better formatting for the modules/xml documentation.

(:
 : Copyright 2006-2010 The FLWOR Foundation.
 :
 : 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.
:)

(:~
 :

 : This module provides functions for manipulating XML files.
 :

 :
 : @author Nicolae Brinza
 : @project data processing/data converters
 :
 :)
module namespace parse-xml = "http://www.zorba-xquery.com/modules/xml";
declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
declare option ver:module-version "2.0";

(:~
 : A function to parse XML files and fragments (i.e. external general parsed
 : entities). The functions takes two arguments: the first one is the string
 : to be parsed. The second argument is a string (eEdDsSlLwWfF]*(;[\p{L}]*)?)
 : defining the following options.
 :

 :

 :
 : The convention for the standard flags is that a lower-case letter enables
 : an option, and the corresponding upper-case letter disables it; specifying
 : both is an error; specifying neither leaves it implementation-defined
 : whether the option is enabled or disabled. Specifying the same option twice
 : is not an error, but specifying inconsistent options (for example "eE") is
 : a dynamic error. The options defined are:
 :
 :

 :

 : eE - enables or disables processing of XML external entities. If the option
 : is enabled, the input must conform to the syntax _extParsedEnt_ (production
 : [78] in XML 1.0, see XML 1.0)
 : The result of the function call is a list of nodes corresponding to the
 : top-level components of the _content_ of the external entity: that is,
 : elements, processing instructions, comments, and text nodes. CDATA sections
 : and character references are expanded, and adjacent characters are merged
 : so the result contains no adjacent text nodes. If this option is enabled,
 : none of the options d, s, or, l  may be enabled. If the option is disabled,
 : the input must be a well-formed XML document conforming to the syntax
 : document_ (production [1] in XML 1.0).
 :

 :
 :

 : dD - enables or disables DTD-based validation. If this option is enabled and
 : the input references a DTD, then the input must be a well-formed and
 : DTD-valid XML document. If the option is enabled and the input does not
 : reference a DTD then the option is ignored. If the option is disabled, the
 : input is not required to reference a DTD and if it does reference a DTD then
 : the DTD is ignored for validation purposes (though it will still be read for
 : purposes such as expanding entity references and identifying ID attributes).
 :

 :
 :

 : sS - enables or disables strict XSD-based validation. If this option is
 : enabled, the result is equivalent to processing the input with the option
 : disabled, and then copying the result using the XQuery "validate strict"
 : expression, or the XSLT xsl:copy-of instruction with validation="strict".
 :

 :
 :

 : lL - enables or disables lax XSD-based validation. If this option is enabled,
 : the result is equivalent to processing the input with the option disabled,
 : and then copying the result using the XQuery "validate lax " expression, or
 : the XSLT xsl:copy-of instruction with validation="lax".
 :

 :
 :

 : wW - enables or disables whitespace stripping. If the option is enabled,
 : any whitespace-only text nodes that remain after any DTD-based or XSD-based
 : processing are stripped from the input; if it is disabled, such
 : whitespace-only text nodes are retained. (In XSLT, if the option is not
 : specified, the provisions of the xsl:strip-space and xsl:preserve-space
 : declarations apply.)
 :

 :
 :

 : fF - enables or disables fatal error processing. If fatal error processing
 : is enabled, then any failure to parse the input in the manner requested
 : results in a dynamic error. If fatal error processing is disabled, then any
 : failure to parse the input (and also, in the case of fn:doc, a failure to
 : obtain the input by dereferencing the supplied URI) results in the function
 : returning an empty sequence and raising no error.
 :

 :

 :
 : @param $xml-string The string that holds the XML to be parse. If empty,
 :                    the function will return an empty sequence
 : @param $options The options for the parsing
 : @return The parsed XML as a document node or a list of nodes, or an empty
 :         sequence
 :)
declare function parse-xml:parse-xml-fragment(
  $xml-string as xs:string?,
  $options as xs:string) as node()* external;

(:~
 : A function to parse XML files and fragments. The behavior is the
 : same as the parse-xml-fragment with two arguments.
 : @param $xml-string The string that holds the XML to be parse. If empty,
 :                    the function will return an empty sequence
 : @param $base-uri The baseURI that will be used as the baseURI for every
 :                    node returned by this function.
 : @param $options The options for the parsing (see parse-xml-fragment#2)
 : @return The parsed XML as a document node or a list of nodes, or an empty
 :         sequence
 :)
declare function parse-xml:parse-xml-fragment(
  $xml-string as xs:string?,
  $base-uri as xs:string,
  $options as xs:string) as node()* external;

(:
 : Copyright 2006-2010 The FLWOR Foundation.
 :
 : 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.
:)

(:~
 :

 : This module provides functions for manipulating XML files.
 :

 :
 : @author Nicolae Brinza
 : @project data processing/data converters
 :
 :)
module namespace parse-xml = "http://www.zorba-xquery.com/modules/xml";
declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
declare option ver:module-version "2.0";

(:~
 : A function to parse XML files and fragments (i.e. external general parsed
 : entities). The functions takes two arguments: the first one is the string
 : to be parsed. The second argument is a string (eEdDsSlLwWfF]*(;[\p{L}]*)?)
 : defining the following options.
 :

 :
 : The convention for the standard flags is that a lower-case letter enables
 : an option, and the corresponding upper-case letter disables it; specifying
 : both is an error; specifying neither leaves it implementation-defined
 : whether the option is enabled or disabled. Specifying the same option twice
 : is not an error, but specifying inconsistent options (for example "eE") is
 : a dynamic error. The options defined are:
 :

 :
 : eE - enables or disables processing of XML external entities. If the option
 : is enabled, the input must conform to the syntax _extParsedEnt_ (production
 : [78] in XML 1.0, see XML 1.0)
 : The result of the function call is a list of nodes corresponding to the
 : top-level components of the _content_ of the external entity: that is,
 : elements, processing instructions, comments, and text nodes. CDATA sections
 : and character references are expanded, and adjacent characters are merged
 : so the result contains no adjacent text nodes. If this option is enabled,
 : none of the options d, s, or, l  may be enabled. If the option is disabled,
 : the input must be a well-formed XML document conforming to the syntax
 : document_ (production [1] in XML 1.0).
 :

 :
 : dD - enables or disables DTD-based validation. If this option is enabled and
 : the input references a DTD, then the input must be a well-formed and
 : DTD-valid XML document. If the option is enabled and the input does not
 : reference a DTD then the option is ignored. If the option is disabled, the
 : input is not required to reference a DTD and if it does reference a DTD then
 : the DTD is ignored for validation purposes (though it will still be read for
 : purposes such as expanding entity references and identifying ID attributes).
 :

 :
 : sS - enables or disables strict XSD-based validation. If this option is
 : enabled, the result is equivalent to processing the input with the option
 : disabled, and then copying the result using the XQuery "validate strict"
 : expression, or the XSLT xsl:copy-of instruction with validation="strict".
 :

 :
 : lL - enables or disables lax XSD-based validation. If this option is enabled,
 : the result is equivalent to processing the input with the option disabled,
 : and then copying the result using the XQuery "validate lax " expression, or
 : the XSLT xsl:copy-of instruction with validation="lax".
 :

 :
 : wW - enables or disables whitespace stripping. If the option is enabled,
 : any whitespace-only text nodes that remain after any DTD-based or XSD-based
 : processing are stripped from the input; if it is disabled, such
 : whitespace-only text nodes are retained. (In XSLT, if the option is not
 : specified, the provisions of the xsl:strip-space and xsl:preserve-space
 : declarations apply.)
 :

 :
 : fF - enables or disables fatal error processing. If fatal error processing
 : is enabled, then any failure to parse the input in the manner requested
 : results in a dynamic error. If fatal error processing is disabled, then any
 : failure to parse the input (and also, in the case of fn:doc, a failure to
 : obtain the input by dereferencing the supplied URI) results in the function
 : returning an empty sequence and raising no error.
 :

 :
 : @param $xml-string The string that holds the XML to be parse. If empty,
 :                    the function will return an empty sequence
 : @param $options The options for the parsing
 : @return The parsed XML as a document node or a list of nodes, or an empty
 :         sequence
 :)
declare function parse-xml:parse-xml-fragment(
  $xml-string as xs:string?,
  $options as xs:string) as node()* external;

(:~
 : A function to parse XML files and fragments. The behavior is the
 : same as the parse-xml-fragment with two arguments.
 : @param $xml-string The string that holds the XML to be parse. If empty,
 :                    the function will return an empty sequence
 : @param $base-uri The baseURI that will be used as the baseURI for every
 :                    node returned by this function.
 : @param $options The options for the parsing (see parse-xml-fragment#2)
 : @return The parsed XML as a document node or a list of nodes, or an empty
 :         sequence
 :)
declare function parse-xml:parse-xml-fragment(
  $xml-string as xs:string?,
  $base-uri as xs:string,
  $options as xs:string) as node()* external;


updated map{} to new usage

updated map{} to new usage

declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;
let $doc := /.

let $xpaths := map{
    "Posting/Facility": "csd:facilities/csd:facility",
    "ID Number": "csd:otherID/@code",
    "ID Date of Issue":"csd:otherID/@issueDate/text()",
    "ID Date of Expiration":"csd:otherID/@expirationDate/text()",
    "Place of Issue": "csd:otherID/@assigningAuthorityName/text()",
    "First name": "csd:demographic/csd:name/csd:forename/text()",
    "Last name": "csd:demographic/csd:name/csd:surname/text()",
    "Middle name":"csd:demographic/csd:name/csd:otherNames[@type='middle']/text()",
    "Maiden name": "csd:demographic/csd:name/csd:otherNames[@type='maiden']/text()",
    "Other name 1" : "csd:demographic/csd:name/csd:otherNames[@type='other_1']/text()",
    "Other name 2" :"csd:demographic/csd:name/csd:otherNames[@type='other_2']/text()",
    "Other name 3" : "csd:demographic/csd:name/csd:otherNames[@type='other_3']/text()",
    "Place of birth country":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:country/text()",
    "Place of birth town": "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:town/text()",
    "Father’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:fatherName/text()",
    "Mother’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:motherName/text()",
    "Photograph" :    "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds'  and @type='photograph']/csd:image/text()",
    "Date of birth" :  "csd:demographic/csd:dateOfBirth/text()",
    "Sex at birth " : "csd:demographic/csd:gender/text()",
    "Citizenship at birth" : "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:birth/text()" ,
    "Citizenship at present country of residence":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:residence/text()",
    "Ability in written languages":"csd:language[@code]/@written-ability",
    "Ability in spoken languages": "csd:language[@code]/@spoken-ability",
    "Address Country":"csd:demographic/csd:address/csd:addressLine[@component='country']/text()",
    "Address City": "csd:demographic/csd:address/csd:addressLine[@component='city']/text()" ,
    "Street Address": "csd:demographic/csd:address/csd:addressLine[@component='streetAddress']/text()",
    "Address Postal Code" :"csd:demographic/csd:address/csd:addressLine[@component='postalCode']/text()" ,
    "Telephone number" : "csd:demographic/csd:contactPoint/csd:codedType[@code='BP'  and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Email address" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMAIL' and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Emergency contact name" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMERGENCY'  and @codingScheme= 'urn:who.int:hrh:mds']/text()",
    "Professional License and Certification Document Type" : "csd:credential/csd:codedType/@code",
    "Professional License and Certification Document Category" : "csd:credential/csd:codedType/@category",
    "Professional License and Certification Issuing Institution": "csd:credential/csd:issuingAuthority/text()",
    "Professional License and Certification Date of Issue" : "csd:credential/csd:credentialIssueDate/text()",
    "Professional License and Certification Date of Expiration" : "csd:credential/csd:credentialRenewalDate/text()" ,
    "Professional License and Certification Scan/Photograph" :  "csd:credential/csd:extension[@urn ='urn:who.int:hrh:mds' and @type='photograph']/csd:image/text()" ,
    "Employment status" : "csd:record/@status" ,
    "Occupational category" : "csd:codedType/@code" ,
    "Employment title" : "csd:codedType[@code]/text()",
    "Complaints" : "csd:credential/csd:extension[@urn = 'urn:who.int:hrh:mds' and @type='complaints']/@value",
    "Data submission  institution ": "csd:record/@sourceDirectory",
    "Data submission date" : "csd:record/@updated"
}

let $total := count($doc/csd:CSD/csd:providerDirectory/csd:provider)

let $stats :=
  map:for-each($xpaths,
    function($label,$xpath) {
      let $matches :=
        for $provider in $doc/csd:CSD/csd:providerDirectory/csd:provider
        let $bindings := map{"provider":$provider}
	let $expr := " declare namespace csd = 'urn:ihe:iti:csd:2013'; declare variable $provider external; $provider/" || $xpath
	let $result := xquery:eval($expr,$bindings)
	where exists($result)
	return 	$provider
      let $count:=count($matches)
      return <record>{$label}<count>{$count}</count><percent>{if ($total > 0) then floor($count div $total * 100) else "N/A"} %</percent></record>
    })

let $csv:=
  <csv >
  <record>Data Field<count>Number of Records Total of {$total}</count><percent>Percentage</percent></record>
   {
     for $stat in $stats
     order by number($stat/count/text()) descending
     return $stat
   }
  </csv>

return csv:serialize($csv,map{ 'header': 'no', 'separator': 'tab'  })

declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;
let $doc := /.

let $xpaths := map{
    "Posting/Facility": "csd:facilities/csd:facility",
    "ID Number": "csd:otherID/@code",
    "ID Date of Issue":"csd:otherID/@issueDate/text()",
    "ID Date of Expiration":"csd:otherID/@expirationDate/text()",
    "Place of Issue": "csd:otherID/@assigningAuthorityName/text()",
    "First name": "csd:demographic/csd:name/csd:forename/text()",
    "Last name": "csd:demographic/csd:name/csd:surname/text()",
    "Middle name":"csd:demographic/csd:name/csd:otherNames[@type='middle']/text()",
    "Maiden name": "csd:demographic/csd:name/csd:otherNames[@type='maiden']/text()",
    "Other name 1" : "csd:demographic/csd:name/csd:otherNames[@type='other_1']/text()",
    "Other name 2" :"csd:demographic/csd:name/csd:otherNames[@type='other_2']/text()",
    "Other name 3" : "csd:demographic/csd:name/csd:otherNames[@type='other_3']/text()",
    "Place of birth country":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:country/text()",
    "Place of birth town": "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:town/text()",
    "Father’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:fatherName/text()",
    "Mother’s name":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='birth']/csd:motherName/text()",
    "Photograph" :    "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds'  and @type='photograph']/csd:image/text()",
    "Date of birth" :  "csd:demographic/csd:dateOfBirth/text()",
    "Sex at birth " : "csd:demographic/csd:gender/text()",
    "Citizenship at birth" : "csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:birth/text()" ,
    "Citizenship at present country of residence":"csd:demographic/csd:extension[@urn='urn:who.int:hrh:mds' and @type='citizenship']/csd:residence/text()",
    "Ability in written languages":"csd:language[@code]/@written-ability",
    "Ability in spoken languages": "csd:language[@code]/@spoken-ability",
    "Address Country":"csd:demographic/csd:address/csd:addressLine[@component='country']/text()",
    "Address City": "csd:demographic/csd:address/csd:addressLine[@component='city']/text()" ,
    "Street Address": "csd:demographic/csd:address/csd:addressLine[@component='streetAddress']/text()",
    "Address Postal Code" :"csd:demographic/csd:address/csd:addressLine[@component='postalCode']/text()" ,
    "Telephone number" : "csd:demographic/csd:contactPoint/csd:codedType[@code='BP'  and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Email address" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMAIL' and @codingScheme='urn:ihe:iti:csd:2013:contactPoint']/text()",
    "Emergency contact name" : "csd:demographic/csd:contactPoint/csd:codedType[@code='EMERGENCY'  and @codingScheme= 'urn:who.int:hrh:mds']/text()",
    "Professional License and Certification Document Type" : "csd:credential/csd:codedType/@code",
    "Professional License and Certification Document Category" : "csd:credential/csd:codedType/@category",
    "Professional License and Certification Issuing Institution": "csd:credential/csd:issuingAuthority/text()",
    "Professional License and Certification Date of Issue" : "csd:credential/csd:credentialIssueDate/text()",
    "Professional License and Certification Date of Expiration" : "csd:credential/csd:credentialRenewalDate/text()" ,
    "Professional License and Certification Scan/Photograph" :  "csd:credential/csd:extension[@urn ='urn:who.int:hrh:mds' and @type='photograph']/csd:image/text()" ,
    "Employment status" : "csd:record/@status" ,
    "Occupational category" : "csd:codedType/@code" ,
    "Employment title" : "csd:codedType[@code]/text()",
    "Complaints" : "csd:credential/csd:extension[@urn = 'urn:who.int:hrh:mds' and @type='complaints']/@value",
    "Data submission  institution ": "csd:record/@sourceDirectory",
    "Data submission date" : "csd:record/@updated"
}

let $total := count($doc/csd:CSD/csd:providerDirectory/csd:provider)

let $stats :=
  map:for-each($xpaths,
    function($label,$xpath) {
      let $matches :=
        for $provider in $doc/csd:CSD/csd:providerDirectory/csd:provider
        let $bindings := map{"provider":$provider}
	let $expr := " declare namespace csd = 'urn:ihe:iti:csd:2013'; declare variable $provider external; $provider/" || $xpath
	let $result := xquery:eval($expr,$bindings)
	where exists($result)
	return 	$provider
      let $count:=count($matches)
      return <record>{$label}<count>{$count}</count><percent>{if ($total > 0) then floor($count div $total * 100) else "N/A"} %</percent></record>
    })

let $csv:=
  <csv >
  <record>Data Field<count>Number of Records Total of {$total}</count><percent>Percentage</percent></record>
   {
     for $stat in $stats
     order by number($stat/count/text()) descending
     return $stat
   }
  </csv>

return csv:serialize($csv,{ 'header': 'no', 'separator': 'tab'  })


fixed typo in webapp_ui

fixed typo in webapp_ui

(:~
: This is a module conttaining configuration options for the openinfoman webap
: @version 1.0
: @see https://github.com/openhie/openinfoman @see http://ihe.net
:
:)

module namespace csd_webui = "https://github.com/openhie/openinfoman/csd_webui";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace request = "http://exquery.org/ns/request";

declare function csd_webui:generateURL() {
  csd_webui:generateURL(())
};

declare function csd_webui:generateURL($end as item*) {
  let $cend :=
    functx:string-join(
      for $e in $end
      return replace(replace(string($e),'^/+',''),'/+$','')
      ,'/')

  let $cbegin :=
    if (functx:all-whitespace($csd_webconf:baseurl))
    then concat(request:scheme(),"://",request:hostname(),":",request:port())
    else replace($csd_webconf:baseurl, '/+$', '')

  return concat($cbegin,'/',$cend)

};

declare function csd_webui:nocache($response)
{(
  <rest:response>
    <http:response >
      <http:header name="Cache-Control" value="must-revalidate,no-cache,no-store"/>
    </http:response>
  </rest:response>
  ,
  $response
)};

declare function csd_webui:redirect() as element(restxq:redirect) {
  csd_webui:redirect(())
};

declare function csd_webui:redirect($end*) as element(restxq:redirect)
{
  <restxq:redirect>{ csd_webui:generateURL($end }</restxq:redirect>
};

declare function csd_webui:redirect_out() as element(restxq:redirect) {
  csd_webui:redirect_out(())
};

declare function csd_webui:redirect_out($end*) as element(restxq:redirect)
{
  db:output(<restxq:redirect>{ csd_webui:generateURL($end }</restxq:redirect>)
};

declare function csd_webui:wrapper($content) {
  csd_webui:wrapper($content,())
};

declare function csd_webui:wrapper($content,$headers) {

    <link href="{$csd_webui:generateURL('static/bootstrap/css/bootstrap.css')}" rel="stylesheet"/>
    <link href="{$csd_webui:generateURL('static/bootstrap/css/bootstrap-theme.css')}" rel="stylesheet"/>
    <link rel="shortcut icon" href="{$csd_webui:generateURL(,'static/favicon.ico')}"/>

(:~
: This is a module conttaining configuration options for the openinfoman webap
: @version 1.0
: @see https://github.com/openhie/openinfoman @see http://ihe.net
:
:)

module namespace csd_webui = "https://github.com/openhie/openinfoman/csd_webui";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";
import module namespace request = "http://exquery.org/ns/request";

declare function csd_webui:generateURL() {
  csd_webui:generateURL(())
};

declare function csd_webui:generateURL($end*) {
  let $cend :=
    functx:string-join(
      for $e in $end
      return replace(replace(string($e),'^/+',''),'/+$','')
      ,'/')

  let $cbegin :=
    if (functx:all-whitespace($csd_webconf:baseurl))
    then concat(request:scheme(),"://",request:hostname(),":",request:port())
    else replace($csd_webconf:baseurl, '/+$', '')

  return concat($cbegin,'/',$cend)

};

declare function csd_webui:nocache($response)
{(
  <rest:response>
    <http:response >
      <http:header name="Cache-Control" value="must-revalidate,no-cache,no-store"/>
    </http:response>
  </rest:response>
  ,
  $response
)};

declare function csd_webui:redirect() as element(restxq:redirect) {
  csd_webui:redirect(())
};

declare function csd_webui:redirect($end*) as element(restxq:redirect)
{
  <restxq:redirect>{ csd_webui:generateURL($end }</restxq:redirect>
};

declare function csd_webui:redirect_out() as element(restxq:redirect) {
  csd_webui:redirect_out(())
};

declare function csd_webui:redirect_out($end*) as element(restxq:redirect)
{
  db:output(<restxq:redirect>{ csd_webui:generateURL($end }</restxq:redirect>)
};

declare function csd_webui:wrapper($content) {
  csd_webui:wrapper($content,())
};

declare function csd_webui:wrapper($content,$headers) {

    <link href="{$csd_webui:generateURL('static/bootstrap/css/bootstrap.css')}" rel="stylesheet"/>
    <link href="{$csd_webui:generateURL('static/bootstrap/css/bootstrap-theme.css')}" rel="stylesheet"/>
    <link rel="shortcut icon" href="{$csd_webui:generateURL(,'static/favicon.ico')}"/>


Added some links to task views.

Added some links to task views.

declare default element namespace "http://www.w3.org/1999/xhtml";

import module namespace logx="http://cefn.com/logx" at "lib/logx.xq";

logx:webpage(

Each Page Below Represents a Task

        {
            for $item in (
                logx:viewer-link('xq/tasks/tags.xq', 'Tag papers'),
                logx:viewer-link('xq/tasks/years.xq', 'Annotate with Year'),
                logx:viewer-link('xq/tasks/notes.xq', 'Papers without notes')
            )
            return
{$item}

        }

)

declare default element namespace "http://www.w3.org/1999/xhtml";

import module namespace logx="http://cefn.com/logx" at "lib/logx.xq";

logx:webpage(

Each Page Below Represents a Task

        {
            for $item in (
                logx:viewer-link('xq/tasks/tag.xq', 'Tag papers'),
                logx:viewer-link('xq/tasks/year.xq', 'Annotate with Year'),
                logx:viewer-link('xq/tasks/scan.xq', 'Scan content of paper')
            )
            return
{$item}

        }

)


better adhoc example request

better adhoc example request

module namespace page = 'http://basex.org/modules/web-page';

import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";

declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare variable $page:csd_docs := csd_dm:registered_documents($csd_webconf:db);

declare
  %rest:path("/CSD/csr/{$name}/careServicesRequest")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$careServicesRequest}")
  function page:csr($name,$careServicesRequest)
{
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
 csr_proc:process_CSR($csd_webconf:db,$careServicesRequest/careServicesRequest,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr/{$name}/careServicesRequest/{$search}")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$requestParams}")
  function page:csr2($name,$requestParams,$search)
{
let $careServicesRequest :=
  <csd:careServicesRequest>
    <csd:function urn="{$search}"><requestParams>{$requestParams}</requestParams></csd:function>
  </csd:careServicesRequest>
return
  if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
    csr_proc:process_CSR($csd_webconf:db,$careServicesRequest,$name,$csd_webconf:baseurl)
  else
    (:need appropriate error handling:)
  ()

};

declare updating
  %rest:path("/CSD/csr/{$name}/careServicesRequest/update")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$careServicesRequest}")
  function page:csr_updating($name,$careServicesRequest)
{
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
 csr_proc:process_updating_CSR($csd_webconf:db,$careServicesRequest/careServicesRequest,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr/{$name}/adhoc")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST
  %rest:form-param("adhoc","{$adhoc}")
  %rest:form-param("content", "{$content}","application/xml")
function page:adhoc($name,$adhoc,$content) {
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
let  $adhoc_doc := csr_proc:create_adhoc_doc(string($adhoc),$content)
  return  csr_proc:process_CSR($csd_webconf:db, $adhoc_doc,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr")
  %rest:GET
  %output:method("xhtml")
  function page:csr_list()
{
let $response := page:endpoints()
return csd_webconf:wrapper($response)
};

declare function page:endpoints() {

Care Services Request - Endpoints

      {
	for $name in $page:csd_docs
	return

	  Submit Care Services Request for {$name} at:

{$csd_webconf:baseurl}CSD/csr/{$name}/careServicesRequest

	  Submit ad-hoc query:
	  <form method='post' action="/CSD/csr/{$name}/adhoc"  enctype="multipart/form-data">
	    Ad-Hoc Query<textarea  rows="10" cols="80" name="adhoc" >{$page:sample}</textarea>

	    Content Type<input    cols="80" name="content" value="text/html"/>

	    <input type="submit" value="submit"/>
	  </form>

      }

};

declare variable $page:sample :=
"declare namespace csd = 'urn:ihe:iti:csd:2013';

You have {count(/csd:CSD/csd:providerDirectory/*)} providers.

You have {count(/csd:CSD/csd:facilityDirectory/*)} facilities.

You have {count(/csd:CSD/csd:organizationDirectory/*)} organizations.

You have {count(/csd:CSD/csd:serviceDirectory/*)} services.

";

module namespace page = 'http://basex.org/modules/web-page';

import module namespace csr_proc = "https://github.com/openhie/openinfoman/csr_proc";
import module namespace csd_dm = "https://github.com/openhie/openinfoman/csd_dm";
import module namespace csd_webconf =  "https://github.com/openhie/openinfoman/csd_webconf";

declare   namespace   csd = "urn:ihe:iti:csd:2013";
declare default element  namespace   "urn:ihe:iti:csd:2013";

declare variable $page:csd_docs := csd_dm:registered_documents($csd_webconf:db);

declare
  %rest:path("/CSD/csr/{$name}/careServicesRequest")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$careServicesRequest}")
  function page:csr($name,$careServicesRequest)
{
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
 csr_proc:process_CSR($csd_webconf:db,$careServicesRequest/careServicesRequest,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr/{$name}/careServicesRequest/{$search}")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$requestParams}")
  function page:csr2($name,$requestParams,$search)
{
let $careServicesRequest :=
  <csd:careServicesRequest>
    <csd:function urn="{$search}"><requestParams>{$requestParams}</requestParams></csd:function>
  </csd:careServicesRequest>
return
  if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
    csr_proc:process_CSR($csd_webconf:db,$careServicesRequest,$name,$csd_webconf:baseurl)
  else
    (:need appropriate error handling:)
  ()

};

declare updating
  %rest:path("/CSD/csr/{$name}/careServicesRequest/update")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST("{$careServicesRequest}")
  function page:csr_updating($name,$careServicesRequest)
{
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
 csr_proc:process_updating_CSR($csd_webconf:db,$careServicesRequest/careServicesRequest,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr/{$name}/adhoc")
  %rest:consumes("application/xml", "text/xml", "multipart/form-data")
  %rest:POST
  %rest:form-param("adhoc","{$adhoc}")
  %rest:form-param("content", "{$content}","application/xml")
function page:adhoc($name,$adhoc,$content) {
if (csd_dm:document_source_exists($csd_webconf:db,$name)) then
let  $adhoc_doc := csr_proc:create_adhoc_doc(string($adhoc),$content)
  return  csr_proc:process_CSR($csd_webconf:db, $adhoc_doc,$name,$csd_webconf:baseurl)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr")
  %rest:GET
  %output:method("xhtml")
  function page:csr_list()
{
let $response := page:endpoints()
return csd_webconf:wrapper($response)
};

declare function page:endpoints() {

Care Services Request - Endpoints

      {
	for $name in $page:csd_docs
	return

	  Submit Care Services Request for {$name} at:

{$csd_webconf:baseurl}CSD/csr/{$name}/careServicesRequest

	  Submit ad-hoc query:
	  <form method='post' action="/CSD/csr/{$name}/adhoc"  enctype="multipart/form-data">
	    Ad-Hoc Query<textarea  rows="10" cols="80" name="adhoc" >{$page:sample}</textarea>

	    Content Type<input    cols="80" name="content" value="text/html"/>

	    <input type="submit" value="submit"/>
	  </form>

      }

};

declare variable $page:sample :=
"

You have {count(/csd:CSD/csd:providerDirectory/*)} providers.

You have {count(/csd:CSD/csd:facilityDirectory/*)} facilities.

You have {count(/csd:CSD/csd:organizationDirectory/*)} organizations.

You have {count(/csd:CSD/csd:serviceDirectory/*)} services.

";


Some small changes:
1) declred external variables
2) *item-at*  is depricated

svn path=/trunk/eXist/; revision=8170

(:  This XQuery is used to generate a collection listing
    in response to a GET request on a collection
:)
xquery version "1.0";

(::pragma exist:output-size-limit -1 ::)

import module namespace xdb="http://exist-db.org/xquery/xmldb";

declare namespace f="urn:my-functions";

declare variable $uri external;
declare variable $collection external;

declare variable $f:months {
	("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
	"Nov", "Dec")
};

declare function f:format-date($date as xs:dateTime) as xs:string {
	string-join((
		xs:string($f:months[month-from-date($date)]),
		xs:string(day-from-date($date)),
		xs:string(year-from-date($date))), " ")
};

declare function f:format-int($component as xs:integer) as xs:string {
	if($component lt 10) then
		concat("0", $component)
	else
		xs:string($component)
};

declare function f:format-time($time as xs:dateTime) as xs:string {
	concat(
		f:format-int(hours-from-dateTime($time)), ":",
		f:format-int(minutes-from-dateTime($time)), ":",
		f:format-int(xs:integer(seconds-from-dateTime($time)))
	)
};

declare function f:format-dateTime($dt as xs:dateTime) as xs:string {
    concat(f:format-date($dt), " ", f:format-time($dt))
};

declare function f:display-child-resources($collection as xs:string)
as element()* {
    for $child in xdb:get-child-resources($collection)
    order by $child
    return

            {$child}
            {xdb:permissions-to-string(xdb:get-permissions($collection, $child))}
            {xdb:get-owner($collection, $child)}
            {xdb:get-group($collection, $child)}
            {f:format-dateTime(xdb:created($collection, $child))}
            {f:format-dateTime(xdb:last-modified($collection, $child))}
            {fn:ceiling(xdb:size($collection, $child) div 1024)}

};

declare function f:display-child-collections($collection as xs:string)
as element()* {
    for $child in xdb:get-child-collections($collection)
    let $path := concat($collection, '/', $child),
        $created := xdb:created($path)
    order by $child
    return

            {$child}
            {xdb:permissions-to-string(xdb:get-permissions($path))}
            {xdb:get-owner($path)}
            {xdb:get-group($path)}
            {f:format-dateTime($created)}

};

        <title>{$collection}</title>

Contents of {$collection}

                Name
                Permissions
                Owner
                Group
                Created
                Last Modified

            {f:display-child-collections($collection)}
            {f:display-child-resources($collection)}

(:  This XQuery is used to generate a collection listing
    in response to a GET request on a collection
:)
xquery version "1.0";

(::pragma exist:output-size-limit -1 ::)

import module namespace xdb="http://exist-db.org/xquery/xmldb";

declare namespace f="urn:my-functions";

declare variable $f:months {
	("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
	"Nov", "Dec")
};

declare function f:format-date($date as xs:dateTime) as xs:string {
	string-join((
		xs:string(item-at($f:months, month-from-date($date))),
		xs:string(day-from-date($date)),
		xs:string(year-from-date($date))), " ")
};

declare function f:format-int($component as xs:integer) as xs:string {
	if($component lt 10) then
		concat("0", $component)
	else
		xs:string($component)
};

declare function f:format-time($time as xs:dateTime) as xs:string {
	concat(
		f:format-int(hours-from-dateTime($time)), ":",
		f:format-int(minutes-from-dateTime($time)), ":",
		f:format-int(xs:integer(seconds-from-dateTime($time)))
	)
};

declare function f:format-dateTime($dt as xs:dateTime) as xs:string {
    concat(f:format-date($dt), " ", f:format-time($dt))
};

declare function f:display-child-resources($collection as xs:string)
as element()* {
    for $child in xdb:get-child-resources($collection)
    order by $child
    return

            {$child}
            {xdb:permissions-to-string(xdb:get-permissions($collection, $child))}
            {xdb:get-owner($collection, $child)}
            {xdb:get-group($collection, $child)}
            {f:format-dateTime(xdb:created($collection, $child))}
            {f:format-dateTime(xdb:last-modified($collection, $child))}
            {fn:ceiling(xdb:size($collection, $child) div 1024)}

};

declare function f:display-child-collections($collection as xs:string)
as element()* {
    for $child in xdb:get-child-collections($collection)
    let $path := concat($collection, '/', $child),
        $created := xdb:created($path)
    order by $child
    return

            {$child}
            {xdb:permissions-to-string(xdb:get-permissions($path))}
            {xdb:get-owner($path)}
            {xdb:get-group($path)}
            {f:format-dateTime($created)}

};

        <title>{$collection}</title>

Contents of {$collection}

                Name
                Permissions
                Owner
                Group
                Created
                Last Modified

            {f:display-child-collections($collection)}
            {f:display-child-resources($collection)}