validations for various actions done

validations for various actions done

xquery version "1.0";

(: ~
 : Module Name:             edit context webpage and XQuery
 :
 : Module Version           2.0
 :
 : Date                     31st July 2009
 :
 : Copyright                The cagrid consortium
 :
 : Module overview          edit context information
 :
 :)

(:~
 :    @author Rakesh Dhaval
      @author Puneet Mathur
 :    @version 0.2
 :
 :    User Management Page
~ :)

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

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

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

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

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

declare function local:success-page()
{
   let $calling-page := request:get-parameter("calling-page","")
   return

        if(local:validateUser()=true()) then
        (

This section will allow you to manage the different users wih their respective roles. The following actions can be performed:

1. Add a New User

2. Edit an existing user

3. Remove a user

A user can exist in one of the following three different roles :

1. dba

2. user

3. guest

                Action
                dba
                user
                guest

                New User
                Yes
                No
                No

                Edit User
                Yes
                No
                No

                Remove User
                Yes
                No
                No

Note: "Admin" is the superuser with dba role and has got all the privileges. Any other user with
         dba role cannot Edit or Remove Admin user.

         {local:process()}

        )
        else(

            Error : Access Denied !! Only users of "dba" group have access

            Return to maintenance menu

        )

};

declare function local:create-user() as element()*
{

    let $name := request:get-parameter("name", ()),
    $grp := request:get-parameter("groups", ()),
    $groups := if ($grp) then
        (
            if(contains($grp, ",")) then
            (
                tokenize($grp, "\s*,\s*")
            )
            else
            (
                $grp
            )
        )else(),
    $pass1 := request:get-parameter("pass1", ""),
    $pass2 := request:get-parameter("pass2", "")
    return

    if($name eq "") then
    (

	Error : UserName is missing !!!!

 {local:correct-user(-1, $name, $grp)}

    )
   (:
   else if($name != "") then
   (
                for $user in doc("/db/system/users.xml")//users/user
                    let $stored_username := xs:string($user/@name)
 	 return(
 	 	if($name eq $stored_username) then
 	 	(

			Error : UserName Already Exists !! Chooose a different Username!!!!

 {local:correct-user(-1, $name, $grp)}

		)
		else()
	   )

   ) :)

    else if($grp eq "") then
    (

	Error : GroupName is missing !! Please specify atleast one group!!!!!

 {local:correct-user(-1, $name, $grp)}

    )

    else if($pass1 != $pass2 or $pass1 eq "") then
        (

	Error : Either Password is missing or Passwords are not identical !!!!

 {local:correct-user(-1, $name, $grp)}

        )
        else(

            xmldb:create-user($name, $pass1, $groups, ""),

            Success: User "{$name}" Created !!!

{local:display()}

          )
};

declare function local:display()
{

      <form>

                Name
                Groups

            {
                for $user in doc("/db/system/users.xml")//users/user
                    let $name := xs:string($user/@name),
                    $groups := string-join($user/group, ", ")
                order by $name return

                        <input type="radio" name="uid" value="{$user/@uid}"/>
                        {$name}
                        {$groups}

            }

                    <input type="submit" name="action" value="Edit"/>
                    <input type="submit" name="action" value="New User"/>
                    <input type="submit" name="action" value="Remove"/>

Return to maintenance menu
    </form>

} ;

declare function local:correct-user($uid as xs:integer, $name as xs:string, $groups as xs:string)  as element()
{

    <form action="{session:encode-url(request:get-uri())}" method="get">
        {local:edit-user($uid, $name, $groups)}
        <input type="hidden" name="panel" value="users"/>
    </form>

};

declare function local:edit-user($uid as xs:integer, $name as xs:string, $groups as xs:string) as element()
{

            User:
            {
                if($name eq "") then
                (
                    <input type="text" name="name"/>
                )
                else
                (
                    <input type="hidden" name="name" value="{$name}"/>{$name}
                )
            }

            Groups:
            <input type="text" name="groups" value="{$groups}"/>
            A comma-separated list of groups.
            Note: non-existing groups will be created automatically.

            Password:
            <input type="password" name="pass1"/>

            Repeat:
            <input type="password" name="pass2"/>

         {
            if($uid ge 0) then
            (
                <input type="checkbox" name="nopass"/> Leave password unchanged.
            )else()
        }

        {
            if($uid lt 0) then
            (

                <input type="submit" name="action" value="Create"/>
	            <input type="submit" name="action" value="Cancel"/>
            )
            else
            (

                <input type="submit" name="action" value="Change"/>
	 <input type="submit" name="action" value="Cancel"/>
            )

        }

        <input type="hidden" name="uid" value="{$uid}"/>

 };

declare function local:process()  as element()*
{
    let $action := request:get-parameter("action", "") ,
    $session_user  := session:get-attribute("username"),
    $current_user := xmldb:get-current-user()
    return
        if($action eq "Create") then
        (
            local:create-user()
        )
        else if($action eq "New User") then
        (
            local:correct-user(-1, "", "")
        )
       else if($action eq "Change") then
        (
            local:update-user()
        )
        else if($action eq "Edit") then
        (
            let $uid := request:get-parameter("uid", ()) return
            if(empty($uid) or xs:integer($uid) le 0)then
 	        (

Error : Select a User to Update !!!!

{local:display()}

	         )
      	     else
	         (
               		let $user := doc("/db/system/users.xml")//users/user[@uid = $uid] return
        			if( ($user/@name) eq "admin" and xmldb:get-current-user() != "admin" ) then
	      	        (

Error : You do not have permission to Edit the Admin User !!!!

{local:display()}

	       	        )
       	            else(
       	             	     local:correct-user(xs:integer($uid), $user/@name, string-join($user/group, ", "))
		            )

              )

            )
        else if($action eq "Remove") then
        (
            local:remove-user()
        )
        else if($action eq "Cancel") then
        (

	       {local:display()}

        )
        else(

	       {local:display()}

        )

};

declare function local:validateUser() as xs:boolean
{
   let $hostname :=  request:get-hostname()

   let $resource_location := concat("xmldb:exist://", "localhost", ":8080/exist/xmlrpc/db")
   let $user := session:get-attribute("username")
   let $password := session:get-attribute("password")
   let $is-ssl :=  lib-util:checkSSL()
   return
           if(xmldb:is-admin-user($user)) then
           (
            	if (xmldb:login($resource_location, $user, $password))
              then (
		true()
	)
	else(
		false()
	)
          )
          else(
	          false()
          )

};

declare function local:update-user() as element()*
{

    let $name := request:get-parameter("name", ()),
    $grp := request:get-parameter("groups", ()),
    $groups := if ($grp) then
        (
            if(contains($grp, ",")) then
            (
                tokenize($grp, "\s*,\s*")
            )
            else
            (
                $grp
            )
        )else(),
    $pass1 := request:get-parameter("pass1", ""),
    $pass2 := request:get-parameter("pass2", ""),
    $nopass := request:get-parameter("nopass", ()),
    $pass := if($nopass) then () else $pass1,
    $uid := request:get-parameter("uid", "") return

        if(not($nopass) and $pass1 ne $pass2)then
        (

Passwords are not identical.
,
            local:correct-user($uid, $name, $grp)
        )
        else if(empty($groups)) then
        (

Please specify one group at least.
,
            local:correct-user($uid, $name, $grp)
        )
        else
        (
            xmldb:change-user($name, $pass, $groups, ""),

            if(xmldb:get-current-user() eq $name) then
            (
                session:set-attribute("password", $pass)
            )else(),

            Success : User "{$name}" Updated !!!

{local:display()}

        )

};

declare function local:remove-user()
{
    if(empty(request:get-parameter("uid", ())) or xs:integer(request:get-parameter("uid", ())) le 0 )then
    (

            Error : Select a User to Remove !!!!

{local:display()}

    )
   else
   (
    let $uid := request:get-parameter("uid", ()),
    $name := doc("/db/system/users.xml")//user[@uid = $uid]/@name cast as xs:string return

        if($name eq xmldb:get-current-user() or $name eq "admin") then
        (

            Error : You cannot remove the Admin User or Current User!!!!

{local:display()}

        )
        else if (xmldb:is-admin-user($name) and xmldb:get-current-user() != "admin") then
        (

            Error : You do not have the permission to remove the user of "dba" group!!!!

{local:display()}

      )
      else
      (

           { xmldb:delete-user($name) }
           Success : User "{$name}" Removed !!!

{local:display()}

        )
     )
};

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

   session:create(),
   let $id := request:get-parameter('id','')
   let $title as xs:string := concat(" User Management", $id)

   return
      lib-rendering:txfrm-webpage(
      $title,
            local:success-page()
         )

xquery version "1.0";

(: ~
 : Module Name:             edit context webpage and XQuery
 :
 : Module Version           2.0
 :
 : Date                     31st July 2009
 :
 : Copyright                The cagrid consortium
 :
 : Module overview          edit context information
 :
 :)

(:~
 :    @author Rakesh Dhaval
      @author Puneet Mathur
 :    @version 0.2
 :
 :    User Management Page
~ :)

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

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

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

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

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

declare function local:success-page()
{
   let $calling-page := request:get-parameter("calling-page","")
   return

        if(local:validateUser()=true()) then
        (
        	local:process()
        )
        else(

            Access Denied !! Only users of "dba" group have access

            Return to maintenance menu

        )

};

declare function local:new-user() as element()*
{

    let $name := request:get-parameter("name", ()),
    $grp := request:get-parameter("groups", ()),
    $groups := if ($grp) then
        (
            if(contains($grp, ",")) then
            (
                tokenize($grp, "\s*,\s*")
            )
            else
            (
                $grp
            )
        )else(),
    $pass1 := request:get-parameter("pass1", ""),
    $pass2 := request:get-parameter("pass2", "")
    return

    if($name eq "") then
    (

	Error : UserName is missing !!!!

 {local:correct-user(-1, $name, $grp)}

    )
   (:
   else if($name != "") then
   (
                for $user in doc("/db/system/users.xml")//users/user
                    let $stored_username := xs:string($user/@name)
 	 return(
 	 	if($name eq $stored_username) then
 	 	(

			Error : UserName Already Exists !! Chooose a different Username!!!!

 {local:correct-user(-1, $name, $grp)}

		)
		else()
	   )

   ) :)

    else if($grp eq "") then
    (

	Error : GroupName is missing !! Please specify atleast one group!!!!!

 {local:correct-user(-1, $name, $grp)}

    )

    else if($pass1 != $pass2 or $pass1 eq "") then
        (

	Error : Either Password is missing or Passwords are not identical !!!!

 {local:correct-user(-1, $name, $grp)}

        )
        else(

            xmldb:create-user($name, $pass1, $groups, ""),

            User "{$name}" Created !!!

{local:display()}

          )
};

 declare function local:do-display() as node()?
{
    let $uid := request:get-parameter("uid", ())
    return
        if (empty($uid)) then
            local:display()
        else ()
};

declare function local:display() as node()?
{

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

                Name
                Groups

            {
                for $user in doc("/db/system/users.xml")//users/user
                    let $name := xs:string($user/@name),
                    $groups := string-join($user/group, ", ")
                order by $name return

                        <input type="radio" name="uid" value="{$user/@uid}"/>
                        {$name}
                        {$groups}

            }

                    <input type="submit" name="action" value="Edit"/>
                    <input type="submit" name="action" value="New User"/>
                    <input type="submit" name="action" value="Remove"/>

        {
                let $action := request:get-parameter("action", ""),
                $uid := request:get-parameter("uid", ()) return
                if($action eq "Edit") then
                    (
                            if(empty($uid) or xs:integer($uid) le 0)then
 	             (

Error : Select a User to Update !!!!

	            )
      	          else
	            (
                         		let $user := doc("/db/system/users.xml")//users/user[@uid = $uid] return
        			if( ($user/@name) eq "admin" and xmldb:get-current-user() != "admin" ) then
	      	              (

 Error : You do not have permission to Edit the Admin User !!!!

	       	             )
       	             	          else(
                         		local:edit-user(xs:integer($uid), $user/@name, string-join($user/group, ", "))
                         	          )
                           )
                    )
                    else if($action eq "New User") then
                    (
                        local:edit-user(-1, "", "")
                    )else()

        }

Return to maintenance menu
     </form>

} ;

declare function local:correct-user($uid as xs:integer, $name as xs:string, $groups as xs:string)  as element()
{

    <form action="{session:encode-url(request:get-uri())}" method="get">
        {local:edit-user($uid, $name, $groups)}
        <input type="hidden" name="panel" value="users"/>
    </form>

};

declare function local:edit-user($uid as xs:integer, $name as xs:string, $groups as xs:string) as element()
{

            User:
            {
                if($name eq "") then
                (
                    <input type="text" name="name"/>
                )
                else
                (
                    <input type="hidden" name="name" value="{$name}"/>{$name}
                )
            }

            Groups:
            <input type="text" name="groups" value="{$groups}"/>
            A comma-separated list of groups.
            Note: non-existing groups will be created automatically.

            Password:
            <input type="password" name="pass1"/>

            Repeat:
            <input type="password" name="pass2"/>

         {
            if($uid ge 0) then
            (
                <input type="checkbox" name="nopass"/> Leave password unchanged.
            )else()
        }

        {
            if($uid lt 0) then
            (

                <input type="submit" name="action" value="Create"/>
	<input type="submit" name="action" value="Cancel"/>
            )
            else
            (

                <input type="submit" name="action" value="Change"/>
	 <input type="submit" name="action" value="Cancel"/>
            )

        }

        <input type="hidden" name="uid" value="{$uid}"/>

 };

declare function local:process()  as element()*
{
    let $action := request:get-parameter("action", "") ,
    $session_user  := session:get-attribute("username"),
    $current_user := xmldb:get-current-user()
    return
        if($action eq "Create") then
        (
            local:new-user()
        )
       else if($action eq "Change") then
        (
            local:update-user()
        )

         else if($action eq "Remove") then
        (
            local:remove-user()
        )
        else if($action eq "Cancel") then
        (

	       {local:display()}

        )
        else(

	       {local:display()}

        )

};

declare function local:validateUser() as xs:boolean
{
   let $hostname :=  request:get-hostname()

   let $resource_location := concat("xmldb:exist://", "localhost", ":8080/exist/xmlrpc/db")
   let $user := session:get-attribute("username")
   let $password := session:get-attribute("password")
   let $is-ssl :=  lib-util:checkSSL()
   return
           if(xmldb:is-admin-user($user)) then
           (
            	if (xmldb:login($resource_location, $user, $password))
              then (
		true()
	)
	else(
		false()
	)
          )
          else(
	          false()
          )

};

declare function local:update-user() as element()*
{

    let $name := request:get-parameter("name", ()),
    $grp := request:get-parameter("groups", ()),
    $groups := if ($grp) then
        (
            if(contains($grp, ",")) then
            (
                tokenize($grp, "\s*,\s*")
            )
            else
            (
                $grp
            )
        )else(),
    $pass1 := request:get-parameter("pass1", ""),
    $pass2 := request:get-parameter("pass2", ""),
    $nopass := request:get-parameter("nopass", ()),
    $pass := if($nopass) then () else $pass1,
    $uid := request:get-parameter("uid", "") return

        if(not($nopass) and $pass1 ne $pass2)then
        (

Passwords are not identical.
,
            local:correct-user($uid, $name, $grp)
        )
        else if(empty($groups)) then
        (

Please specify one group at least.
,
            local:correct-user($uid, $name, $grp)
        )
        else
        (
            xmldb:change-user($name, $pass, $groups, ""),

            if(xmldb:get-current-user() eq $name) then
            (
                session:set-attribute("password", $pass)
            )else(),

            User "{$name}" Updated !!!

{local:display()}

        )

};

declare function local:remove-user()
{
    if(empty(request:get-parameter("uid", ())) or xs:integer(request:get-parameter("uid", ())) le 0 )then
    (

            Error : Select a User to Remove !!!!

Return to User Management

    )
   else
   (
    let $uid := request:get-parameter("uid", ()),
    $name := doc("/db/system/users.xml")//user[@uid = $uid]/@name cast as xs:string return

        if($name eq xmldb:get-current-user() or $name eq "admin") then
        (

            You cannot remove the Admin User or Current User!!!!

Return to User Management

        )
        else if (xmldb:is-admin-user($name) and xmldb:get-current-user() != "admin") then
        (

            You do not have the permission to remove the user of "dba" group!!!!

Return to User Management

      )
      else
      (

            User "{$name}" Removed !!!

{local:display()}

        )
     )
};

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

   session:create(),
   let $id := request:get-parameter('id','')
   let $title as xs:string := concat(" User Management", $id)

   return
      lib-rendering:txfrm-webpage(
      $title,
            local:success-page()
         )


added missing author name

added missing author name

xquery version "3.0";

(:
 : Copyright 2006-2013 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 a function to put the currently running query
 : to sleep.
 :
 : @author Matthias Brantner
 :)
module namespace sleep = "http://zorba.io/modules/sleep";

declare namespace an = "http://zorba.io/annotations";

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

(:~
 : Puts the currently running query to sleep.
 : This function is mainly useful in development e.g. to simulate the
 : effects of long-running tasks wrt. the concurrent execution of
 : requests.
 :
 : @param $millis the number of milliseconds to sleep
 : @return the function is sequential and returns the empty sequence
 :)
declare %an:sequential function sleep:millis($millis as xs:integer)
  as empty-sequence() external;

xquery version "3.0";

(:
 : Copyright 2006-2013 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 a function to put the currently running query
 : to sleep.
 :
 :)
module namespace sleep = "http://zorba.io/modules/sleep";

declare namespace an = "http://zorba.io/annotations";

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

(:~
 : Puts the currently running query to sleep.
 : This function is mainly useful in development e.g. to simulate the
 : effects of long-running tasks wrt. the concurrent execution of
 : requests.
 :
 : @param $millis the number of milliseconds to sleep
 : @return the function is sequential and returns the empty sequence
 :)
declare %an:sequential function sleep:millis($millis as xs:integer)
  as empty-sequence() external;


do stable sort

do stable sort

declare variable $input-context external;
let $auction := doc($input-context) return
for $b in $auction/site/regions//item
let $k := $b/name/text()
stable order by zero-or-one($b/location) ascending empty greatest
return <item name="{$k}">{$b/location/text()}</item>

declare variable $input-context external;
let $auction := doc($input-context) return
for $b in $auction/site/regions//item
let $k := $b/name/text()
order by zero-or-one($b/location) ascending empty greatest
return <item name="{$k}">{$b/location/text()}</item>


fixed issue with displaying list of registered careServiceFunctions

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: {string($uuid)}

      Method: {string(csd_webconf:lookup_stored_method($uuid))}

      Content: {string(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 - 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"/>