fixed bug where stored function could be added multiple times with same uuid

(:~
: This is the Care Services Discovery RESTful document processor
: @version 1.0
: @see https://github.com/his-interop/openinfoman
:
:)
module namespace csr_proc = "https://github.com/his-interop/openinfoman/csr_proc";

import module namespace csd_bsq = "https://github.com/his-interop/openinfoman/csd_bsq" at "csd_base_stored_queries.xqm";
import module namespace csd_hwr = "https://github.com/his-interop/openinfoman-hwr/csd_hwr" at "csd_health_worker_registry.xqm";
import module namespace csd_hwru = "https://github.com/his-interop/openinfoman-hwr/csd_hwru" at "csd_health_worker_registry_updating.xqm";

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

(:this should proabably be moved to the database :)
declare variable $csr_proc:stored_query_dir := "../resources/stored_query_definitions";
declare variable $csr_proc:stored_updating_query_dir := "../resources/stored_updating_query_definitions";

declare variable $csr_proc:stored_functions_doc := 'stored_functions.xml';
declare variable $csr_proc:stored_updating_functions_doc := 'stored_updating_functions.xml';

declare function csr_proc:stored_functions($db) {
 db:open($db,$csr_proc:stored_functions_doc)/careServicesFunctions/careServicesFunction
};

declare function csr_proc:stored_updating_functions($db) {
 db:open($db,$csr_proc:stored_updating_functions_doc)/careServicesFunctions/csd:careServicesFunction
};

declare updating function csr_proc:init($db) {
  (
    if (not (db:is-xml($db,$csr_proc:stored_updating_functions_doc))) then
      db:add($db, <careServicesFunctions/>,$csr_proc:stored_updating_functions_doc)
    else
      ()
      ,
    if (not (db:is-xml($db,$csr_proc:stored_functions_doc))) then
      db:add($db, <careServicesFunctions/>,$csr_proc:stored_functions_doc)
    else
      ()
  )
};

declare updating function csr_proc:load_functions_from_files($db) {
  (
    if (file:is-dir($csr_proc:stored_query_dir)) then
      for $file in file:list($csr_proc:stored_query_dir,boolean('false'),"*.xml")
      let $func := doc(concat($csr_proc:stored_query_dir,'/',$file))/careServicesFunction
      return if (exists($func)) then csr_proc:load_stored_function($db,$func) else ()
    else()
      ,
    if (file:is-dir($csr_proc:stored_updating_query_dir)) then
      for $file in file:list($csr_proc:stored_updating_query_dir,boolean('false'),"*.xml")
      let $func := doc(concat($csr_proc:stored_updating_query_dir,'/',$file))/careServicesFunction
      return if (exists($func)) then csr_proc:load_stored_updating_function($db,$func) else ()
    else ()
  )
};

declare updating function csr_proc:delete_stored_function($db,$uuid) {
  let $stored_updating_functions := db:open($db,$csr_proc:stored_updating_functions_doc)/careServicesFunctions/*
  let $stored_functions := db:open($db,$csr_proc:stored_functions_doc)/careServicesFunctions/*
  let $functions := ($stored_functions,$stored_updating_functions)

  let $old := $functions[@uuid = $uuid]
  return if ($old) then delete node $old else ()

};

declare updating function csr_proc:load_stored_updating_function($db,$func) {
  let $stored_updating_functions := db:open($db,$csr_proc:stored_updating_functions_doc)/careServicesFunctions
  let $uuid := $func/@uuid
  let $old := $stored_updating_functions/careServicesFunction[@uuid = $uuid]
  return
    if (exists($uuid)) then
      if (exists($old))
	then
	(delete node $old,
	insert node $func into $stored_updating_functions
	)
      else
	insert node $func into $stored_updating_functions
  else ()
};

declare updating function csr_proc:load_stored_function($db,$func) {
  let $stored_functions := db:open($db,$csr_proc:stored_functions_doc)/careServicesFunctions
  let $uuid := $func/@uuid
  let $old := $stored_functions/careServicesFunction[@uuid = $uuid]
  return
    if (exists($uuid) and exists($stored_functions)) then
      if (exists($old))
	then
	(delete node $old,
	insert node $func into $stored_functions
	)
      else
	insert node $func into $stored_functions
    else ()
};

declare function csr_proc:process_CSR($db,$careServicesRequest, $doc)
{
let $func :=$careServicesRequest/function
let $adhoc :=$careServicesRequest/expression
return if (exists($func))
then
  csr_proc:process_CSR_stored($db,$func,$doc)
else if (exists($adhoc))
then
  csr_proc:process_CSR_adhoc($adhoc,$doc)
else
  <rest:response>
    <http:response status="400" message="Invalid care services request.">
      <http:header name="Content-Language" value="en"/>
      <http:header name="Content-Type" value="text/html; charset=utf-8"/>
    </http:response>
  </rest:response>

};

declare function csr_proc:process_CSR_adhoc($expression,$doc)
{

let $expr :=string($expression)
return if ($expr) then
  let $result := xquery:evaluate($expr,map{"":=$doc})
  return(
   <rest:response>
   <http:response status="200" >
      <http:header name="Content-Type" value="{$expression/@content-type}"/>
    </http:response>
  </rest:response>
  ,$result
 )
else
   <rest:response>
     <http:response status="400" message="No ad-hoc expression" />
  </rest:response>
};

declare function csr_proc:process_CSR_stored($db,$function,$doc)
{
let $uuid := $function/@uuid
let $stored_functions := csr_proc:stored_functions($db)
let $definition := $stored_functions[@uuid = $uuid][1]/definition/text()
let $method_name := $stored_functions[@uuid = $uuid][1]/definition/@method
let $method :=  if ($method_name) then function-lookup( xs:QName($method_name), 2) else ()
let $content_type := csr_proc:lookup_stored_content_type($db,$function/@uuid)
let $result0 :=
  if (exists($method)) then
    $method($function/requestParams,$doc)
  else
    if (exists($definition)) then
      xquery:evaluate($definition,map{'':=$doc,'careServicesRequest':=$function/requestParams})
    else
      ()
let $result1:=
  if ($function/@encapsulated) then
    csr_proc:wrap_result($result0,$content_type)
  else $result0
return if ($result0) then
  (
  <rest:response>
    <http:response status="200" >
      <http:header name="Content-Type" value="{$content_type}"/>
    </http:response>
  </rest:response>
  ,
  $result1
  )
else
  <rest:response>
    <http:response status="404" message="No registered function with UUID='{$function/@uuid}.'">
      <http:header name="Content-Language" value="en"/>
      <http:header name="Content-Type" value="text/html; charset=utf-8"/>
    </http:response>
  </rest:response>

};

declare function csr_proc:wrap_result($result,$content-type) {
 <careServicesResponse content-type="{$content-type}"><result>{$result}</result></careServicesResponse>
};

declare function csr_proc:create_adhoc_doc($adhoc_query,$content_type) {
let $content := if ($content_type) then $content_type else "application/xml"
return
 <csd:careServicesRequest xmlns:csd='urn:ihe:iti:csd:2013'>
  <csd:expression content-type='{$content}'>
  {$adhoc_query}
  </csd:expression>
</csd:careServicesRequest>

};

declare updating function csr_proc:process_updating_CSR($db,$careServicesRequest, $doc)
{
(:not allowing ad-hoc updates:)
let $function :=$careServicesRequest//csd:function
let $uuid := $function/@uuid
let $stored_updating_functions := csr_proc:stored_updating_functions($db)
let $method_name := $stored_updating_functions[@uuid = $uuid][1]/csd:definition/@method
let $method :=  if ($method_name) then function-lookup( xs:QName($method_name), 2) else ()
let $content_type := csr_proc:lookup_stored_content_type($db,$function/@uuid)
return  if (exists($method)) then
    db:output(
      $method($function/requestParams,$doc)
    )
  else
    db:output(
    <rest:response>
      <http:response status="404" message="No registered updating function with UUID='{$function/@uuid} or method name '{$method_name}'">
	<http:header name="Content-Language" value="en"/>
	<http:header name="Content-Type" value="text/html; charset=utf-8"/>
      </http:response>
    </rest:response>
       )
};

declare function csr_proc:lookup_stored_content_type($db,$uuid)
{
  let $stored_updating_functions := csr_proc:stored_updating_functions($db)
  let $stored_functions := csr_proc:stored_functions($db)
  return string(($stored_functions[@uuid = $uuid]/@content-type, $stored_updating_functions[@uuid = $uuid]/@content-type  , "text/xml")[1])
};

(:~
: This is the Care Services Discovery RESTful document processor
: @version 1.0
: @see https://github.com/his-interop/openinfoman
:
:)
module namespace csr_proc = "https://github.com/his-interop/openinfoman/csr_proc";

import module namespace csd_bsq = "https://github.com/his-interop/openinfoman/csd_bsq" at "csd_base_stored_queries.xqm";
import module namespace csd_hwr = "https://github.com/his-interop/openinfoman-hwr/csd_hwr" at "csd_health_worker_registry.xqm";
import module namespace csd_hwru = "https://github.com/his-interop/openinfoman-hwr/csd_hwru" at "csd_health_worker_registry_updating.xqm";

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

(:this should proabably be moved to the database :)
declare variable $csr_proc:stored_query_dir := "../resources/stored_query_definitions";
declare variable $csr_proc:stored_updating_query_dir := "../resources/stored_updating_query_definitions";

declare variable $csr_proc:stored_functions_doc := 'stored_functions.xml';
declare variable $csr_proc:stored_updating_functions_doc := 'stored_updating_functions.xml';

declare function csr_proc:stored_functions($db) {
 db:open($db,$csr_proc:stored_functions_doc)/careServicesFunctions/careServicesFunction
};

declare function csr_proc:stored_updating_functions($db) {
 db:open($db,$csr_proc:stored_updating_functions_doc)/careServicesFunctions/csd:careServicesFunction
};

declare updating function csr_proc:init($db) {
  (
    if (not (db:is-xml($db,$csr_proc:stored_updating_functions_doc))) then
      db:add($db, <careServicesFunctions/>,$csr_proc:stored_updating_functions_doc)
    else
      ()
      ,
    if (not (db:is-xml($db,$csr_proc:stored_functions_doc))) then
      db:add($db, <careServicesFunctions/>,$csr_proc:stored_functions_doc)
    else
      ()
  )
};

declare updating function csr_proc:load_functions_from_files($db) {
  (
    if (file:is-dir($csr_proc:stored_query_dir)) then
      for $file in file:list($csr_proc:stored_query_dir,boolean('false'),"*.xml")
      let $func := doc(concat($csr_proc:stored_query_dir,'/',$file))/careServicesFunction
      return if (exists($func)) then csr_proc:load_stored_function($db,$func) else ()
    else()
      ,
    if (file:is-dir($csr_proc:stored_updating_query_dir)) then
      for $file in file:list($csr_proc:stored_updating_query_dir,boolean('false'),"*.xml")
      let $func := doc(concat($csr_proc:stored_updating_query_dir,'/',$file))/careServicesFunction
      return if (exists($func)) then csr_proc:load_stored_updating_function($db,$func) else ()
    else ()
  )
};

declare updating function csr_proc:delete_stored_function($db,$uuid) {
  let $stored_updating_functions := db:open($db,$csr_proc:stored_updating_functions_doc)/careServicesFunctions/*
  let $stored_functions := db:open($db,$csr_proc:stored_functions_doc)/careServicesFunctions/*
  let $functions := ($stored_functions,$stored_updating_functions)

  let $old := $functions[@uuid = $uuid]
  return if ($old) then delete node $old else ()

};

declare updating function csr_proc:load_stored_updating_function($db,$func) {
  let $stored_updating_functions := db:open($db,$csr_proc:stored_updating_functions_doc)/careServicesFunctions
  let $uuid := $func/@uuid
  let $old := $stored_updating_functions[@uuid = $uuid]
  return
    if (exists($uuid)) then
      if (exists($old))
	then
	replace node $old with $func
      else
	insert node $func into $stored_updating_functions
  else ()
};

declare updating function csr_proc:load_stored_function($db,$func) {
  let $stored_functions := db:open($db,$csr_proc:stored_functions_doc)/careServicesFunctions
  let $uuid := $func/@uuid
  let $old := $stored_functions[@uuid = $uuid]
  return
    if (exists($uuid) and exists($stored_functions)) then
      if (exists($old))
	then
	replace node $old with $func
      else
	insert node $func into $stored_functions
    else ()
};

declare function csr_proc:process_CSR($db,$careServicesRequest, $doc)
{
let $func :=$careServicesRequest/function
let $adhoc :=$careServicesRequest/expression
return if (exists($func))
then
  csr_proc:process_CSR_stored($db,$func,$doc)
else if (exists($adhoc))
then
  csr_proc:process_CSR_adhoc($adhoc,$doc)
else
  <rest:response>
    <http:response status="400" message="Invalid care services request.">
      <http:header name="Content-Language" value="en"/>
      <http:header name="Content-Type" value="text/html; charset=utf-8"/>
    </http:response>
  </rest:response>

};

declare function csr_proc:process_CSR_adhoc($expression,$doc)
{

let $expr :=string($expression)
return if ($expr) then
  let $result := xquery:evaluate($expr,map{"":=$doc})
  return(
   <rest:response>
   <http:response status="200" >
      <http:header name="Content-Type" value="{$expression/@content-type}"/>
    </http:response>
  </rest:response>
  ,$result
 )
else
   <rest:response>
     <http:response status="400" message="No ad-hoc expression" />
  </rest:response>
};

declare function csr_proc:process_CSR_stored($db,$function,$doc)
{
let $uuid := $function/@uuid
let $stored_functions := csr_proc:stored_functions($db)
let $definition := $stored_functions[@uuid = $uuid][1]/definition/text()
let $method_name := $stored_functions[@uuid = $uuid][1]/definition/@method
let $method :=  if ($method_name) then function-lookup( xs:QName($method_name), 2) else ()
let $content_type := csr_proc:lookup_stored_content_type($db,$function/@uuid)
let $result0 :=
  if (exists($method)) then
    $method($function/requestParams,$doc)
  else
    if (exists($definition)) then
      xquery:evaluate($definition,map{'':=$doc,'careServicesRequest':=$function/requestParams})
    else
      ()
let $result1:=
  if ($function/@encapsulated) then
    csr_proc:wrap_result($result0,$content_type)
  else $result0
return if ($result0) then
  (
  <rest:response>
    <http:response status="200" >
      <http:header name="Content-Type" value="{$content_type}"/>
    </http:response>
  </rest:response>
  ,
  $result1
  )
else
  <rest:response>
    <http:response status="404" message="No registered function with UUID='{$function/@uuid}.'">
      <http:header name="Content-Language" value="en"/>
      <http:header name="Content-Type" value="text/html; charset=utf-8"/>
    </http:response>
  </rest:response>

};

declare function csr_proc:wrap_result($result,$content-type) {
 <careServicesResponse content-type="{$content-type}"><result>{$result}</result></careServicesResponse>
};

declare function csr_proc:create_adhoc_doc($adhoc_query,$content_type) {
let $content := if ($content_type) then $content_type else "application/xml"
return
 <csd:careServicesRequest xmlns:csd='urn:ihe:iti:csd:2013'>
  <csd:expression content-type='{$content}'>
  {$adhoc_query}
  </csd:expression>
</csd:careServicesRequest>

};

declare updating function csr_proc:process_updating_CSR($db,$careServicesRequest, $doc)
{
(:not allowing ad-hoc updates:)
let $function :=$careServicesRequest//csd:function
let $uuid := $function/@uuid
let $stored_updating_functions := csr_proc:stored_updating_functions($db)
let $method_name := $stored_updating_functions[@uuid = $uuid][1]/csd:definition/@method
let $method :=  if ($method_name) then function-lookup( xs:QName($method_name), 2) else ()
let $content_type := csr_proc:lookup_stored_content_type($db,$function/@uuid)
return  if (exists($method)) then
    db:output(
      $method($function/requestParams,$doc)
    )
  else
    db:output(
    <rest:response>
      <http:response status="404" message="No registered updating function with UUID='{$function/@uuid} or method name '{$method_name}'">
	<http:header name="Content-Language" value="en"/>
	<http:header name="Content-Type" value="text/html; charset=utf-8"/>
      </http:response>
    </rest:response>
       )
};

declare function csr_proc:lookup_stored_content_type($db,$uuid)
{
  let $stored_updating_functions := csr_proc:stored_updating_functions($db)
  let $stored_functions := csr_proc:stored_functions($db)
  return string(($stored_functions[@uuid = $uuid]/@content-type, $stored_updating_functions[@uuid = $uuid]/@content-type  , "text/xml")[1])
};


Begin annotating and correcting signatures.

xquery version "3.0";
(:~
: BaseX Database Module functions
:
: @see http://docs.basex.org/wiki/Database_Module
:)
module namespace db = "http://basex.org/modules/db";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "7.0") function db:system() as element(system) external;
declare %a:since("basex", "7.0") function db:option($name as xs:string) as xs:string external;
declare %a:since("basex", "7.0") function db:info($db as xs:string) as element(database) external;
declare %a:since("basex", "7.0") function db:property($db as xs:string, $name as xs:string) as xs:anyAtomicType external;
declare %a:since("basex", "7.0") function db:list() as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string) as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string, $path as xs:string) as xs:string* external;
declare %a:since("basex", "7.1") function db:list-details() as element(database)* external;
declare %a:since("basex", "7.1") function db:list-details($db as xs:string) as element(resource)* external;
declare %a:since("basex", "7.1") function db:list-details($db as xs:string, $path as xs:string) as element(resource)* external;
declare %a:since("basex", "7.5") function db:backups() as element(backup)* external;
declare %a:since("basex", "7.5") function db:backups($db as xs:string) as element(backup)* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string, $path as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open-pre($db as xs:string, $pre as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:open-id($db as xs:string, $id as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:node-pre($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:node-id($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:text($db as xs:string, $strings as xs:string*) as text()* external;
declare %a:since("basex", "7.2.1") function db:text-range($db as xs:string, $min as xs:string, $max as xs:string) as text()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as xs:string*) as attribute()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as xs:strings*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.2.1") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string) as attribute()* external;
declare %a:since("basex", "7.2.1") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.0") function db:token($db as xs:string, $tokens as xs:string*) as attribute()* external;
declare %a:since("basex", "7.0") function db:token($db as xs:string, $tokens as xs:string*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.5") function db:create($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.5") function db:drop($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:delete($db as xs:string, $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:copy($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:alter($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:create-backup($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:drop-backup($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.8.2") function db:restore($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:rename($db as xs:string, $source as xs:string, $target as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item(), $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:store($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.3") function db:flush($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.7") function db:name($node as node()) as xs:string external;
declare %a:since("basex", "7.7") function db:path($node as node()) as xs:string external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-raw($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-xml($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.1") function db:content-type($db as xs:string, $path as xs:string) as xs:string external;
declare %a:since("basex", "7.2.1") %a:until("basex", "9.0") %a:see-also("basex", "9.0", "update:output") function db:output() external;
declare %a:since("basex", "8.2") %a:until("basex", "9.0") %a:see-also("basex", "9.0", "update:cache") function db:output-cache() external;
declare %a:since("basex", "7.7") %a:until("basex", "..") function db:export() external;
declare %a:since("basex", "7.0") %a:until("basex", "7.8") %a:see-also("basex", "7.8", "ft:search") function db:fulltext() external;
declare %a:since("basex", "..") %a:until("basex", "8.2") function db:event() external;

xquery version "3.0";
(:~
: BaseX Database Module functions
:
: @see http://docs.basex.org/wiki/Database_Module
:)
module namespace db = "http://basex.org/modules/db";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "7.0") function db:system() as element(system) external;
declare %a:since("basex", "7.0") function db:option($name as xs:string) as xs:string external;
declare %a:since("basex", "7.0") function db:info($db as xs:string) as element(database) external;
declare %a:since("basex", "7.0") function db:property($db as xs:string, $name as xs:string) as xs:anyAtomicType external;
declare %a:since("basex", "7.0") function db:list() as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string) as xs:string* external;
declare %a:since("basex", "7.0") function db:list($db as xs:string, $path as xs:string) as xs:string* external;
declare %a:since("basex", "7.0") function db:list-details() as element(database)* external;
declare %a:since("basex", "7.0") function db:list-details($db as xs:string) as element(resource)* external;
declare %a:since("basex", "7.0") function db:list-details($db as xs:string, $path as xs:string) as element(resource)* external;
declare %a:since("basex", "7.0") function db:backups() as element(backup)* external;
declare %a:since("basex", "7.0") function db:backups($db as xs:string) as element(backup)* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open($db as xs:string, $path as xs:string) as document-node()* external;
declare %a:since("basex", "7.0") function db:open-pre($db as xs:string, $pre as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:open-id($db as xs:string, $id as xs:integer) as node() external;
declare %a:since("basex", "7.0") function db:node-pre($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:node-id($nodes as node()*) as xs:integer* external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:retrieve($db as xs:string, $path as xs:string) as xs:base64Binary external;
declare %a:since("basex", "7.0") function db:text($db as xs:string, $strings as xs:string*) as text()* external;
declare %a:since("basex", "7.0") function db:text-range($db as xs:string, $min as xs:string, $max as xs:string) as text()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as as xs:string*) as attribute()* external;
declare %a:since("basex", "7.0") function db:attribute($db as xs:string, $strings as xs:strings*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.0") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string) as attribute()* external;
declare %a:since("basex", "7.0") function db:attribute-range($db as xs:string, $min as xs:string, $max as xs:string, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.0") function db:token($db as xs:string, $tokens as xs:string*) as attribute()* external;
declare %a:since("basex", "7.0") function db:token($db as xs:string, $tokens as xs:string*, $name as xs:string) as attribute()* external;
declare %a:since("basex", "7.0") function db:create($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:create($db as xs:string, $inputs as item()*) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:create($db as xs:string, $inputs as item()*, $paths as xs:string*, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:drop($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:add($db as xs:string, $input as item(), $path as xs:string, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:delete($db as xs:string, $path as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:copy($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:alter($db as xs:string, $name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:create-backup($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:drop-backup($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:restore($name as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:optimize($db as xs:string, $all as xs:boolean, $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:rename($db as xs:string, $source as xs:string, $target as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:replace($db as xs:string, $path as xs:string, $input as item(), $options as map(*)?) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:store($db as xs:string, $path as xs:string, $input as item()) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:flush($db as xs:string) as empty-sequence() external;
declare %a:since("basex", "7.0") function db:name($node as node()) as xs:string external;
declare %a:since("basex", "7.0") function db:path($node as node()) as xs:string external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:exists($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-raw($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:is-xml($db as xs:string, $path as xs:string) as xs:boolean external;
declare %a:since("basex", "7.0") function db:content-type($db as xs:string, $path as xs:string) as xs:string external;


Fix #144 Flash Error Message Overlaps with Breadcrumbs When Action Tabs are Hidden

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

import module namespace calli = "http://callimachusproject.org/rdf/2009/framework#" at "/callimachus/layout-functions.xq";

    <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,target-densityDpi=device-dpi"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link rel="icon" href="/favicon.ico" />
    {calli:styles-href(<link rel="stylesheet" />)}
    {calli:scripts-src(
    <![endif]-->
    {calli:head-nodes()}

    {calli:body-attributes()}

                    {calli:home-href(Callimachus)}

                    {calli:login-href(Sign in )}

{calli:lookup-form('Lookup...')}

                        <button type="button" class="btn btn-default navbar-btn dropdown-toggle" data-toggle="dropdown">
                            Main menu

                        </button>

{calli:folder-href(Home folder)}

{calli:changes-href(Recent changes)}

{calli:lookup-href(Lookup resources)}

{calli:callimachus-about-href(About Callimachus)}

{calli:callimachus-getting-started-href(Getting started)}

{calli:callimachus-feedback-href(Send feedback)}

                            {calli:head-links(

,
)}

{calli:whatlinkshere-href(What links here)}

{calli:relatedchanges-href(Related changes)}

{calli:permissions-href(Permissions)}

{calli:introspect-href(Introspect resource)}

Print this page

{calli:profile-href(Account)}

{calli:logout-href(Sign out)}

{calli:breadcrumb-links(

,
)}

        {calli:activate-nav(

{calli:view-href(View)}

{calli:edit-href(Edit)}

{calli:discussion-href(Discussion)}

{calli:describe-href(Describe)}

{calli:history-href(History)}

        )}

        {calli:error-alert(

            <button type="button" class="close" data-dismiss="alert">×</button>

Oops!

)}

    {calli:body-nodes()}

                {calli:generator-p(
)}
                {calli:lastmod-time(
This resource was last modified at <time class="datetime-local"/>
)}


minor modification to merge bindings

minor modification to merge bindings

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_mcs = "https://github.com/openhie/openinfoman/csd_mcs";
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 function page:redirect($redirect as xs:string) as element(restxq:redirect)
{
  <restxq:redirect>{ $redirect }</restxq:redirect>
};

declare function page:nocache($response) {
(<http:response status="200" message="OK">

  <http:header name="Cache-Control" value="must-revalidate,no-cache,no-store"/>
</http:response>,
$response)
};

declare function page:is_merge($search_name) {
  let $ufunction := csr_proc:get_updating_function_definition($csd_webconf:db,$search_name)
  let $ext := $ufunction//csd:extension[  @urn='urn:openhie.org:openinfoman:adapter' and @type='merge']
  return (count($ext) > 0)
};

declare
  %rest:path("/CSD/csr/{$doc_name}/careServicesRequest/{$search_name}/adapter/merge")
  %output:method("xhtml")
  %rest:GET
  function page:show_endpoints($search_name,$doc_name)
{
    if (not(page:is_merge($search_name)) )
      then concat('Not a stored function for a merge: ' , $search_name    )
    else
      let $action := concat("/CSD/csr/",$doc_name,"/careServicesRequest/",$search_name, "/adapter/merge")
      let $ufunction := csr_proc:get_updating_function_definition($csd_webconf:db,$search_name)
      let $contents :=

Merge into {$doc_name}

Merge Cached Service Directoriesn

{$ufunction/csd:description}

	      <form method='POST' action="{$action}">
		{
		  let $docs := csd_dm:registered_documents($csd_webconf:db)
		  return

		    {
		      for $doc in $docs
		      where not($doc = $doc_name)
		      return (<input type='checkbox'  name="merge" value="{$doc}">{$doc}</input>,
)
		    }

		    <input type='submit' value='Merge'/>

		}
	      </form>

      return csd_webconf:wrapper($contents)
};

declare updating
  %rest:path("/CSD/csr/{$doc_name}/careServicesRequest/{$search_name}/adapter/merge")
  %output:method("xhtml")
  %rest:query-param("merge", "{$merge}")
  %rest:POST
  function page:perform_merge($search_name,$doc_name,$merge)
{
  let $doc :=  csd_dm:open_document($csd_webconf:db,$doc_name)
  let $function := csr_proc:get_function_definition($csd_webconf:db,$search_name)
  let $action := concat("/CSD/csr/",$doc_name,"/careServicesRequest/",$search_name, "/adapter/merge")
  let $careServicesRequest :=
    <csd:careServicesRequest>
      <csd:function urn="{$search_name}" resource="{$doc_name}" base_url="{$csd_webconf:baseurl}">
        <csd:requestParams >
	  <documents >
	    {
              for $name in $merge
	      where not ($name = $doc_name)
	      return  <document resource="{$name}"/>
	    }
	  </documents>
        </csd:requestParams >
      </csd:function>
    </csd:careServicesRequest>

    return
      (
	csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$careServicesRequest)
	,
	db:output(page:redirect(concat($csd_webconf:baseurl,$action)))
      )
};

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_mcs = "https://github.com/openhie/openinfoman/csd_mcs";
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 function page:redirect($redirect as xs:string) as element(restxq:redirect)
{
  <restxq:redirect>{ $redirect }</restxq:redirect>
};

declare function page:nocache($response) {
(<http:response status="200" message="OK">

  <http:header name="Cache-Control" value="must-revalidate,no-cache,no-store"/>
</http:response>,
$response)
};

declare function page:is_merge($search_name) {
  let $ufunction := csr_proc:get_updating_function_definition($csd_webconf:db,$search_name)
  let $ext := $ufunction//csd:extension[  @urn='urn:openhie.org:openinfoman:adapter' and @type='merge']
  return (count($ext) > 0)
};

declare
  %rest:path("/CSD/csr/{$doc_name}/careServicesRequest/{$search_name}/adapter/merge")
  %output:method("xhtml")
  %rest:GET
  function page:show_endpoints($search_name,$doc_name)
{
    if (not(page:is_merge($search_name)) )
      then concat('Not a stored function for a merge: ' , $search_name    )
    else
      let $action := concat("/CSD/csr/",$doc_name,"/careServicesRequest/",$search_name, "/adapter/merge")
      let $ufunction := csr_proc:get_updating_function_definition($csd_webconf:db,$search_name)
      let $contents :=

Merge into {$doc_name}

Merge Cached Service Directoriesn

{$ufunction/csd:description}

	      <form method='POST' action="{$action}">
		{
		  let $docs := csd_dm:registered_documents($csd_webconf:db)
		  return

		    {
		      for $doc in $docs
		      where not($doc = $doc_name)
		      return (<input type='checkbox'  name="merge" value="{$doc}">{$doc}</input>,
)
		    }

		    <input type='submit' value='Merge'/>

		}
	      </form>

      return csd_webconf:wrapper($contents)
};

declare updating
  %rest:path("/CSD/csr/{$doc_name}/careServicesRequest/{$search_name}/adapter/merge")
  %output:method("xhtml")
  %rest:query-param("merge", "{$merge}")
  %rest:POST
  function page:perform_merge($search_name,$doc_name,$merge)
{
  let $doc :=  csd_dm:open_document($csd_webconf:db,$doc_name)
  let $function := csr_proc:get_function_definition($csd_webconf:db,$search_name)
  let $action := concat("/CSD/csr/",$doc_name,"/careServicesRequest/",$search_name, "/adapter/merge")
  let $careServicesRequest :=
    <csd:careServicesRequest>
      <csd:function urn="{$search_name}" resource="{$doc_name}" base_url="{$csd_webconf:baseurl}">
        <csd:requestParams >
	  <documents >
	    {
              for $name in $merge
	      where not ($name = $doc_name)
	      return  <document resource='{$name}'/>
	    }
	  </documents>
        </csd:requestParams >
      </csd:function>
    </csd:careServicesRequest>

    return
      (
	csr_proc:process_updating_CSR_stored_results($csd_webconf:db, $doc,$careServicesRequest),
	db:output(page:redirect(concat($csd_webconf:baseurl,$action)))
      )
};


First take at morphology.

First take at morphology.

declare variable $pos := //parts-of-speech;
declare variable $morph := //morphology;

declare function local:morph-description($tag, $category)
{
   $morph/field[@tag=$category]/value[@tag=$tag]/@summary ! string(.)
};

declare function local:number($morph as xs:string)
{
  let $tag := substring($morph,2,1)
  where $tag != "-"
  return
    attribute number {
      local:morph-description($tag, "number")
    }
};

declare function local:person($morph as xs:string)
{
  let $tag := substring($morph,1,1)
  where $tag != "-"
  return
    attribute person {
      tokenize(local:morph-description($tag, "person"))[1]
    }
};

declare function local:gender($morph as xs:string)
{
  let $tag := substring($morph,6,1)
  where $tag != "-"
  return
    attribute gender {
      local:morph-description($tag,"gender")
    }
};

declare function local:case($morph as xs:string)
{
  let $tag := substring($morph,7,1)
  where $tag != "-"
  return
    attribute case {
      local:morph-description($tag,"case")
    }
};

declare function local:tense($morph as xs:string)
{
  let $tag := substring($morph,3,1)
  where $tag != "-"
  return
    attribute tense {
      local:morph-description($tag,"tense")
    }
};

declare function local:voice($morph as xs:string)
{
  let $tag := substring($morph,5,1)
  where $tag != "-"
  return
    attribute voice {
      local:morph-description($tag,"voice")
    }
};

declare function local:mood($morph as xs:string)
{
  let $tag := substring($morph,4,1)
  where $tag != "-"
  return
    attribute mood {
      local:morph-description($tag,"mood")
    }
};

declare function local:degree($morph as xs:string)
{
  let $tag := substring($morph,8,1)
  where $tag != "-"
  return
    attribute degree {
      local:morph-description($tag,"degree")
    }
};

declare function local:strength($morph as xs:string)
{
  let $tag := substring($morph,9,1)
  where $tag != "-"
  return
    attribute strength {
      local:morph-description($tag,"strength")
    }
};

declare function local:inflection($morph as xs:string)
{
  let $tag := substring($morph,10,1)
  where $tag != "-"
  return
    attribute inflection {
      local:morph-description($tag,"inflection")
    }
};

declare function local:morphology($t)
{
  let $morph := string($t/@morphology)
  where $morph
  return (
    local:number($morph),
    local:person($morph),
    local:gender($morph),
    local:case($morph),
    local:tense($morph),
    local:voice($morph),
    local:mood($morph),
    local:degree($morph),
    local:strength($morph),
    local:inflection($morph)
  )
};

declare function local:class($t)
{
  let $description :=  string($pos/value[@tag = $t/@part-of-speech]/@summary)
  let $class :=
    switch ($description)
      case "interrogative adverb" return "adverb"
      case "relative adverb" return "adverb"
      case "common noun" return "noun"
      case "proper noun" return "noun"
      case "cardinal numeral" return "numeral"
      case "ordinal numeral" return "numeral"
      case "demonstrative pronoun" return "pronoun"
      case "indefinite pronoun" return "pronoun"
      case "interrogative pronoun" return "pronoun"
      case "relative pronoun" return "pronoun"
      case "personal pronoun" return "pronoun"
      case "personal reflexive pronoun" return "pronoun"
      case "possessive pronoun" return "pronoun"
      case "possessive reflexive pronoun" return "pronoun"
      case "reciprocal pronoun" return "pronoun"
      case "" return ()
      default return $description
  let $type :=
    switch ($description)
      case "interrogative adverb" return "interrogative"
      case "relative adverb" return "relative"
      case "common noun" return "common"
      case "proper noun" return "proper"
      case "cardinal numeral" return "cardinal"
      case "ordinal numeral" return "ordinal"
      case "demonstrative pronoun" return "demonstrative"
      case "indefinite pronoun" return "indefinite"
      case "interrogative pronoun" return "interrogative"
      case "relative pronoun" return "relative"
      case "personal pronoun" return "personal"
      case "personal reflexive pronoun" return "personal relative"
      case "possessive pronoun" return "possessive"
      case "possessive reflexive pronoun" return "possessive reflexive"
      case "reciprocal pronoun" return "reciprocal"
      default return ()
  return
    (
      $class ! attribute class {$class},
      $type ! attribute type {$type}
    )
};

declare function local:token($t)
{
  <w>
    {
      local:class($t),
      attribute role {$t/@relation},
      local:morphology($t),
      attribute id {$t/@id},
      $t/@head-id ! attribute head-id {$t/@head-id }
    }
    {
      string($t/@form)
    }
  </w>,
  $t/@presentation-after[. != ' '] ! <pc>{string(.)}</pc>
};

declare function local:unwrap($t, $stok)
{
  let $children :=  $stok[@head-id = $t/@id]
  let $seq := ($children | $t)/.
  return
    if ($children)
    then
      <wg role="{$t/@relation}">
        {
          for $s in $seq
          return
            if ($s is $t)
            then local:token($t)
            else local:unwrap($s, $stok)
        }
      </wg>
    else local:token($t)
};

declare function local:sentence($s)
{
  <sentence>
    {
      attribute id { $s/@id }
    }
    {
      let $stok := $s//token
      for $t in $stok[not(@head-id)]
      return local:unwrap($t, $stok)
    }
  </sentence>
};

<?xml-stylesheet href="treedown.css"?>,
<?xml-stylesheet href="boxwood.css"?>,
<book>
  {
    for $s in //sentence
    return local:sentence($s)
  }
</book>

declare variable $pos := //parts-of-speech;

declare function local:pos($t)
{
  let $description :=  string($pos/value[@tag = $t/@part-of-speech]/@summary)
  let $class :=
    switch ($description)
      case "interrogative adverb" return "adverb"
      case "relative adverb" return "adverb"
      case "common noun" return "noun"
      case "proper noun" return "noun"
      case "cardinal numeral" return "numeral"
      case "ordinal numeral" return "numeral"
      case "demonstrative pronoun" return "pronoun"
      case "indefinite pronoun" return "pronoun"
      case "interrogative pronoun" return "pronoun"
      case "relative pronoun" return "pronoun"
      case "personal pronoun" return "pronoun"
      case "personal reflexive pronoun" return "pronoun"
      case "possessive pronoun" return "pronoun"
      case "possessive reflexive pronoun" return "pronoun"
      case "reciprocal pronoun" return "pronoun"
      case "" return ()
      default return $description
  let $type :=
    switch ($description)
      case "interrogative adverb" return "interrogative"
      case "relative adverb" return "relative"
      case "common noun" return "common"
      case "proper noun" return "proper"
      case "cardinal numeral" return "cardinal"
      case "ordinal numeral" return "ordinal"
      case "demonstrative pronoun" return "demonstrative"
      case "indefinite pronoun" return "indefinite"
      case "interrogative pronoun" return "interrogative"
      case "relative pronoun" return "relative"
      case "personal pronoun" return "personal"
      case "personal reflexive pronoun" return "personal relative"
      case "possessive pronoun" return "possessive"
      case "possessive reflexive pronoun" return "possessive reflexive"
      case "reciprocal pronoun" return "reciprocal"
      default return ()
  return
    (
      $class ! attribute class {$class},
      $type ! attribute type {$type}
    )
};

declare function local:token($t)
{
  <w>
    {
      local:pos($t),
      attribute role {$t/@relation},
      attribute id {$t/@id},
      $t/@head-id ! attribute head-id {$t/@head-id }
    }
    {
      string($t/@form)
    }
  </w>,
  $t/@presentation-after[. != ' '] ! <pc>{string(.)}</pc>
};

declare function local:unwrap($t, $stok)
{
  let $children :=  $stok[@head-id = $t/@id]
  let $seq := ($children | $t)/.
  return
    if ($children)
    then
      <wg role="{$t/@relation}">
        {
          for $s in $seq
          return
            if ($s is $t)
            then local:token($t)
            else local:unwrap($s, $stok)
        }
      </wg>
    else local:token($t)
};

declare function local:sentence($s)
{
  <sentence>
    {
      attribute id { $s/@id }
    }
    {
      let $stok := $s//token
      for $t in $stok[not(@head-id)]
      return local:unwrap($t, $stok)
    }
  </sentence>
};

<?xml-stylesheet href="treedown.css"?>,
<?xml-stylesheet href="boxwood.css"?>,
<book>
  {
    for $s in //sentence
    return local:sentence($s)
  }
</book>


enabling the auto close of pop up window after the item selection is done

xquery version "1.0";
(: ~
: Module Name:             Reference URI search popup
:
: Module Version           1.0
:
: Date                     08 Jul 2008
:
: Copyright                The cagrid consortium
:
: Module overview          Finds a reference uri for an administered item
:
:)

(:~
:    @author Andrew Tsui
:    @version 1.0
~ :)
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace rs="http://cagrid.org/schema/result-set";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace op="http://www.w3.org/2002/11/xquery-operators";

declare namespace c="http://cagrid.org/schema/config";
declare namespace q="http://cagrid.org/schema/query";

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

import module namespace
    lib-uri-resolution="http://www.cagrid.org/xquery/library/resolver"
    at "../resolver/m-lib-uri-resolution.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("{self.close();", "window.opener.document.getElementById('",$control,"').value='",$value,"';",
            "window.opener.document.getElementById('", $control, "-div').innerHTML='",$name,"';",
            "}")}
      }

};

declare option exist:serialize "media-type=text/html";
session:create(),
let $resource as xs:string := xs:string(request:get-parameter("resource", "EVS-DescLogicConcept"))
let $element as xs:string := xs:string(request:get-parameter("element", ""))
let $form-name as xs:string := xs:string(request:get-parameter("form-name", ""))
let $phrase as xs:string := xs:string(request:get-parameter("phrase", ""))
let $control as xs:string := xs:string(request:get-parameter("control", ""))
let $start as xs:int := xs:int(request:get-parameter("start", 0))
let $count as xs:int := xs:int(request:get-parameter("count", 50))
let $request as xs:string := xs:string(request:get-parameter("request",""))

(:
let $log := util:log-system-out($element)
let $log := util:log-system-out($control)
:)

return

          <title>Searching for a reference uri</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"/>

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

                  Search

                      <input type='text' name='phrase' value='{$phrase}'/>
                      <select name="resource">
                           {lib-qs:selectResource-form('CONCEPT')}
                      </select>

                  <input type="submit" value="Submit query" class="cgButton"/>

                    LexEVS REST interface supports case sensitive search only at this time!

            {

                let $concepts :=
                    if ($request != "")
                        then (lib-qs:query($request,$resource)//rs:concept)
                    else
                        if ($phrase != "")
                            then (lib-qs:query($resource, (), $phrase, $start, $count)//rs:concept)
                    else ()
                  for $concept in $concepts
                  let $id := $concept/rs:names/rs:id
                  let $name := $concept/rs:names/rs:preferred
                  let $definition := $concept/rs:definition
                  return

                         {lib-uri-resolution:html-anchor($id)}
                          {$name}: {$definition}
                          {local:action-button($id, $element, "use this term", $name)}

            }

            {
                let $recordCounter :=
                    if ($request != "")
                        then (lib-qs:query($request,$resource)//rs:recordCounter)
                    else
                        if ($phrase != "")
                            then (lib-qs:query($resource, (), $phrase, $start, $count)//rs:recordCounter)
                    else ()

                    let $div := xs:integer(xs:integer($recordCounter) div xs:integer($count))
                    let $mod := xs:integer($recordCounter mod $count)
                    let $div:=
                        if (exists($div))
                        then
                            if($mod !=0)
                            then
                                let $div := xs:integer(xs:integer($div) + xs:integer(1))
                            return $div
                            else
                                let $div:=$div
                            return $div
                        else()
                    let $query := lib-qs:getURL($resource, (), $phrase, $start, $count)
                    let $increment := xs:integer(50)
                    let $div:=xs:integer($div)-xs:integer(1)
                    for $i in (0 to $div)
                    return
                    (
                           if($i gt 0)
                           then
                           (
                               {$i+1}
                            )
                           else(
                               {$i+1}
                           )
                    )
            }

            </form>

(: works

            {
                let $concepts :=
                    if ($request != "")
                        then (lib-qs:query($request,$resource)//rs:concept)
                    else
                        if ($phrase != "")
                            then (lib-qs:query($resource, (), $phrase, $start, $count)//rs:concept)
                    else ()
                  for $concept in $concepts
                  let $log:=util:log-system-out($concept)
                  let $id := $concept/rs:names/rs:id
                  let $name := $concept/rs:names/rs:preferred
                  let $definition := $concept/rs:definition
                  return

                         {lib-uri-resolution:html-anchor($id)}
                          {$name}: {$definition}
                          {local:action-button($id, $element, "use this term", $name)}

            }

            {
                if (($phrase != "") and ($resource != ""))
                then
                (
                    let $pages := lib-qs:query($resource, (), $phrase, $start, $count)//rs:pages
                    for $page in $pages/rs:page
                        let $pagelink:= encode-for-uri($page/rs:pageurl)
                        let $log:= util:log-system-err($pagelink)
                        let $pagenum:= $page/rs:pagenum
                    return

                       {$pagenum}

                )
                else ()
            }

            {
                if (($phrase != "") and ($resource != ""))
                then
                (
                let $nextlink := lib-qs:query($resource, (), $phrase, $start, $count)//rs:next
                return

                    {$nextlink/rs:nextname}

                )
                else ()
             }

:)

            (:
            {
                let $pages := if ($phrase)
                    then lib-qs:query($resource, (), $phrase, $start, $count)//rs:pages
                else ()
                for $page in $pages/rs:page
                    let $pagelink:= $page/rs:pageurl
                    let $pagenum:= $page/rs:pagenum
                return

                    {$pagenum}

            }
              {
                    let $nextlink := if ($phrase)
                        then lib-qs:query($resource, (), $phrase, $start, $count)//rs:next
                        else ()
                    return
                        {$nextlink/rs:nextname}
             }
            :)

xquery version "1.0";
(: ~
: Module Name:             Reference URI search popup
:
: Module Version           1.0
:
: Date                     08 Jul 2008
:
: Copyright                The cagrid consortium
:
: Module overview          Finds a reference uri for an administered item
:
:)

(:~
:    @author Andrew Tsui
:    @version 1.0
~ :)
declare namespace request="http://exist-db.org/xquery/request";
declare namespace session="http://exist-db.org/xquery/session";
declare namespace rs="http://cagrid.org/schema/result-set";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace op="http://www.w3.org/2002/11/xquery-operators";

declare namespace c="http://cagrid.org/schema/config";
declare namespace q="http://cagrid.org/schema/query";

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

import module namespace
    lib-uri-resolution="http://www.cagrid.org/xquery/library/resolver"
    at "../resolver/m-lib-uri-resolution.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";
session:create(),
let $resource as xs:string := xs:string(request:get-parameter("resource", "EVS-DescLogicConcept"))
let $element as xs:string := xs:string(request:get-parameter("element", ""))
let $form-name as xs:string := xs:string(request:get-parameter("form-name", ""))
let $phrase as xs:string := xs:string(request:get-parameter("phrase", ""))
let $control as xs:string := xs:string(request:get-parameter("control", ""))
let $start as xs:int := xs:int(request:get-parameter("start", 0))
let $count as xs:int := xs:int(request:get-parameter("count", 50))
let $request as xs:string := xs:string(request:get-parameter("request",""))

(:
let $log := util:log-system-out($element)
let $log := util:log-system-out($control)
:)

return

          <title>Searching for a reference uri</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"/>

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

                  Search

                      <input type='text' name='phrase' value='{$phrase}'/>
                      <select name="resource">
                           {lib-qs:selectResource-form('CONCEPT')}
                      </select>

                  <input type="submit" value="Submit query" class="cgButton"/>

                    LexEVS REST interface supports case sensitive search only at this time!

            {

                let $concepts :=
                    if ($request != "")
                        then (lib-qs:query($request,$resource)//rs:concept)
                    else
                        if ($phrase != "")
                            then (lib-qs:query($resource, (), $phrase, $start, $count)//rs:concept)
                    else ()
                  for $concept in $concepts
                  let $id := $concept/rs:names/rs:id
                  let $name := $concept/rs:names/rs:preferred
                  let $definition := $concept/rs:definition
                  return

                         {lib-uri-resolution:html-anchor($id)}
                          {$name}: {$definition}
                          {local:action-button($id, $element, "use this term", $name)}

            }

            {
                let $recordCounter :=
                    if ($request != "")
                        then (lib-qs:query($request,$resource)//rs:recordCounter)
                    else
                        if ($phrase != "")
                            then (lib-qs:query($resource, (), $phrase, $start, $count)//rs:recordCounter)
                    else ()

                    let $div := xs:integer(xs:integer($recordCounter) div xs:integer($count))
                    let $mod := xs:integer($recordCounter mod $count)
                    let $div:=
                        if (exists($div))
                        then
                            if($mod !=0)
                            then
                                let $div := xs:integer(xs:integer($div) + xs:integer(1))
                            return $div
                            else
                                let $div:=$div
                            return $div
                        else()
                    let $query := lib-qs:getURL($resource, (), $phrase, $start, $count)
                    let $increment := xs:integer(50)
                    let $div:=xs:integer($div)-xs:integer(1)
                    for $i in (0 to $div)
                    return
                    (
                           if($i gt 0)
                           then
                           (
                               {$i+1}
                            )
                           else(
                               {$i+1}
                           )
                    )
            }

            </form>

(: works

            {
                let $concepts :=
                    if ($request != "")
                        then (lib-qs:query($request,$resource)//rs:concept)
                    else
                        if ($phrase != "")
                            then (lib-qs:query($resource, (), $phrase, $start, $count)//rs:concept)
                    else ()
                  for $concept in $concepts
                  let $log:=util:log-system-out($concept)
                  let $id := $concept/rs:names/rs:id
                  let $name := $concept/rs:names/rs:preferred
                  let $definition := $concept/rs:definition
                  return

                         {lib-uri-resolution:html-anchor($id)}
                          {$name}: {$definition}
                          {local:action-button($id, $element, "use this term", $name)}

            }

            {
                if (($phrase != "") and ($resource != ""))
                then
                (
                    let $pages := lib-qs:query($resource, (), $phrase, $start, $count)//rs:pages
                    for $page in $pages/rs:page
                        let $pagelink:= encode-for-uri($page/rs:pageurl)
                        let $log:= util:log-system-err($pagelink)
                        let $pagenum:= $page/rs:pagenum
                    return

                       {$pagenum}

                )
                else ()
            }

            {
                if (($phrase != "") and ($resource != ""))
                then
                (
                let $nextlink := lib-qs:query($resource, (), $phrase, $start, $count)//rs:next
                return

                    {$nextlink/rs:nextname}

                )
                else ()
             }

:)

            (:
            {
                let $pages := if ($phrase)
                    then lib-qs:query($resource, (), $phrase, $start, $count)//rs:pages
                else ()
                for $page in $pages/rs:page
                    let $pagelink:= $page/rs:pageurl
                    let $pagenum:= $page/rs:pagenum
                return

                    {$pagenum}

            }
              {
                    let $nextlink := if ($phrase)
                        then lib-qs:query($resource, (), $phrase, $start, $count)//rs:next
                        else ()
                    return
                        {$nextlink/rs:nextname}
             }
            :)


main careServicesRequst page show a list of the registered functions

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

import module namespace csr_proc = "https://github.com/his-interop/openinfoman/csr_proc" at "../repo/csr_processor.xqm";
import module namespace csd_dm = "https://github.com/his-interop/openinfoman/csd_dm" at "../repo/csd_document_manager.xqm";
import module namespace csd_webconf =  "https://github.com/his-interop/openinfoman/csd_webconf" at "../repo/csd_webapp_config.xqm";

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($careServicesRequest/careServicesRequest,csd_dm:open_document($csd_webconf:db,$name))
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
(:  csr_proc:process_CSR_adhoc(fn:parse-xml($adhoc),csd_dm:open_document($csd_webconf:db,$name)) :)
let  $adhoc_doc := csr_proc:create_adhoc_doc(fn:root(fn:parse-xml($adhoc)),$content)
return  csr_proc:process_CSR($adhoc_doc,csd_dm:open_document($csd_webconf:db,$name))
(:
  return  csr_proc:process_CSR($adhoc_doc,csd_dm:open_document($csd_webconf:db,$name))      :)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr")
  %rest:GET
  %output:method("xhtml")
  function page:csr_list()
{
let $response :=

Care Services Request - Stored Queries

      {
      for $function in $csd_webconf:stored_functions
      let  $uuid := string($function/@uuid)
      return

      UUID: {$uuid}

      Method: {csd_webconf:lookup_stored_method($uuid)}

      Content: {csd_webconf:lookup_stored_content_type($uuid) }

      }

Care Services Request - Ad Hoc Option

      {
	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" ><![CDATA[

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.

 ]]> </textarea>

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

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

      }

  return page:wrapper($response)
};

declare function page:wrapper($response) {

    <link href="{$csd_webconf:baseurl}static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="{$csd_webconf:baseurl}static/bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>

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

import module namespace csr_proc = "https://github.com/his-interop/openinfoman/csr_proc" at "../repo/csr_processor.xqm";
import module namespace csd_dm = "https://github.com/his-interop/openinfoman/csd_dm" at "../repo/csd_document_manager.xqm";
import module namespace csd_webconf =  "https://github.com/his-interop/openinfoman/csd_webconf" at "../repo/csd_webapp_config.xqm";

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($careServicesRequest/careServicesRequest,csd_dm:open_document($csd_webconf:db,$name))
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
(:  csr_proc:process_CSR_adhoc(fn:parse-xml($adhoc),csd_dm:open_document($csd_webconf:db,$name)) :)
let  $adhoc_doc := csr_proc:create_adhoc_doc(fn:root(fn:parse-xml($adhoc)),$content)
return  csr_proc:process_CSR($adhoc_doc,csd_dm:open_document($csd_webconf:db,$name))
(:
  return  csr_proc:process_CSR($adhoc_doc,csd_dm:open_document($csd_webconf:db,$name))      :)
else
  (:need appropriate error handling:)
  ()

};

declare
  %rest:path("/CSD/csr")
  %rest:GET
  %output:method("xhtml")
  function page:csr_list()
{
let $response :=

Care Services Request

      {
	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" ><![CDATA[

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.

 ]]> </textarea>

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

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

      }

  return page:wrapper($response)
};

declare function page:wrapper($response) {

    <link href="{$csd_webconf:baseurl}static/bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="{$csd_webconf:baseurl}static/bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>