Replaced deprecated function

Replaced deprecated function

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

xquery version "1.0";
(: $Id$ :)
(:
    Module: display and browse collections.
:)

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

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace v="http://exist-db.org/versioning";

import module namespace date="http://exist-db.org/xquery/admin-interface/date" at "dates.xqm";

(:
    Main function: outputs the page.
:)
declare function browse:main() as element()
{
    let $colName := request:get-parameter("collection", "/db") return

            { browse:process-action($colName) }

Browsing Collection: {xdb:decode-uri(xs:anyURI($colName))}

            <form method="POST" enctype="multipart/form-data">
                {
                    browse:display-collection($colName)
                }

<input type="submit" name="action" value="Remove Selected"/>

                        <input type="submit" name="action" value="Create Collection"/>
                        New collection:

                        <input type="text" name="create" size="40"/>

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

                        <input type="text" name="name" size="20"/>

                <input type="hidden" name="collection" value="{$colName}"/>
                <input type="hidden" name="panel" value="browse"/>
            </form>

};

(:
    Process an action.
:)
declare function browse:process-action($colName as xs:string) as element()*
{
    let $action := request:get-parameter("action", ()) return
        util:catch("java.lang.Exception",
            if($action eq "Remove Selected") then
            (
                browse:remove()
            )
            else if($action eq "Create Collection") then
            (
                browse:create-collection($colName)
            )
            else if($action eq "Store") then
            (
                browse:store($colName)
            )
            else if($action eq "Upload") then
            (
                browse:upload($colName)
            )else(),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

(:
    Store uploaded content.
:)
declare function browse:upload($colName as xs:string) as element()
{
    let $name := request:get-parameter("name", ()),
    $docName := if($name) then $name else request:get-uploaded-file-name("upload"),
    $file := request:get-uploaded-file-data("upload") return

Actions:

Storing uploaded content to: {$docName}

                {
                    xdb:decode-uri(xs:anyURI(xdb:store($colName, xdb:encode-uri($docName), $file)))
                }

};

(:
    Store files from an URI.

    Allowing this opens a security whole as a user can
    upload arbitrary files on the server if the process is running
    as root.
:)
declare function browse:store($colName as xs:string) as element()
{
    let $uri := request:get-parameter("uri", ()),
    $path := if(starts-with($uri, "file:")) then $uri else concat("file:", $uri),
    $docName := request:get-parameter("name", ()) return

Actions:

Storing resources from URI: {$path}

                {
                    xdb:store($colName, $docName, xs:anyURI($path))
                }

};

(:
    Remove a set of resources.
:)
declare function browse:remove() as element()
{
    let $resources := request:get-parameter("resource", ()) return

Actions:

                {
                    for $resource in $resources
                    return
                        browse:remove-resource($resource)
                }

};

(:
    Remove a resource.
:)
declare function browse:remove-resource($resource as xs:string) as element()*
{
    let $isBinary := util:binary-doc-available($resource),
    $doc := if ($isBinary) then $resource else doc($resource) return

        if($doc)then
        (

Removing document: {xdb:decode-uri(xs:anyURI($resource))} ...
,
            xdb:remove(util:collection-name($doc), util:document-name($doc))
        )
        else
        (

Removing collection: {xdb:decode-uri(xs:anyURI($resource))} ...
,
            xdb:remove($resource)
        )
};

(:
    Create a collection.
:)
declare function browse:create-collection($parentColName as xs:string) as element()
{
    let $newcol := request:get-parameter("create", ()) return

Actions:

            {
                if($newcol) then
                (
                    let $col := xdb:create-collection($parentColName, xdb:encode-uri($newcol)) return

Created collection: {xdb:decode-uri(xs:anyURI(util:collection-name($col)))}.

                )
                else
                (

No name specified for new collection!

                )
            }

};

(:
    Display the contents of a collection in a table view.
:)
declare function browse:display-collection($colName as xs:string) as element()
{

            Name
            Permissions
            Owner
            Group
            Created
            Modified
            Size (KB)
			Revision

            Up

        {
            browse:display-child-collections($colName),
            browse:display-child-resources($colName)
        }

};

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

            <input type="checkbox" name="resource" value="{$path}"/>
            {xdb:decode-uri(xs:anyURI($child))}
            {xdb:permissions-to-string(xdb:get-permissions($path))}
            {xdb:get-owner($path)}
            {xdb:get-group($path)}
            {date:format-dateTime($created)}

};

declare function browse:display-child-resources($colName as xs:string) as element()*
{
    for $child in xdb:get-child-resources($colName)
    let $restUri := concat(request:get-context-path(), '/rest')
    order by $child
	return

            <input type="checkbox" name="resource" value="{$colName}/{$child}"/>
            {xdb:decode-uri(xs:anyURI($child))}
            {xdb:permissions-to-string(xdb:get-permissions($colName, $child))}
            {xdb:get-owner($colName, $child)}
            {xdb:get-group($colName, $child)}
            {date:format-dateTime(xdb:created($colName, $child))}
            {date:format-dateTime(xdb:last-modified($colName, $child))}
            {fn:ceiling(xdb:size($colName, $child) div 1024)}

				{browse:last-revision($colName, $child)//v:properties/v:revision/string()}

};

declare function browse:last-revision($collection as xs:string, $resource as xs:string) {
	let $vCollection := concat("/db/system/versions", $collection)
	let $versions :=
		for $version in collection($vCollection)/v:version[
			v:properties[v:document = $resource]
		]
		order by xs:long($version/v:properties/v:revision) descending
		return $version
	return
		$versions[1]
};

(:
    Get the name of the parent collection from a specified collection path.
:)
declare function browse:get-parent-collection($path as xs:string) as xs:string
{
    if($path eq "/db") then
        $path
    else
        replace($path, "/[^/]*$", "")
};

xquery version "1.0";
(: $Id$ :)
(:
    Module: display and browse collections.
:)

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

declare namespace request="http://exist-db.org/xquery/request";
declare namespace xdb="http://exist-db.org/xquery/xmldb";
declare namespace util="http://exist-db.org/xquery/util";
declare namespace v="http://exist-db.org/versioning";

import module namespace date="http://exist-db.org/xquery/admin-interface/date" at "dates.xqm";

(:
    Main function: outputs the page.
:)
declare function browse:main() as element()
{
    let $colName := request:get-parameter("collection", "/db") return

            { browse:process-action($colName) }

Browsing Collection: {xdb:decode-uri(xs:anyURI($colName))}

            <form method="POST" enctype="multipart/form-data">
                {
                    browse:display-collection($colName)
                }

<input type="submit" name="action" value="Remove Selected"/>

                        <input type="submit" name="action" value="Create Collection"/>
                        New collection:

                        <input type="text" name="create" size="40"/>

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

                        <input type="text" name="name" size="20"/>

                <input type="hidden" name="collection" value="{$colName}"/>
                <input type="hidden" name="panel" value="browse"/>
            </form>

};

(:
    Process an action.
:)
declare function browse:process-action($colName as xs:string) as element()*
{
    let $action := request:get-parameter("action", ()) return
        util:catch("java.lang.Exception",
            if($action eq "Remove Selected") then
            (
                browse:remove()
            )
            else if($action eq "Create Collection") then
            (
                browse:create-collection($colName)
            )
            else if($action eq "Store") then
            (
                browse:store($colName)
            )
            else if($action eq "Upload") then
            (
                browse:upload($colName)
            )else(),

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

(:
    Store uploaded content.
:)
declare function browse:upload($colName as xs:string) as element()
{
    let $name := request:get-parameter("name", ()),
    $docName := if($name) then $name else request:get-uploaded-file-name("upload"),
    $file := request:get-uploaded-file("upload") return

Actions:

Storing uploaded content to: {$docName}

                {
                    xdb:decode-uri(xs:anyURI(xdb:store($colName, xdb:encode-uri($docName), $file)))
                }

};

(:
    Store files from an URI.

    Allowing this opens a security whole as a user can
    upload arbitrary files on the server if the process is running
    as root.
:)
declare function browse:store($colName as xs:string) as element()
{
    let $uri := request:get-parameter("uri", ()),
    $path := if(starts-with($uri, "file:")) then $uri else concat("file:", $uri),
    $docName := request:get-parameter("name", ()) return

Actions:

Storing resources from URI: {$path}

                {
                    xdb:store($colName, $docName, xs:anyURI($path))
                }

};

(:
    Remove a set of resources.
:)
declare function browse:remove() as element()
{
    let $resources := request:get-parameter("resource", ()) return

Actions:

                {
                    for $resource in $resources
                    return
                        browse:remove-resource($resource)
                }

};

(:
    Remove a resource.
:)
declare function browse:remove-resource($resource as xs:string) as element()*
{
    let $isBinary := util:binary-doc-available($resource),
    $doc := if ($isBinary) then $resource else doc($resource) return

        if($doc)then
        (

Removing document: {xdb:decode-uri(xs:anyURI($resource))} ...
,
            xdb:remove(util:collection-name($doc), util:document-name($doc))
        )
        else
        (

Removing collection: {xdb:decode-uri(xs:anyURI($resource))} ...
,
            xdb:remove($resource)
        )
};

(:
    Create a collection.
:)
declare function browse:create-collection($parentColName as xs:string) as element()
{
    let $newcol := request:get-parameter("create", ()) return

Actions:

            {
                if($newcol) then
                (
                    let $col := xdb:create-collection($parentColName, xdb:encode-uri($newcol)) return

Created collection: {xdb:decode-uri(xs:anyURI(util:collection-name($col)))}.

                )
                else
                (

No name specified for new collection!

                )
            }

};

(:
    Display the contents of a collection in a table view.
:)
declare function browse:display-collection($colName as xs:string) as element()
{

            Name
            Permissions
            Owner
            Group
            Created
            Modified
            Size (KB)
			Revision

            Up

        {
            browse:display-child-collections($colName),
            browse:display-child-resources($colName)
        }

};

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

            <input type="checkbox" name="resource" value="{$path}"/>
            {xdb:decode-uri(xs:anyURI($child))}
            {xdb:permissions-to-string(xdb:get-permissions($path))}
            {xdb:get-owner($path)}
            {xdb:get-group($path)}
            {date:format-dateTime($created)}

};

declare function browse:display-child-resources($colName as xs:string) as element()*
{
    for $child in xdb:get-child-resources($colName)
    let $restUri := concat(request:get-context-path(), '/rest')
    order by $child
	return

            <input type="checkbox" name="resource" value="{$colName}/{$child}"/>
            {xdb:decode-uri(xs:anyURI($child))}
            {xdb:permissions-to-string(xdb:get-permissions($colName, $child))}
            {xdb:get-owner($colName, $child)}
            {xdb:get-group($colName, $child)}
            {date:format-dateTime(xdb:created($colName, $child))}
            {date:format-dateTime(xdb:last-modified($colName, $child))}
            {fn:ceiling(xdb:size($colName, $child) div 1024)}

				{browse:last-revision($colName, $child)//v:properties/v:revision/string()}

};

declare function browse:last-revision($collection as xs:string, $resource as xs:string) {
	let $vCollection := concat("/db/system/versions", $collection)
	let $versions :=
		for $version in collection($vCollection)/v:version[
			v:properties[v:document = $resource]
		]
		order by xs:long($version/v:properties/v:revision) descending
		return $version
	return
		$versions[1]
};

(:
    Get the name of the parent collection from a specified collection path.
:)
declare function browse:get-parent-collection($path as xs:string) as xs:string
{
    if($path eq "/db") then
        $path
    else
        replace($path, "/[^/]*$", "")
};


[MIN] DBA, Query panel, base uri

[MIN] DBA, Query panel, base uri

(:~
 : Utility functions.
 :
 : @author Christian Grün, BaseX Team, 2014-17
 :)
module namespace util = 'dba/util';

import module namespace cons = 'dba/cons' at 'cons.xqm';

(:~
 : Evaluates a query and returns the result.
 : @param  $query    query string
 : @param  $context  initial context value
 : @return serialized result of query
 :)
declare function util:query(
  $query    as xs:string?,
  $context  as item()*
) as xs:string {
  let $limit := $cons:OPTIONS($cons:K-MAXCHARS)
  let $result := xquery:eval($query, map { '': $context }, util:query-options())
  (: serialize more characters than requested, because limit represents number of bytes :)
  return util:chop(serialize($result, map { 'limit': $limit * 2 + 1, 'method': 'basex' }), $limit)
};

(:~
 : Runs an updating query.
 : @param  $query  query string
 : @return empty sequence
 :)
declare %updating function util:update-query(
  $query  as xs:string?
) {
  xquery:update($query, map { }, util:query-options())
};

(:~
 : Returns the options for evaluating a query.
 : @return options
 :)
declare %private function util:query-options() as map(*) {
  map {
    'timeout'   : $cons:OPTIONS($cons:K-TIMEOUT),
    'memory'    : $cons:OPTIONS($cons:K-MEMORY),
    'permission': $cons:OPTIONS($cons:K-PERMISSION),
    'base-uri'  : $cons:OPTIONS($cons:K-DIRECTORY)
  }
};

(:~
 : Returns the index of the first result to generate.
 : @param  $page  current page
 : @param  $sort  sort key
 : @return last result
 :)
declare function util:start(
  $page  as xs:integer,
  $sort  as xs:string
) as xs:integer {
  if($page and not($sort)) then (
    ($page - 1) * $cons:OPTIONS($cons:K-MAXROWS) + 1
  ) else (
    1
  )
};

(:~
 : Returns the index of the last result to generate.
 : @param  $page  current page
 : @param  $sort  sort key
 : @return last result
 :)
declare function util:end(
  $page  as xs:integer,
  $sort  as xs:string
) as xs:integer {
  if($page and not($sort)) then (
    $page * $cons:OPTIONS($cons:K-MAXROWS)
  ) else (
    999999999
  )
};

(:~
 : Chops a string result to the maximum number of allowed characters.
 : @param  $string  string
 : @param  $max     maximum number of characters
 : @return string
 :)
declare function util:chop(
  $string  as xs:string,
  $max     as xs:integer
) {
  if(string-length($string) > $max) then (
    substring($string, 1, $max) || '...'
  ) else (
    $string
  )
};

(:~
 : Joins sequence entries.
 : @param  $items  items
 : @param  $sep    separator
 : @return result
 :)
declare function util:item-join(
  $items  as item()*,
  $sep    as item()
) {
  for $item at $pos in $items
  return ($sep[$pos > 1], $item)
};

(:~
 : Returns a count info for the specified items.
 : @param  $items   items
 : @param  $name    name of item (singular form)
 : @param  $action  action label (past tense)
 : @return result
 :)
declare function util:info(
  $items   as item()*,
  $name    as xs:string,
  $action  as xs:string
) as xs:string {
  let $count := count($items)
  return $count || ' ' || $name || (if($count > 1) then 's were ' else ' was ') || $action || '.'
};

(:~
 : Capitalizes a string.
 : @param  $string  string
 : @return capitalized string
 :)
declare function util:capitalize(
  $string  as xs:string
) as xs:string {
  upper-case(substring($string, 1, 1)) || substring($string, 2)
};

(:~
 : Utility functions.
 :
 : @author Christian Grün, BaseX Team, 2014-17
 :)
module namespace util = 'dba/util';

import module namespace cons = 'dba/cons' at 'cons.xqm';

(:~
 : Evaluates a query and returns the result.
 : @param  $query    query string
 : @param  $context  initial context value
 : @return serialized result of query
 :)
declare function util:query(
  $query    as xs:string?,
  $context  as item()*
) as xs:string {
  let $limit := $cons:OPTIONS($cons:K-MAXCHARS)
  let $result := xquery:eval($query, map { '': $context }, util:query-options())
  (: serialize more characters than requested, because limit represents number of bytes :)
  return util:chop(serialize($result, map { 'limit': $limit * 2 + 1, 'method': 'basex' }), $limit)
};

(:~
 : Runs an updating query.
 : @param  $query  query string
 : @return empty sequence
 :)
declare %updating function util:update-query(
  $query  as xs:string?
) {
  xquery:update($query, map { }, util:query-options())
};

(:~
 : Returns the options for evaluating a query.
 : @return options
 :)
declare %private function util:query-options() as map(*) {
  map {
    'timeout'   : $cons:OPTIONS($cons:K-TIMEOUT),
    'memory'    : $cons:OPTIONS($cons:K-MEMORY),
    'permission': $cons:OPTIONS($cons:K-PERMISSION)
  }
};

(:~
 : Returns the index of the first result to generate.
 : @param  $page  current page
 : @param  $sort  sort key
 : @return last result
 :)
declare function util:start(
  $page  as xs:integer,
  $sort  as xs:string
) as xs:integer {
  if($page and not($sort)) then (
    ($page - 1) * $cons:OPTIONS($cons:K-MAXROWS) + 1
  ) else (
    1
  )
};

(:~
 : Returns the index of the last result to generate.
 : @param  $page  current page
 : @param  $sort  sort key
 : @return last result
 :)
declare function util:end(
  $page  as xs:integer,
  $sort  as xs:string
) as xs:integer {
  if($page and not($sort)) then (
    $page * $cons:OPTIONS($cons:K-MAXROWS)
  ) else (
    999999999
  )
};

(:~
 : Chops a string result to the maximum number of allowed characters.
 : @param  $string  string
 : @param  $max     maximum number of characters
 : @return string
 :)
declare function util:chop(
  $string  as xs:string,
  $max     as xs:integer
) {
  if(string-length($string) > $max) then (
    substring($string, 1, $max) || '...'
  ) else (
    $string
  )
};

(:~
 : Joins sequence entries.
 : @param  $items  items
 : @param  $sep    separator
 : @return result
 :)
declare function util:item-join(
  $items  as item()*,
  $sep    as item()
) {
  for $item at $pos in $items
  return ($sep[$pos > 1], $item)
};

(:~
 : Returns a count info for the specified items.
 : @param  $items   items
 : @param  $name    name of item (singular form)
 : @param  $action  action label (past tense)
 : @return result
 :)
declare function util:info(
  $items   as item()*,
  $name    as xs:string,
  $action  as xs:string
) as xs:string {
  let $count := count($items)
  return $count || ' ' || $name || (if($count > 1) then 's were ' else ' was ') || $action || '.'
};

(:~
 : Capitalizes a string.
 : @param  $string  string
 : @return capitalized string
 :)
declare function util:capitalize(
  $string  as xs:string
) as xs:string {
  upper-case(substring($string, 1, 1)) || substring($string, 2)
};


[tweak]  need to init /db/system/repo for repo admin to work!

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

xquery version "1.0";

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

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

declare function repomanager:upload() as element()
{
    let $name := request:get-parameter("name", ()),
    $repocol :=  if (collection('/db/system/repo')) then () else xmldb:create-collection('/db/system','repo'),
    $docName := if($name) then $name else request:get-uploaded-file-name("upload"),
    $file := request:get-uploaded-file-data("upload") return

Actions:

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

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

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

                }

};

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

Actions:

activated package: {$name}

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

};

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

Actions:

deactivated package: {$name}

                {
                    repo:remove($name)
                }

};

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

Actions:

removed package: {$name}

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

};

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

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

declare function repomanager:main() as element() {
    let $action := lower-case(request:get-parameter("action", "refresh"))
    let $repocol :=  if (collection('/db/system/repo')) then () else xmldb:create-collection('/db/system','repo')

    return

Package Repository

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

         { repomanager:process-action() }

                Package
                Date installed
                Installed
                Action

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

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

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

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

                {
                if($installed) then
                  deactivate

                 else
                 ( activate,' | ',
                 remove
                 )
                }

            }

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

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

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

          </form>

};

xquery version "1.0";

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

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

declare function repomanager:upload() as element()
{
    let $name := request:get-parameter("name", ()),
    $repocol :=  if (collection('/db/system/repo')) then () else xmldb:create-collection('/db/system','repo'),
    $docName := if($name) then $name else request:get-uploaded-file-name("upload"),
    $file := request:get-uploaded-file-data("upload") return

Actions:

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

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

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

                }

};

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

Actions:

activated package: {$name}

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

};

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

Actions:

deactivated package: {$name}

                {
                    repo:remove($name)
                }

};

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

Actions:

removed package: {$name}

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

};

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

                An error occurred while processing the action:

                {$util:exception-message}

        )
};

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

    return

Package Repository

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

         { repomanager:process-action() }

                Package
                Date installed
                Installed
                Action

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

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

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

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

                {
                if($installed) then
                  deactivate

                 else
                 ( activate,' | ',
                 remove
                 )
                }

            }

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

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

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

          </form>

};


update

update

xquery version "3.0";
declare namespace tei="http://www.tei-c.org/ns/1.0";(:
declare option exist:serialize "method=html5 media-type=text/html omit-xml-declaration=yes indent=yes";:)
let $fenomenos := doc('/db/exemplos/feature_library.xml')//tei:fs
let $cantigas := doc('/db/exemplos/A1-A4_draft.xml')//tei:div[@type='poem']
let $ling := $cantigas//tei:rdg[tokenize(replace(@ana, '#', ''), ' ') = $fenomenos[@feats[contains(., '#ling')]]/@xml:id]
let $graph := $cantigas//tei:rdg[tokenize(replace(@ana, '#', ''), ' ') = $fenomenos[@feats[contains(., '#graph')]]/@xml:id]
let $error := $cantigas//tei:rdg[tokenize(replace(@ana, '#', ''), ' ') = $fenomenos[@feats[contains(., '#Error')]]/@xml:id]
let $poets := doc('/db/exemplos/corpus_autores.xml')//tei:person

(: Problemas que resolver:
    1. Formatar <ex>
        :)

return

       <title>Estudos lingüísticos</title>

Variaçom lingüística

                    Fenómeno
                    Variante
                    Testemunho
                    Copista
                    Autor
                    Período
                    Cantiga
                    Linha

            {for $fen in $ling
            let $author := $poets[@xml:id = $fen/ancestor::*[name()='div'[1]]//tei:name/substring(@ref,2)]
            return
            for $ana in $fen/tokenize(replace(@ana, '#', ''), ' ')[. = $fenomenos[@feats[contains(., '#ling')]]/@xml:id]
            return

                    {$fenomenos[@xml:id = $ana]/@n/string()}
                    {(if ($fen//tei:choice) then $fen//tei:reg else
                    (if (string-length($fen) = 0) then 'omissão'
                    else $fen/string()))||' (vs. '||
                    (if ($fen/../*[not(@wit = $fen/@wit)]/tei:choice) then $fen/../*[not(@wit = $fen/@wit)]//tei:reg/string()
                    else
                    if (string-length($fen/../*[not(@wit = $fen/@wit)]) = 0) then 'omisisão' else $fen/../*[not(@wit = $fen/@wit)])||')'}
                    {$fen/substring(@wit, 2)}
                    {$fen/ancestor::*[name()='div'[1]]//tei:rdg[@wit = $fen/@wit]/substring(@hand, 2)}
                    {$author/tei:persName/string()}
                    {$author/tei:floruit/@from||'-'||$author/tei:floruit/@to|| ' (' ||$author/tei:floruit/@period||')'}
                    {$fen/ancestor::*[name() ='div'[1]]/substring(@corresp, 2)}
                    {$fen/ancestor::*[name()='l']/@n/string()}

             }

Variaçom gráfica

                    Fenómeno
                    Variante
                    Testemunho
                    Copista
                    Autor
                    Período
                    Cantiga
                    Linha

            {for $fen in $graph
            let $author := $poets[@xml:id = $fen/ancestor::*[name()='div'[1]]//tei:name/substring(@ref,2)]
            return
            for $ana in $fen/tokenize(replace(@ana, '#', ''), ' ')[. = $fenomenos[@feats[contains(., '#graph')]]/@xml:id]
            return

                    {$fenomenos[@xml:id = $ana]/@n/string()}
                    {(if ($fen//tei:choice) then $fen//tei:reg else $fen/string())||' (vs. '||
                    (if ($fen/../*[not(@wit = $fen/@wit)]/tei:choice) then $fen/../*[not(@wit = $fen/@wit)]//tei:reg/string()
                    else $fen/../*[not(@wit = $fen/@wit)]/string())||')'}
                    {$fen/substring(@wit, 2)}
                    {$fen/ancestor::*[name()='div'[1]]//tei:rdg[@wit = $fen/@wit]/substring(@hand, 2)}
                    {$author/tei:persName/string()}
                    {$author/tei:floruit/@from||'-'||$author/tei:floruit/@to|| ' (' ||$author/tei:floruit/@period||')'}
                    {$fen/ancestor::*[name() ='div'[1]]/substring(@corresp, 2)}
                    {$fen/ancestor::*[name()='l']/@n/string()}

             }

Erros de cópia

                    Fenómeno
                    Variante
                    Testemunho
                    Copista
                    Autor
                    Período
                    Cantiga
                    Linha

            {for $fen in $error
            let $author := $poets[@xml:id = $fen/ancestor::*[name()='div'[1]]//tei:name/substring(@ref,2)]
            return
            for $ana in $fen/tokenize(replace(@ana, '#', ''), ' ')[. = $fenomenos[@feats[contains(., '#Error')]]/@xml:id]
            return

                    {$fenomenos[@xml:id = $ana]/@n/string()}
                    {(if ($fen//tei:choice) then $fen//tei:reg else $fen/string())||' (vs. '||
                    (if ($fen/../*[not(@wit = $fen/@wit)]/tei:choice) then $fen/../*[not(@wit = $fen/@wit)]//tei:reg/string()
                    else $fen/../*[not(@wit = $fen/@wit)]/string())||')'}
                    {$fen/substring(@wit, 2)}
                    {$fen/ancestor::*[name()='div'[1]]//tei:rdg[@wit = $fen/@wit]/substring(@hand, 2)}
                    {$author/tei:persName/string()}
                    {$author/tei:floruit/@from||'-'||$author/tei:floruit/@to|| ' (' ||$author/tei:floruit/@period||')'}
                    {$fen/ancestor::*[name() ='div'[1]]/substring(@corresp, 2)}
                    {$fen/ancestor::*[name()='l']/@n/string()}

             }

xquery version "3.0";
declare namespace tei="http://www.tei-c.org/ns/1.0";(:
declare option exist:serialize "method=html5 media-type=text/html omit-xml-declaration=yes indent=yes";:)
let $fenomenos := doc('/db/exemplos/feature_library.xml')//tei:fs
let $cantigas := doc('/db/exemplos/A1-A4_draft.xml')//tei:div[@type='poem']
let $ling := $cantigas//tei:rdg[tokenize(replace(@ana, '#', ''), ' ') = $fenomenos[@feats[contains(., '#ling')]]/@xml:id]
let $graph := $cantigas//tei:rdg[tokenize(replace(@ana, '#', ''), ' ') = $fenomenos[@feats[contains(., '#graph')]]/@xml:id]
let $error := $cantigas//tei:rdg[tokenize(replace(@ana, '#', ''), ' ') = $fenomenos[@feats[contains(., '#Error')]]/@xml:id]
let $poets := doc('/db/exemplos/corpus_autores.xml')//tei:person

(: Problemas que resolver:
    1. Formatar <ex>
        :)

return

       <title>Estudos lingüísticos</title>

Variaçom lingüística

                    Fenómeno
                    Variante
                    Testemunho
                    Copista
                    Autor
                    Período
                    Cantiga
                    Linha

            {for $fen in $ling
            let $author := $poets[@xml:id = $fen/ancestor::*[name()='div'[1]]//tei:name/substring(@ref,2)]
            return
            for $ana in $fen/tokenize(replace(@ana, '#', ''), ' ')[. = $fenomenos[@feats[contains(., '#ling')]]/@xml:id]
            return

                    {$fenomenos[@xml:id = $ana]/@n/string()}
                    {(if ($fen//tei:choice) then $fen//tei:reg else
                    (if (string-length($fen) = 0) then 'omisión'
                    else $fen/string()))||' (vs. '||
                    (if ($fen/../*[not(@wit = $fen/@wit)]/tei:choice) then $fen/../*[not(@wit = $fen/@wit)]//tei:reg/string()
                    else
                    if (string-length($fen/../*[not(@wit = $fen/@wit)]) = 0) then 'omisión' else $fen/../*[not(@wit = $fen/@wit)]/string())||')'}
                    {$fen/substring(@wit, 2)}
                    {$fen/ancestor::*[name()='div'[1]]//tei:rdg[@wit = $fen/@wit]/substring(@hand, 2)}
                    {$author/tei:persName/string()}
                    {$author/tei:floruit/@from||'-'||$author/tei:floruit/@to|| ' (' ||$author/tei:floruit/@period||')'}
                    {$fen/ancestor::*[name() ='div'[1]]/substring(@corresp, 2)}
                    {$fen/ancestor::*[name()='l']/@n/string()}

             }

Variaçom gráfica

                    Fenómeno
                    Variante
                    Testemunho
                    Copista
                    Autor
                    Período
                    Cantiga
                    Linha

            {for $fen in $graph
            let $author := $poets[@xml:id = $fen/ancestor::*[name()='div'[1]]//tei:name/substring(@ref,2)]
            return
            for $ana in $fen/tokenize(replace(@ana, '#', ''), ' ')[. = $fenomenos[@feats[contains(., '#graph')]]/@xml:id]
            return

                    {$fenomenos[@xml:id = $ana]/@n/string()}
                    {(if ($fen//tei:choice) then $fen//tei:reg else $fen/string())||' (vs. '||
                    (if ($fen/../*[not(@wit = $fen/@wit)]/tei:choice) then $fen/../*[not(@wit = $fen/@wit)]//tei:reg/string()
                    else $fen/../*[not(@wit = $fen/@wit)]/string())||')'}
                    {$fen/substring(@wit, 2)}
                    {$fen/ancestor::*[name()='div'[1]]//tei:rdg[@wit = $fen/@wit]/substring(@hand, 2)}
                    {$author/tei:persName/string()}
                    {$author/tei:floruit/@from||'-'||$author/tei:floruit/@to|| ' (' ||$author/tei:floruit/@period||')'}
                    {$fen/ancestor::*[name() ='div'[1]]/substring(@corresp, 2)}
                    {$fen/ancestor::*[name()='l']/@n/string()}

             }

Erros de cópia

                    Fenómeno
                    Variante
                    Testemunho
                    Copista
                    Autor
                    Período
                    Cantiga
                    Linha

            {for $fen in $error
            let $author := $poets[@xml:id = $fen/ancestor::*[name()='div'[1]]//tei:name/substring(@ref,2)]
            return
            for $ana in $fen/tokenize(replace(@ana, '#', ''), ' ')[. = $fenomenos[@feats[contains(., '#Error')]]/@xml:id]
            return

                    {$fenomenos[@xml:id = $ana]/@n/string()}
                    {(if ($fen//tei:choice) then $fen//tei:reg else $fen/string())||' (vs. '||
                    (if ($fen/../*[not(@wit = $fen/@wit)]/tei:choice) then $fen/../*[not(@wit = $fen/@wit)]//tei:reg/string()
                    else $fen/../*[not(@wit = $fen/@wit)]/string())||')'}
                    {$fen/substring(@wit, 2)}
                    {$fen/ancestor::*[name()='div'[1]]//tei:rdg[@wit = $fen/@wit]/substring(@hand, 2)}
                    {$author/tei:persName/string()}
                    {$author/tei:floruit/@from||'-'||$author/tei:floruit/@to|| ' (' ||$author/tei:floruit/@period||')'}
                    {$fen/ancestor::*[name() ='div'[1]]/substring(@corresp, 2)}
                    {$fen/ancestor::*[name()='l']/@n/string()}

             }


added a "cancel" button

added a "cancel" button

xquery version "1.0";

(: ~
 : Module Name:             edit value domain webpage and XQuery
 :
 : Module Version           3.0
 :
 : Date                     26th Aug 2009
 :
 : Copyright                The cagrid consortium
 :
 : Module overview          Edit Value Domain
 :
 :)

(:~
 :    @author Rakesh Dhaval
 :    @author Puneet Mathur
 :    @version 3.0
 :    allows editing the DataElementConcept
~ :)

  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";

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

  import module namespace
    lib-uri-resolution="http://www.cagrid.org/xquery/library/resolver"
    at "../resolver/m-lib-uri-resolution.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 function local:value_domain(
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,
   $conceptual_domain_id as xs:string?,
   $enum_datatype as xs:string?,
   $enum_uom as xs:string?,
   $char_quantity as xs:string?,
   $value_domain_format as xs:string?,
   $values as xs:string*
   ) as xs:boolean
{
   let $version := lib-forms:substring-after-last($id,'_')
   let $data-identifier := substring-after(lib-forms:substring-before-last($id,'_'),'_')
   let $doc-name := concat($id,'.xml')
   let $concept_domain := lib-util:mdrElement("conceptual_domain",$conceptual_domain_id)
   let $permissible-identifier := substring-after(lib-forms:substring-before-last($id,'_'),'_')
   let $value_meaning_identifier := $concept_domain//openMDR:value_meaning_identifier/text()
   let $content := (
            lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
            lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
            lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),

             for $meaning at $pos in $concept_domain//openMDR:value_meaning_description
                    return (
                       element openMDR:containing {
                         attribute permissible_value_identifier {$permissible-identifier},
                         element openMDR:permissible_value_begin_date {current-date()},
                         element openMDR:value_item {$values[$pos]},
                         element openMDR:contained_in {$value_meaning_identifier[$pos]}
                       }
             ),
            element openMDR:representing {$conceptual_domain_id},
            element openMDR:value_domain_datatype {$enum_datatype},
            element openMDR:value_domain_unit_of_measure {$enum_uom},
            element openMDR:value_domain_maximum_character_quantity{$char_quantity},
            element openMDR:value_domain_format{$value_domain_format}

    )

   (: compose the document :)
    let $document := (
     if($values > '' ) then (
      element openMDR:Enumerated_Value_Domain {
            attribute item_registration_authority_identifier {$reg-auth},
            attribute data_identifier {$data-identifier},
            attribute version {$version},
            $content
           }
      ) else (
       element openMDR:Non_Enumerated_Value_Domain {
            attribute item_registration_authority_identifier {$reg-auth},
            attribute data_identifier {$data-identifier},
            attribute version {$version},
            $content
           }
      )
   )

   let $collection := 'value_domain'
   let $message := lib-forms:store-document($document)
   return
      if ($message='stored')
      then true()
      else response:redirect-to(xs:anyURI(concat("../web/login.xquery?calling_page=editValueDomain.xquery&",$message)))
};

declare function local:input-page(
   $message as xs:string?,
   $id as xs:string?,
   $reg-auth as xs:string?,
   $administrative-note  as xs:string?,
   $administrative-status  as xs:string?,
   $administered-by  as xs:string?,
   $submitted-by  as xs:string?,
   $registered-by  as xs:string?,
   $context-ids  as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $action as xs:string?,
   $preferred as xs:string?,
   $conceptual_domain_id as xs:string?,
   $enum_datatype as xs:string?,
   $enum_uom as xs:string?,
   $char_quantity as xs:string?,
   $value_domain_format as xs:string?,
   $values as xs:string*
   ) {
   let $skip-name := substring-after($action,'delete naming entry')
   let $skip-name-index := if ($skip-name>'') then xs:int($skip-name) else 0
   return

                This form will allow you to edit a Value Domain in the metadata repository

                <form name="edit_value_domain" action="editValueDomain.xquery" method="post" class="cagridForm" enctype="multipart/form-data">

                {lib-forms:hidden-element('id',$id)}
                {lib-forms:hidden-element('updating','updating')}

                {lib-forms:edit-admin-item($reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $action)}

                            Conceptual Domain

                        {
                        let $concept_domain := lib-util:mdrElement("conceptual_domain",$conceptual_domain_id)

                        return
                        if ($conceptual_domain_id > '' or $conceptual_domain_id eq "Cancel")
                        then (

                                Conceptual Domain ID
                                {$conceptual_domain_id}
                                {session:set-attribute("old_cd_id", $conceptual_domain_id)}
                                {lib-forms:popup-form-search('conceptual_domain','conceptual_domain_id','edit_value_domain', 'Change Relationship')}
                                {lib-forms:hidden-element('conceptual_domain_id',$conceptual_domain_id)}

,

                                Conceptual Domain Name
                                {administered-item:preferred-name('conceptual_domain',$conceptual_domain_id)}

,

Value Domain
,

                               Value Domain Data Type
                               {lib-forms:make-select-datatype('enum_datatype', $enum_datatype)}

,

                               Value Domain Unit of Measure
                               {lib-forms:make-select-uom('enum_uom',$enum_uom)}

,

                               Value Domain Format (E.g. MM-DD-YYYY)
                               <input type="text" name="value_domain_format" value='{$value_domain_format}'></input>

,

                               Value Domain Maximum Character Count
                               <input type="text" name="char_quantity" value='{$char_quantity}'></input>

,
                           if ($concept_domain//openMDR:value_meaning_description > '')
                           then
                           (

                                   Possible Values
                                   meaning
                                   value

,
                                        for $meaning at $pos in $concept_domain//openMDR:value_meaning_description
                                        return (

                                              Permissable Value {$pos}
                                              {$meaning}
                                              {lib-forms:input-element('values', 20, $values[$pos])}

                                        )
                           )
                           else ()
                    )
                    else (

                                    Choose Conceptual Domain
                                    {lib-forms:make-select-form-admin-item('conceptual_domain','conceptual_domain_id',$conceptual_domain_id,'edit_value_domain', 'Select Relationship')}

                   )
               }

Store

	<input type="submit" name="update" value="Store Changes"/>
                          <input type="submit"  name="update" value="Cancel"
                              onClick= "{concat("window.open('../web/value_domain.xquery?compound_id=", $id, "');")}" />

          </form>

{$message}

   };

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

                    Value Domain modified.

                Return to maintenance menu

                Create another Value Domain

};

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 $updating := request:get-parameter('updating','')
   let $title as xs:string := concat("Editing ValueDomain ", $id)
   let $element := lib-util:mdrElement("value_domain",$id)
   let $action := request:get-parameter('update','')

   let $ireg-auth := string($element/@item_registration_authority_identifier)
   let $iadministrative-note := string($element//openMDR:administrative_note)
   let $iadministrative-status := string($element//openMDR:administrative_status)
   let $iadministered-by := string($element//openMDR:administered_by)
   let $isubmitted-by := string($element//openMDR:submitted_by)
   let $iregistered-by := string($element//openMDR:registered_by)
   let $icontext-ids := $element//openMDR:context_identifier
   let $icountry-identifiers := $element//openMDR:country_identifier
   let $ilanguage-identifiers := $element//openMDR:language_identifier
   let $inames := $element//openMDR:name
   let $idefinitions := $element//openMDR:definition_text
   let $isources := $element//openMDR:definition_source_reference
   let $ipreferred := string(fn:index-of($element//openMDR:preferred_designation,'true'))

    let $iconceptual_domain_id := if($element//openMDR:representing/text() > '')
                                    then ($element//openMDR:representing/text()) else ("")
    let $iconceptual_domain := lib-util:mdrElement("conceptual_domain",$iconceptual_domain_id)
    let $ivalues := $element//openMDR:value_item
    let $ienum_datatype := $element//openMDR:value_domain_datatype
    let $ienum_uom := $element//openMDR:value_domain_unit_of_measure
    let $ichar_quantity := $element//openMDR:value_domain_maximum_character_quantity
    let $ivalue_domain_format := $element//openMDR:value_domain_format

    (:
    let $icontained_in_identifier := $element//openMDR:contained_in
    let $log := util:log-system-err($iconceptual_domain)
    let $log := util:log-system-err($ivalues)
    let $log := util:log-system-err($element//openMDR:contained_in)
    let $log := util:log-system-err($iconceptual_domain_id)
    let $log := util:log-system-err(value-meaning:value-meaning($element/openMDR:contained_in/text()/openMDR:value_meaning_description))
    let $log := util:log-system-err($element//openMDR:contained_in/text()/openMDR:value_meaning_description)
    let test := element//openMDR:contained_in/text())/openMDR:value_meaning_description
    for $meaning at $pos in $iconceptual_domain//openMDR:value_meaning_description
       let $log := util:log-system-err($meaning)
    :)

   let $reg-auth := request:get-parameter('registration-authority','')
   let $administrative-note := request:get-parameter('administrative-note','')
   let $administrative-status := request:get-parameter('administrative-status','')
   let $administered-by := request:get-parameter('administered-by','')
   let $submitted-by := request:get-parameter('submitted-by','')
   let $registered-by := request:get-parameter('registered-by','')
   let $context-ids := request:get-parameter('context-ids',())
   let $country-identifiers := request:get-parameter('country-identifiers',())
   let $language-identifiers := request:get-parameter('language-identifiers',())
   let $names := request:get-parameter('names',())
   let $definitions := request:get-parameter('definitions',())
   let $sources := request:get-parameter('sources',())
   let $preferred := request:get-parameter('preferred','')
   let $conceptual_domain_id := request:get-parameter('conceptual_domain_id','')
   let $values := request:get-parameter('values',())
   let $enum_datatype := request:get-parameter('enum_datatype','')
   let $enum_uom := request:get-parameter('enum_uom','')
   let $char_quantity := request:get-parameter('char_quantity','')
   let $value_domain_format := request:get-parameter('value_domain_format','')

   return
      lib-rendering:txfrm-webpage(
      $title,
      if ($action='Store Changes')
      then
         (
         if (
               local:value_domain
                  (
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $conceptual_domain_id,
                     $enum_datatype,
                     $enum_uom,
                     $char_quantity,
                     $value_domain_format,
                     $values
                  )
            )
         then (local:success-page()  )
         else (local:input-page(
            'could not store document',
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $action,
                     $preferred,
                     $conceptual_domain_id,
                     $enum_datatype,
                     $enum_uom,
                     $char_quantity,
                     $value_domain_format,
                     $values
                     )
               )
         )
       else if ($action='Change Relationship')
         then(
               let $conceptual_domain_id as xs:string? := ""

               return
               local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               $conceptual_domain_id,
               $enum_datatype,
               $enum_uom,
               $char_quantity,
               $value_domain_format,
               $values
               )
         )
         else if($conceptual_domain_id eq "Cancel")
         then(
               local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               session:get-attribute("old_cd_id"),
               $enum_datatype,
               $enum_uom,
               $char_quantity,
               $value_domain_format,
               $values
               ),
               session:set-attribute("old_cd_id", $iconceptual_domain_id)
        )
        else (
         if ($updating ='updating')
         then (

         local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               $conceptual_domain_id,
               $enum_datatype,
               $enum_uom,
               $char_quantity,
               $value_domain_format,
               $values
               )
         ) else (
               local:input-page
               (
               '',
               $id,
               $ireg-auth,
               $iadministrative-note,
               $iadministrative-status,
               $iadministered-by,
               $isubmitted-by,
               $iregistered-by,
               $icontext-ids,
               $icountry-identifiers,
               $ilanguage-identifiers,
               $inames,
               $idefinitions,
               $isources,
               $action,
               $ipreferred,
               $iconceptual_domain_id,
               $ienum_datatype,
               $ienum_uom,
               $ichar_quantity,
               $ivalue_domain_format,
               $ivalues
               )
         )
       )
    )

xquery version "1.0";

(: ~
 : Module Name:             edit value domain webpage and XQuery
 :
 : Module Version           3.0
 :
 : Date                     26th Aug 2009
 :
 : Copyright                The cagrid consortium
 :
 : Module overview          Edit Value Domain
 :
 :)

(:~
 :    @author Rakesh Dhaval
 :    @author Puneet Mathur
 :    @version 3.0
 :    allows editing the DataElementConcept
~ :)

  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";

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

  import module namespace
    lib-uri-resolution="http://www.cagrid.org/xquery/library/resolver"
    at "../resolver/m-lib-uri-resolution.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 function local:value_domain(
   $id as xs:string,
   $reg-auth as xs:string,
   $administrative-note as xs:string,
   $administrative-status as xs:string,
   $administered-by as xs:string,
   $submitted-by as xs:string,
   $registered-by as xs:string,
   $context-ids as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $preferred as xs:string?,
   $conceptual_domain_id as xs:string?,
   $enum_datatype as xs:string?,
   $enum_uom as xs:string?,
   $char_quantity as xs:string?,
   $value_domain_format as xs:string?,
   $values as xs:string*
   ) as xs:boolean
{
   let $version := lib-forms:substring-after-last($id,'_')
   let $data-identifier := substring-after(lib-forms:substring-before-last($id,'_'),'_')
   let $doc-name := concat($id,'.xml')
   let $concept_domain := lib-util:mdrElement("conceptual_domain",$conceptual_domain_id)
   let $permissible-identifier := substring-after(lib-forms:substring-before-last($id,'_'),'_')
   let $value_meaning_identifier := $concept_domain//openMDR:value_meaning_identifier/text()
   let $content := (
            lib-make-admin-item:administration-record($administrative-note,$administrative-status,'Recorded'),
            lib-make-admin-item:custodians($administered-by,$registered-by,$submitted-by),
            lib-make-admin-item:havings(
                    $context-ids,
                    $country-identifiers,
                    $language-identifiers,
                    $names,
                    $definitions,
                    $preferred,
                    $sources),

             for $meaning at $pos in $concept_domain//openMDR:value_meaning_description
                    return (
                       element openMDR:containing {
                         attribute permissible_value_identifier {$permissible-identifier},
                         element openMDR:permissible_value_begin_date {current-date()},
                         element openMDR:value_item {$values[$pos]},
                         element openMDR:contained_in {$value_meaning_identifier[$pos]}
                       }
             ),
            element openMDR:representing {$conceptual_domain_id},
            element openMDR:value_domain_datatype {$enum_datatype},
            element openMDR:value_domain_unit_of_measure {$enum_uom},
            element openMDR:value_domain_maximum_character_quantity{$char_quantity},
            element openMDR:value_domain_format{$value_domain_format}

    )

   (: compose the document :)
    let $document := (
     if($values > '' ) then (
      element openMDR:Enumerated_Value_Domain {
            attribute item_registration_authority_identifier {$reg-auth},
            attribute data_identifier {$data-identifier},
            attribute version {$version},
            $content
           }
      ) else (
       element openMDR:Non_Enumerated_Value_Domain {
            attribute item_registration_authority_identifier {$reg-auth},
            attribute data_identifier {$data-identifier},
            attribute version {$version},
            $content
           }
      )
   )

   let $collection := 'value_domain'
   let $message := lib-forms:store-document($document)
   return
      if ($message='stored')
      then true()
      else response:redirect-to(xs:anyURI(concat("../web/login.xquery?calling_page=editValueDomain.xquery&",$message)))
};

declare function local:input-page(
   $message as xs:string?,
   $id as xs:string?,
   $reg-auth as xs:string?,
   $administrative-note  as xs:string?,
   $administrative-status  as xs:string?,
   $administered-by  as xs:string?,
   $submitted-by  as xs:string?,
   $registered-by  as xs:string?,
   $context-ids  as xs:string*,
   $country-identifiers as xs:string*,
   $language-identifiers as xs:string*,
   $names as xs:string*,
   $definitions as xs:string*,
   $sources as xs:string*,
   $action as xs:string?,
   $preferred as xs:string?,
   $conceptual_domain_id as xs:string?,
   $enum_datatype as xs:string?,
   $enum_uom as xs:string?,
   $char_quantity as xs:string?,
   $value_domain_format as xs:string?,
   $values as xs:string*
   ) {
   let $skip-name := substring-after($action,'delete naming entry')
   let $skip-name-index := if ($skip-name>'') then xs:int($skip-name) else 0
   return

                This form will allow you to edit a Value Domain in the metadata repository

                <form name="edit_value_domain" action="editValueDomain.xquery" method="post" class="cagridForm" enctype="multipart/form-data">

                {lib-forms:hidden-element('id',$id)}
                {lib-forms:hidden-element('updating','updating')}

                {lib-forms:edit-admin-item($reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $action)}

                            Conceptual Domain

                        {
                        let $concept_domain := lib-util:mdrElement("conceptual_domain",$conceptual_domain_id)
                        return
                        if ($conceptual_domain_id > '' or $conceptual_domain_id eq "Cancel")
                        then (

                                Conceptual Domain ID
                                {$conceptual_domain_id}
                                {session:set-attribute("old_cd_id", $conceptual_domain_id)}
                                {lib-forms:popup-form-search('conceptual_domain','conceptual_domain_id','edit_value_domain', 'Change Relationship')}
                                {lib-forms:hidden-element('conceptual_domain_id',$conceptual_domain_id)}

,

                                Conceptual Domain Name
                                {administered-item:preferred-name('conceptual_domain',$conceptual_domain_id)}

,

Value Domain
,

                               Value Domain Data Type
                               {lib-forms:make-select-datatype('enum_datatype', $enum_datatype)}

,

                               Value Domain Unit of Measure
                               {lib-forms:make-select-uom('enum_uom',$enum_uom)}

,

                               Value Domain Format (E.g. MM-DD-YYYY)
                               <input type="text" name="value_domain_format" value='{$value_domain_format}'></input>

,

                               Value Domain Maximum Character Count
                               <input type="text" name="char_quantity" value='{$char_quantity}'></input>

,
                           if ($concept_domain//openMDR:value_meaning_description > '')
                           then
                           (

                                   Possible Values
                                   meaning
                                   value

,
                                        for $meaning at $pos in $concept_domain//openMDR:value_meaning_description
                                        return (

                                              Permissable Value {$pos}
                                              {$meaning}
                                              {lib-forms:input-element('values', 20, $values[$pos])}

                                        )
                           )
                           else ()
                    )
                    else (

                                    {util:log-system-out(concat("else_id : ",$conceptual_domain_id) )}
                                    Choose Conceptual Domain
                                    {lib-forms:make-select-form-admin-item('conceptual_domain','conceptual_domain_id',$conceptual_domain_id,'edit_value_domain', 'Select Relationship')}

                   )
               }

Store

	<input type="submit" name="update" value="Store Changes"/>	<input type="submit" name="update" value="Clear"/>

          </form>

{$message}

   };

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

                    Value Domain modified.

                Return to maintenance menu

                Create another Value Domain

};

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 $updating := request:get-parameter('updating','')
   let $title as xs:string := concat("Editing ValueDomain ", $id)
   let $element := lib-util:mdrElement("value_domain",$id)
   let $action := request:get-parameter('update','')

   let $ireg-auth := string($element/@item_registration_authority_identifier)
   let $iadministrative-note := string($element//openMDR:administrative_note)
   let $iadministrative-status := string($element//openMDR:administrative_status)
   let $iadministered-by := string($element//openMDR:administered_by)
   let $isubmitted-by := string($element//openMDR:submitted_by)
   let $iregistered-by := string($element//openMDR:registered_by)
   let $icontext-ids := $element//openMDR:context_identifier
   let $icountry-identifiers := $element//openMDR:country_identifier
   let $ilanguage-identifiers := $element//openMDR:language_identifier
   let $inames := $element//openMDR:name
   let $idefinitions := $element//openMDR:definition_text
   let $isources := $element//openMDR:definition_source_reference
   let $ipreferred := string(fn:index-of($element//openMDR:preferred_designation,'true'))

    let $iconceptual_domain_id := if($element//openMDR:representing/text() > '')
                                    then ($element//openMDR:representing/text()) else ("")
    let $iconceptual_domain := lib-util:mdrElement("conceptual_domain",$iconceptual_domain_id)
    let $ivalues := $element//openMDR:value_item
    let $ienum_datatype := $element//openMDR:value_domain_datatype
    let $ienum_uom := $element//openMDR:value_domain_unit_of_measure
    let $ichar_quantity := $element//openMDR:value_domain_maximum_character_quantity
    let $ivalue_domain_format := $element//openMDR:value_domain_format
    (:
    let $icontained_in_identifier := $element//openMDR:contained_in
    let $log := util:log-system-err($iconceptual_domain)
    let $log := util:log-system-err($ivalues)
    let $log := util:log-system-err($element//openMDR:contained_in)
    let $log := util:log-system-err($iconceptual_domain_id)
    let $log := util:log-system-err(value-meaning:value-meaning($element/openMDR:contained_in/text()/openMDR:value_meaning_description))
    let $log := util:log-system-err($element//openMDR:contained_in/text()/openMDR:value_meaning_description)
    let test := element//openMDR:contained_in/text())/openMDR:value_meaning_description
    for $meaning at $pos in $iconceptual_domain//openMDR:value_meaning_description
       let $log := util:log-system-err($meaning)
    :)

   let $reg-auth := request:get-parameter('registration-authority','')
   let $administrative-note := request:get-parameter('administrative-note','')
   let $administrative-status := request:get-parameter('administrative-status','')
   let $administered-by := request:get-parameter('administered-by','')
   let $submitted-by := request:get-parameter('submitted-by','')
   let $registered-by := request:get-parameter('registered-by','')
   let $context-ids := request:get-parameter('context-ids',())
   let $country-identifiers := request:get-parameter('country-identifiers',())
   let $language-identifiers := request:get-parameter('language-identifiers',())
   let $names := request:get-parameter('names',())
   let $definitions := request:get-parameter('definitions',())
   let $sources := request:get-parameter('sources',())
   let $preferred := request:get-parameter('preferred','')
   let $conceptual_domain_id := request:get-parameter('conceptual_domain_id','')
   let $values := request:get-parameter('values',())
   let $enum_datatype := request:get-parameter('enum_datatype','')
   let $enum_uom := request:get-parameter('enum_uom','')
   let $char_quantity := request:get-parameter('char_quantity','')
   let $value_domain_format := request:get-parameter('value_domain_format','')

   return
      lib-rendering:txfrm-webpage(
      $title,
      if ($action='Store Changes')
      then
         (
         if (
               local:value_domain
                  (
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $preferred,
                     $conceptual_domain_id,
                     $enum_datatype,
                     $enum_uom,
                     $char_quantity,
                     $value_domain_format,
                     $values
                  )
            )
         then (local:success-page()  )
         else (local:input-page(
            'could not store document',
                     $id,
                     $reg-auth,
                     $administrative-note,
                     $administrative-status,
                     $administered-by,
                     $submitted-by,
                     $registered-by,
                     $context-ids,
                     $country-identifiers,
                     $language-identifiers,
                     $names,
                     $definitions,
                     $sources,
                     $action,
                     $preferred,
                     $conceptual_domain_id,
                     $enum_datatype,
                     $enum_uom,
                     $char_quantity,
                     $value_domain_format,
                     $values
                     )
               )
         )
       else if ($action='Change Relationship')
         then(
               let $conceptual_domain_id as xs:string? := ""

               return
               local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               $conceptual_domain_id,
               $enum_datatype,
               $enum_uom,
               $char_quantity,
               $value_domain_format,
               $values
               )
         )
         else if($conceptual_domain_id eq "Cancel")
         then(
               local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               session:get-attribute("old_cd_id"),
               $enum_datatype,
               $enum_uom,
               $char_quantity,
               $value_domain_format,
               $values
               ),
               session:set-attribute("old_cd_id", $iconceptual_domain_id)
        )
        else (
         if ($updating ='updating')
         then (

         local:input-page
               (
               '',
               $id,
               $reg-auth,
               $administrative-note,
               $administrative-status,
               $administered-by,
               $submitted-by,
               $registered-by,
               $context-ids,
               $country-identifiers,
               $language-identifiers,
               $names,
               $definitions,
               $sources,
               $action,
               $preferred,
               $conceptual_domain_id,
               $enum_datatype,
               $enum_uom,
               $char_quantity,
               $value_domain_format,
               $values
               )
         ) else (
               local:input-page
               (
               '',
               $id,
               $ireg-auth,
               $iadministrative-note,
               $iadministrative-status,
               $iadministered-by,
               $isubmitted-by,
               $iregistered-by,
               $icontext-ids,
               $icountry-identifiers,
               $ilanguage-identifiers,
               $inames,
               $idefinitions,
               $isources,
               $action,
               $ipreferred,
               $iconceptual_domain_id,
               $ienum_datatype,
               $ienum_uom,
               $ichar_quantity,
               $ivalue_domain_format,
               $ivalues
               )
         )
       )
    )