# Copyright for URLibService (c) 1995 - 2025,
# by Gerald Banon. All rights reserved.
# Depositing a Document (DD)

package provide dpi.inpe.br/banon/1998/08.02.08.56 2.1

# ----------------------------------------------------------------------
# DDDialog
# Example 33-2
# the entry names and types are:
# ddDirectory  .dir.
# ddRepository  .rep.

proc DDDialog {} {
# runs with start
	global w
	global environmentArray
	global tcl_platform
	global ddChoice1 ddChoice2
	global ddChoice3
#	global ddLanguage currentLanguage
#	global keyRepositoryList
#	global dd.dirPostMenu
#	global dd.repPostMenu
	global ddDirectory
	global ddRepository
	global typeTable
	global listNameTable
#	global ddDialogLanguage
	global col
	
#	set col ../../../../..
	set ddDirectory ddDirectory
	set ddRepository ddRepository
	set typeTable(ddDirectory) .dir.
	set typeTable(ddRepository) .rep.
	set listNameTable(ddDirectory) {}
	set listNameTable(ddRepository) keyRepositoryList
	set listNameTable(ddSearch) {}
	frame $w.main
	set f $w.main.dd
	frame $f
#	set currentLanguage $environmentArray(spLanguageEntry)
## ddDialogLanguage
#	set ddDialogLanguage $currentLanguage
	Header $f "Depositing a Document"
	frame $f.sp1 -height .2c 	;# extra space
	set font [lindex [$f.lb configure -font] end]
# Which?
#	frame $f.dir -borderwidth 4 -relief groove
	frame $f.dir -borderwidth 2 -relief groove
	frame $f.dir.sp -height .2c	;# extra space
	label $f.lbwhich -font {$font 10 roman}
	ConfigText $f.lbwhich " Which ? "
	message $f.dir.msg -width 10c -justify center
	ConfigText $f.dir.msg \
"Choose the Default or Empty Document option,
or enter the document folder name."
#	ConfigText $f.dir.msg \
#"Choose the Empty Document option,
#or enter the document folder name."
	frame $f.dir.h1
	frame $f.dir.h1.h1
	SetInitialValue ddChoice1 empty
	radiobutton $f.dir.h1.h1.b1 -variable ddChoice1 \
		-value default -cursor hand2
	ConfigText $f.dir.h1.h1.b1 {  Default Document}
	frame $f.dir.h1.h1.sp -width 1c	;# extra space
	radiobutton $f.dir.h1.h1.b2 -variable ddChoice1 \
		-value empty -cursor hand2
	ConfigText $f.dir.h1.h1.b2 {  Empty Document}
	frame $f.dir.h1.h2
	frame $f.dir.h1.h2.v2
	radiobutton $f.dir.h1.h2.b3 -variable ddChoice1 \
		-value directory -cursor hand2
	set aWhich [Selector $f.dir.h1.h2.v2 ddDirectory dd 1]
	$f.dir.h1.h1.b1 configure \
		-command "DisableEntry $aWhich dd(result1)"
	$f.dir.h1.h1.b2 configure \
		-command "DisableEntry $aWhich dd(result1)"
	$f.dir.h1.h2.b3 configure \
		-command "EnableEntry $aWhich ddDirectory dd(result1)"
	pack $f.dir.h1.h1.b1 -side left
	pack $f.dir.h1.h1.sp -side left	;# extra space
	pack $f.dir.h1.h1.b2 -side left
	pack $f.dir.h1.h2.b3 -side left
	pack $f.dir.h1.h2.v2 -side right -fill both -expand true
	pack $f.dir.h1.h1 -side top -fill x -expand true
	pack $f.dir.h1.h2 -side right -fill both -expand true
	pack $f.dir.sp -side top	;# extra space
	pack $f.dir.msg -side top
#	pack $f.dir.h1 -side top -padx .2c -pady .16c -fill x
	pack $f.dir.h1 -side top -padx .2c -fill x
	place $f.lbwhich -in $f.dir -anchor center \
		-relx 0.5 -y -2
# Which? - end
	frame $f.sp2 -height .6c	;# extra space
# Where?
#	frame $f.rep -borderwidth 4 -relief groove
	frame $f.rep -borderwidth 2 -relief groove
	frame $f.rep.sp -height .2c	;# extra space
	label $f.lbwhere -font {$font 10 roman}
	ConfigText $f.lbwhere " Where ? "
	message $f.rep.msg -width 10c -justify center
	ConfigText $f.rep.msg \
"Choose the New Repository option or
enter the existing repository name."
	frame $f.rep.h1
	frame $f.rep.h1.h1
	radiobutton $f.rep.h1.h1.b1 -variable ddChoice2 \
		-value new -cursor hand2
	ConfigText $f.rep.h1.h1.b1 {  New Repository}
	label $f.rep.h1.h1.lb1 -font {courier 9}
	label $f.rep.h1.h1.lb2 -font {courier 9}
	SetIndicator dd $f	;# dd $w.main.dd
	frame $f.rep.h1.h2
	frame $f.rep.h1.h2.v2
	radiobutton $f.rep.h1.h2.b2 -variable ddChoice2 \
		-value repository -cursor hand2
	if [string equal {127.0.0.1} $environmentArray(ipAddress)] {
		set ddChoice2 repository	;# added by GJFB in 2010-08-11
		$f.rep.h1.h1.b1 configure -state disabled	;# added by GJFB in 2010-08-11
		$f.rep.h1.h2.b2 configure -state disabled	;# added by GJFB in 2010-08-11
	} else {
		SetInitialValue ddChoice2 new
	}
# key first == 0; repository first == 1
	SetInitialValue ddReverse 0
	SetInitialValue ddSearch 0
	SetInitialValue ddSearchEntry {}
	SetInitialValue ddSelectedKeyRepList {}
	set aWhere [Selector $f.rep.h1.h2.v2 ddRepository dd 2 \
		$listNameTable($ddRepository)]
	$f.rep.h1.h1.b1 configure \
		-command "DisableEntry $aWhere dd(result2); \
			$f.buttons.edit.edit configure -state normal"
# puts $f.buttons.edit.edit
	$f.rep.h1.h2.b2 configure \
		-command "EnableEntry $aWhere ddRepository dd(result2) keyRepositoryList; \
			$f.buttons.edit.edit configure -state disabled"
	pack $f.rep.h1.h1.b1 -side left
	pack $f.rep.h1.h1.lb2 -side right
	pack $f.rep.h1.h1.lb1 -side right
	pack $f.rep.h1.h2.b2 -side left
	pack $f.rep.h1.h2.v2 -side right -fill both -expand true
	pack $f.rep.h1.h1 -side top -fill x -expand true
	pack $f.rep.h1.h2 -side top -fill both -expand true
	pack $f.rep.sp -side top	;# extra space
	pack $f.rep.msg -side top
#	pack $f.rep.h1 -side top -padx .2c -pady .16c -fill x
	pack $f.rep.h1 -side top -padx .2c -fill x
	place $f.lbwhere -in $f.rep -anchor center \
		-relx 0.5 -y -2
# Where? - end
# Get repository name
	if [string equal {127.0.0.1} $environmentArray(ipAddress)] {
# added by GJFB in 2010-08-11
		bind $aWhich.button3.3 <ButtonPress-3> "GetRepName $aWhich ddDirectory .dir. dd(result1)"
	} else {
		bind $aWhich.button3.3 <ButtonPress-3> \
"
GetRepName $aWhich ddDirectory .dir. dd(result1)
set ddChoice2 new
DisableEntry $aWhere dd(result2)
"
	}
# Get repository name - end
	frame $f.sp3 -height .3c ;# extra space
# radio buttons
	set r [frame $f.radio]
	frame $r.f1
#	SetInitialValue ddChoice3 copy	;# not used for security reason
	set ddChoice3 copy	;# used for security reason
	radiobutton $r.f1.r1 -variable ddChoice3 -value copy \
		-cursor hand2
	ConfigText $r.f1.r1 {copy the document (like Save As ...) }
# the blank after (default) is to avoid the array syntax
# (an array value cannot be assigned using the variable command)
	frame $r.f2
	radiobutton $r.f2.r2 -variable ddChoice3 -value preserve \
		-cursor hand2
	ConfigText $r.f2.r2 \
		{move the document and preserve the document folder}
	frame $r.f3
	radiobutton $r.f3.r3 -variable ddChoice3 -value delete \
		-cursor hand2
	ConfigText $r.f3.r3 \
		{move the document and delete the document folder}
	pack $r.f1 -side top -fill x -expand true
	pack $r.f1.r1 -side left
	pack $r.f2 -side top -fill x -expand true
	pack $r.f2.r2 -side left
	pack $r.f3 -side top -fill x -expand true
	pack $r.f3.r3 -side left

	if {$ddChoice1 == "directory"} {
		$r.f1.r1 configure -state normal 
		$r.f2.r2 configure -state normal
		$r.f3.r3 configure -state normal
	} else {
		$r.f1.r1 configure -state disabled 
		$r.f2.r2 configure -state disabled
		$r.f3.r3 configure -state disabled
	}
	bind $f.dir.h1.h1.b1 <ButtonPress-1> "\
		$r.f1.r1 configure -state disabled; \ 
		$r.f2.r2 configure -state disabled; \
		$r.f3.r3 configure -state disabled\
	"
	bind $f.dir.h1.h1.b2 <ButtonPress-1> "\
		$r.f1.r1 configure -state disabled; \ 
		$r.f2.r2 configure -state disabled; \
		$r.f3.r3 configure -state disabled\
	"
	bind $f.dir.h1.h2.b3 <ButtonPress-1> "\
		$r.f1.r1 configure -state normal; \
		$r.f2.r2 configure -state normal; \
		$r.f3.r3 configure -state normal\
	"

# radio buttons - end
	set b [Footer $f dd(ok)]
	pack $f.lb -side top -pady .25c
	pack $f.sp1 -side top	;# extra space
#	pack $f.dir -side top -fill x -ipady .05c -padx .2c -pady .05c
	pack $f.dir -side top -fill x -padx .2c -pady .05c
	pack $f.sp2 -side top	;# extra space
#	pack $f.rep -side top -fill x -ipady .05c -padx .2c -pady .05c
	pack $f.rep -side top -fill x -padx .2c -pady .05c
	pack $f.sp3 -side top	;# extra space
	pack $r -side top -pady .1c
	pack $b -side top -pady .15c
# help
	bind $w <1> "ProcessButton1 $f"
# help - end
	set focus $aWhich.entry
	pack $f -side top -fill both -expand true
	pack $w.main -side top -fill both -expand true -padx 14
#	wm geometry $w 368x504+0+0
#	wm minsize $w 310 420
#	wm maxsize $w 810 420
	SetGeometry
	CompleteEntry $aWhich.entry ddDirectory dd(result1) check
	CompleteEntry $aWhere.entry ddRepository dd(result2) check
	if {$ddChoice2 == "repository"} {
# don't allow editing the current repository metadata
		$w.main.dd.buttons.edit.edit config -state disabled
	}		
}

# DDDialog - end
# ----------------------------------------------------------------------
# DDOK
# test values are 0 or 1
# 1 means just test the input syntax and add warnings
# 0 means execute action

proc DDOK {f test} {
# runs with start
	global log
	global dd bc
	global ddChoice1 ddChoice2 ddChoice3 ddReverse
	global ddSearchEntry
	global ddSelectedKeyRepList
	global environmentArray
	global homePath
#	global serverAddress
	global keyRepositoryList

	set argument ""
	set argument "$argument -targetfile enable"
	set argument "$argument -documenttype $ddChoice1"
	set argument "$argument -repositorytype $ddChoice2"
	set argument "$argument -option $ddChoice3"
	set argument "$argument -reverse $ddReverse"
	set argument "$argument -documentpath [list $dd(result1)]"
	set argument "$argument -repositoryentry [list $dd(result2)]"

	if $test {return [DDRoutine $argument 1]}

# Waiting for the completion of other repository insertions
	WaitQueue
# Waiting for the completion of other repository insertions - end

	LogInsert [list [list Insert $log end \
		{\ndepositing a document ...\n}]]
# To let insert message in the log
	set x 0; after 1 {set x 1}; vwait x
# To let insert message in the log - end

	set dd(result1) [string trim $dd(result1)]
	if {$ddChoice2 == "new"} {
# a new repository
		regsub {@.*$} $environmentArray(spMailEntry) {} administratorUserName
#		set metadataCaptured [GetClipboard]	;# to paste the metadata
		set metadataCaptured [GetClipboard {} $administratorUserName]	;# to paste the metadata
#		set repositoryName [CreateRepMetadataRep $ddChoice1 $dd(result1) {} $metadataCaptured enable]
		set repositoryName [CreateRepMetadataRep $ddChoice1 $dd(result1) {} $metadataCaptured enable {} $ddChoice3]	;# added by GJFB in 2012-06-26 - allows the use of the preserve option

		if [string equal {} $repositoryName] {
# MakeRepository fails
			LeaveQueue [pid]
			return
		}

		set metadataRepName [Eval FindMetadataRep $repositoryName]
	} else {
# not a new repository

		set return [DDRoutine $argument]

		if {$return == 1} {
			set environmentArray(ddDirectoryEntry) $dd(result1)
			set environmentArray(ddRepositoryEntry) $dd(result2)
			set environmentArray(ddChoice1) $ddChoice1
			set environmentArray(ddChoice2) $ddChoice2
#			set environmentArray(ddChoice3) $ddChoice3
			set environmentArray(ddReverse) $ddReverse
			set environmentArray(ddSearchEntry) $ddSearchEntry
			set environmentArray(ddSelectedKeyRepList) $ddSelectedKeyRepList
			LeaveQueue [pid]
			return
		}
		if {$return == 0} {
# MakeRepository fails
			LeaveQueue [pid]
			return
		}
		set repositoryName $return
		
# Update lastupdate field in the metadata
		set metadataList {}
		set metadata2List {}
#		set history [Get repositoryProperties($repositoryName,history)]
#		set versionStamp [lindex $history end]
		set versionStamp [Eval GetVersionStamp $repositoryName]
#		set metadataRep [Eval FindMetadataRep $repositoryName]
#		set metadataRepList [Eval FindAllLanguageVersions $metadataRep]
		set metadataRepName [Eval FindMetadataRep $repositoryName]
		set metadataRepList [Eval FindAllLanguageVersions $metadataRepName]
#		foreach mRep [Eval FindAllLanguageVersions $metadataRep]
		foreach mRep $metadataRepList {
			UpdateMetadataField $mRep lastupdate $versionStamp metadataList metadata2List
		}
if 0 {
# commented by GJFB in 2020-08-18
		Eval RemoveMetadata $metadata2List
		Eval AddMetadata $metadataList
} else {
		Eval UpdateMetadata $metadata2List $metadataList	;# added by GJFB in 2020-08-18 - uses metadata2List and metadataList
}
# Update lastupdate field in the metadata - end

		Set saveMetadata 1
		Eval PostponeSaveToDisk
		Eval UpdateRepositoryListForPost [concat $repositoryName $metadataRepList]
	}

# Create the download file
	UpdateDownloadFile $repositoryName	;# may set saveMetadata to 1
# Create the download file - end
# Update keyRepositoryList
	UpdateKeyRepositoryList $repositoryName
	if ![file isdirectory $homePath/col/$metadataRepName] {
		UpdateVariables $metadataRepName
		set metadataRepName ""
	}
	UpdateKeyRepositoryList $metadataRepName
#	StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
# Update keyRepositoryList - end
	set dd(result2) [AddKey $repositoryName/ $ddReverse]
	set environmentArray(ddDirectoryEntry) $dd(result1)
	set environmentArray(ddRepositoryEntry) $repositoryName/
	set bcReverse $environmentArray(bcReverse)
	set bc(result1) [AddKey $repositoryName/ $bcReverse]
	set environmentArray(bcRepositoryEntry) $repositoryName/
	set environmentArray(ddChoice1) $ddChoice1
	set environmentArray(ddChoice2) $ddChoice2
#	set environmentArray(ddChoice3) $ddChoice3
	set environmentArray(ddReverse) $ddReverse
	set environmentArray(ddSearchEntry) $ddSearchEntry
	set environmentArray(ddSelectedKeyRepList) $ddSelectedKeyRepList
	CancelSearch $f.rep.h1.h2.v2.entry ddRepository dd(result2)
# SAVE
#	StoreArray environmentArray ../auxdoc/.environmentArray.tcl
#	StoreArray environmentArray ../auxdoc/.environmentArray2.tcl	;# backup
#	StoreArrayWithBackup environmentArray ../auxdoc/.environmentArray.tcl	;# added by GJFB in 2010-08-05
	StoreArrayWithBackup environmentArray ../auxdoc/.environmentArray.tcl w list	;# added by GJFB in 2010-08-05
##	StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
# SAVE - end
	if [info exists ddChoice3Old] {unset ddChoice3Old}	;# used in SetBackgroundEntry
	LogInsert [list [list Insert $log end \
		{\ndocument deposited\n}]]
	LeaveQueue [pid]
}

# DDOK - end
# ----------------------------------------------------------------------
# DDCancel

proc DDCancel {f} {
# runs with start
	global keyRepositoryList
	CancelSearch $f.rep.h1.h2.v2.entry ddRepository dd(result2)
# SAVE
#	StoreList keyRepositoryList ../auxdoc/.keyRepositoryList.tcl
	Eval SaveMetadata
# SAVE - end
	if [info exists ddChoice3Old] {unset ddChoice3Old}	;# used in SetBackgroundEntry
	LoadTextLog
	DisplayTextLog
}

# DDCancel - end
# ----------------------------------------------------------------------
# DDRoutine
# -targetfile can be enable or disable; for document with only 1 file,
#  enable means to set that file as target file;
#  if they are more than 1 file or if the content type is Mirror, enable preserves (if any) the targetfile
#  given in service
#  disable means to remove (if any) the targetfile (from service and repositoryProperties)
#  default is disable
# -documenttype can be "directory" or "empty" or "default"
# -repositorytype can be "new" or "repository"
# -option can be "copy" or "preserve" or "delete"
# -reverse can be 0 or 1 ; 0 means key first (in -repositoryentry)
# test value is 0 or 1
# 1 means just test the input syntax and add warnings
# 0 means test the input syntax and run the routine
# but doesn't add warnings
# -unzip value is 0 or 1; 1 means to unzip the deposited document
# -selectedfiles value is yes or no; default is yes; yes means to
# -makeauxdoc value is 0 or 1; 1 means to make auxdoc directory
# -makesource value is 0 or 1; 1 means to make source directory
## -copytosource value is 0 or 1; 1 means to deposit the document into the source as well
# -copytosource value is 0 or 1; 1 means to deposit the document into the source (only)
# -movetosource value is 0 or 1 ; 0 means don't move, 1 move the doc content to source - added by GJFB in 2016-05-10 to preserve old doc content before updating it - set in Administrator page for customizing the conference submission forms (iconet.com.br/banon/2006/07.02.02.18)
# -movebacktodoc value is 0 or 1 ; 0 means don't move, 1 move the source content to doc - added by GJFB in 2021-05-27 to give access to previously hidden video (ex: id 8JMKD3MGPGW34M/44N7JSP)
## if -updateagreement is 1 then -copytosource is forced to 0
# -fileinfo value is 0 or 1; 1 means to create size and numberoffiles
# -contenttype values are Metadata, External Contribution, ...
# -documentpath value is the absolute path of the original document (eg, C:/URLib/clipboard/)
# if -documentpath is == col/$repName/doc then the doc content is preserved otherwise
# its old content is lost (if -deletedoccontentbeforeupdate is 1)
# capture the selected files (works with tk only)
# -username is the name of the advanced user who is creating the version stamp
# is optional
# -postsubmissionscriptreplist is a list of repositories containing scripts to process
# the submitted files
# is optional
# -reference ==>
# {%0 Misc} {%@tertiarytype } {%A aa} {%I Deposited in the URLib collection.} {%X aa} {%T tt} {%@secondarykey INPE--/} 
# is optional
## -deletedoccontentbeforeupdate value is 0 or 1; 1 means to delete the doc content before depositing the new document - 1 is default
# -deletedoccontentbeforeupdate value is 0 or 1; 1 means to delete the doc (or source) content before depositing the new document - 1 is default
# -foldername value is empty or the name of the folder (or the sequence of consecutive folders) where to
# deposit the document. Empty value means to deposit the document in doc
# is optional (default is empty)
# -updateagreement value is 0 or 1; 1 means to update the agreement folder
## nothing done if -copytosource and -updateagreement are both 1 (they are incompatible)


proc DDRoutine {argument {test {0}} {repName {}}} {
# runs with start and post
# called at submission and update only
	global zipPath
	global unZipPath
	global log
#	global keyRepositoryList
#	global repositoryProperties	;# post
	global environmentArray
	global URLibServiceRepository
	global defaultDocRepository
	global homePath
	global loCoInRep
	global loBiMiRep
	global col
	global applicationName
	global pwd
	global tcl_platform
#	global devLoCoInRep
#	global serverAddressWithIP
	global errorInfo
	
	upvar #0 Text::Default default
	upvar #0 Text::Empty empty

Load $homePath/col/$URLibServiceRepository/auxdoc/@enableTrace enableTrace
TraceProcedure DDRoutine
TraceProcedure [clock format [clock seconds] -format %Y:%m.%d.%H.%M.%S]
TraceProcedure [CallTrace]

	set pid [pid]
###
	if !$test {LogInsert [list [list Insert $log end {new line}]]}	;# blk line

	foreach {name value} $argument {
		eval [list set $name $value]
	}
# puts ${-option}
# puts --${-documentpath}--

# puts [CallTrace]
# =>
# DDRoutine {
#	-targetfile enable
#	-documenttype directory
#	-repositorytype repository
#	-option preserve
#	-reverse 0
#	-documentpath {C:/Users/geral/URLib 2/clipboard2/}
#	-repositoryentry {:: urlib.net/www/2021/04.27.01.57}
#	-unzip 0
#	-selectedfiles no
#	-username banon
#	-postsubmissionscriptreplist {}
#	-reference {{%0 Film or Broadcast} {%@mirrorrepository dpi.inpe.br/banon/1999/06.19.17.00} {%D 2021} {%T Testando vínculo externo apontando para um vídeo da BAND} {%A TV BAND VALE} {%@usergroup banon} {%U https://youtu.be/w4n5K1W3caE?t=269} {%2 urlib.net/www/2021/04.27.01.57.38} {%4 urlib.net/www/2021/04.27.01.57}}
#	-deletedoccontentbeforeupdate 0
#	-copytosource 0
#	-foldername {}
#	-updateagreement 0
#	-movetosource 1
# }

# set xxx [CallTrace]
# Store xxx C:/tmp/bbb.txt auto 0 a

# set xxx 2-$argument
# Store xxx C:/tmp/aaa auto 0 a
	if {${-documenttype} == "default"} {
		set -documentpath $homePath/col/$defaultDocRepository/doc/
		set -documenttype directory	;# DEFAULT BECOMES DIRECTORY
	}
	if ![info exists -targetfile] {
		set -targetfile disable
	}
	if ![info exists -unzip] {
		set -unzip 0
	}
	if ![info exists -selectedfiles] {
		set -selectedfiles yes
	}
	if ![info exists -makeauxdoc] {
		set -makeauxdoc 1
	}
	if ![info exists -makesource] {
		set -makesource 1
	}
	if ![info exists -copytosource] {
		set -copytosource 0
	}
	if ![info exists -movetosource] {
		set -movetosource 0	;# added by GB in 2016-05-10
	}
	if ![info exists -movebacktodoc] {
		set -movebacktodoc 0	;# added by GB in 2021-05-27
	}
	if ![info exists -fileinfo] {
		set -fileinfo 1
	}
	if ![info exists -contenttype] {
		set -contenttype {}
	}
	if ![info exists -deletedoccontentbeforeupdate] {
		set -deletedoccontentbeforeupdate 1
	}
	if ![info exists -foldername] {
		set -foldername {}
	}
	if ![info exists -updateagreement] {
		set -updateagreement 0
	}
	
TraceProcedure	;# add executing time interval
TraceProcedure [list -targetfile = ${-targetfile}]

#	if {${-copytosource} && ${-updateagreement}} {
#		set -copytosource 0	;# force to 0 - when updating agreement disable copy to source option
#	}
 
# making a repository
	if {${-repositorytype} == "new"} {
# new repository
		if {${-documenttype} != "directory" || \
		[regexp {/$} ${-documentpath}] && \
		![regexp -nocase {^[c-z]:/$|^/$} ${-documentpath}]} {
###
			if !$test {
# make a repository
				if [catch {MakeRepository $repName ${-makeauxdoc} ${-makesource}} input] {
#					$log insert end $input\n
#					destroy .ddhelp
#					destroy .xxdirectory
#					destroy .xxrepository
					puts stderr $input
					puts [StoreLog {alert} {DDRoutine} "$errorInfo\n[CallTrace]"]	;# added by GJFB in 2017-03-06
					return 0	;# CreateNewRepository returns empty when DDRoutine returns 0
				}

				set repName $input
#				lappend keyRepositoryList [AddKey $repName/ 0]	;# key first
				LogInsert [list [list Insert $log end \
					{repository <$var1> made} {} \
					$repName] \
					[list TagAdd $log fixed9 \
					{<$var1>} -forward $repName]] 1 0
				LogInsert [list [list Insert $log insert {new line}]] 0 1
#				set -repositoryentry [AddKey $repName/ ${-reverse}]
			}
		} else {
# improper entry - retry
			Retry ${-documentpath}
			return 1
		}
	} else {
# not a new repository
		if ![regexp { } ${-repositoryentry}] {
# improper entry - retry
			if [regexp "^\[ \t]*$" ${-repositoryentry}] {
# empty entry 2 - retry
				if [regexp "^\[ \t]*$" ${-documentpath}] {
# empty entry 1 - retry
					Dialog OK disabled -1 DD \
						{empty entries}
				} else {
					Dialog OK disabled -1 DD \
						{empty entry}
				}
				return 1
			} else {
# not a repository - retry
				if ${-reverse} {
# repository first
					Dialog OK disabled -1 DD \
						{not a repository} \
						${-repositoryentry}
				} else {
# key first
					Dialog OK disabled -1 DD \
						{not a key} \
						${-repositoryentry}
				}
				return 1
			}
		} else {
			if ${-reverse} {
# repository first
# Correct repository entry
# Extract repName from the entry
				regexp {(.*) .*} \
					${-repositoryentry} m repName
			} else {
# key first
# Extract repName from the entry
				regexp {.* (.*)} \
					${-repositoryentry} m repName
#				if {[lsearch -exact $keyRepositoryList \
					${-repositoryentry}] == -1}
				if ![file isdirectory $homePath/col/$repName] {
# improper entry - retry
					Dialog OK disabled -1 DD \
						{not a repository} \
						$repName
					return 1
				}
			}
		}
# Correct repository entry - end

# the old target file must be deleted
###
		if !$test {
			if [file exists $col/$repName/service/targetFile] {
				Load $col/$repName/service/targetFile oldTargetFile
				file delete $col/$repName/service/targetFile
			}
			if [Info exists repositoryProperties($repName,targetfile)] {
				Unset repositoryProperties($repName,targetfile)
			}
		}
	}
	
# Depositing a Document
	if {${-documenttype} != "directory"} {
## Default Document or Empty Document
# Empty Document
		if {${-repositorytype} != "new"} {
# not a new repository
####
			if $test {
# warning
				cd $col/$repName/doc
#				regsub {\. \.\.} [glob -nocomplain -- * .*] {} fileList	;# not operational system robust
				set fileList [glob -nocomplain -- * .?*]
				set index [lsearch -exact $fileList {..}]
				set fileList [lreplace $fileList $index $index]
				if {$fileList != ""} {
# non empty doc - warning
					if {${-documenttype} == "default"} {
						set document $default
					} else {
						set document $empty
					}
					set choice ""
					set choice $choice[Dialog \
{Yes No} {disabled active} {0 0} DD \
{depositing the Default or Empty Document in a non empty doc} \
$document $repName]
					if $choice {
						cd $pwd
						return 1
					}
# Delete the existing document in the doc part of the repository
					set fileList2 {}
					foreach fileName $fileList {
						lappend fileList2 ./$fileName	;# ~WRD0000.tmp -> ./~WRD0000.tmp - added by GJFB in 2011-03-09, otherwise ~WRD0000.tmp is interpreted as a "~user" path
					}
					set cmd "file delete -force -- $fileList2"
					eval $cmd
# Delete the existing document in the doc part of the repository - end
				}
			}
		}
###
		if !$test {
			if {${-documenttype} == "default"} {
# not used (default has been changed into directory, see above)
# the Default Document
				cd $col/$repName/doc
				if [catch {open .www_browsable w} fileId] {
					puts stderr $fileId
				} else {
					puts $fileId {}
					close $fileId
				}
				set dn4 [lindex [file split $repName] end]
				if [catch {open target.html w} fileId] {
					puts stderr $fileId
				} else {
					puts $fileId "
<HTML><HEAD>
<TITLE>Target file</TITLE>
</HEAD><BODY>
<H2>Target file</H2>
<A HREF =../../$dn4/doc>Current directory</A>
</BODY></HTML>
"
					close $fileId
				}
				LogInsert [list [list Insert $log end \
					{Default Document deposited\
in the repository <$var1>} {} $repName] \
					[list TagAdd $log fixed9 \
					{<$var1>} -forward $repName]] 1 0
				LogInsert [list [list Insert $log insert {new line}]] 0 1
				set targetFile target.html
			} else {
# the Empty Document
				LogInsert [list [list Insert $log end \
					{Empty Document deposited in\
the repository <$var1>} {} $repName] \
					[list TagAdd $log fixed9 \
					{<$var1>} -forward $repName]] 1 0
				LogInsert [list [list Insert $log insert {new line}]] 0 1
			}
		}
		cd $pwd
	} else {
## neither the Default Document nor the Empty Document 
# not the Empty Document 
		if {[regexp {/$} ${-documentpath}] && ![regexp -nocase {^[c-z]:/$|^/$} ${-documentpath}]} {
# deposit the document
# document (source)
			regsub {/$} ${-documentpath} {} document
# docPath (destination)
			set docPath $homePath/col/$repName/doc
			set sourcePath $homePath/col/$repName/source
			set agreementPath $homePath/col/$repName/agreement	;# added by GJFB in 2010-12-05
			if {$tcl_platform(platform) == "windows"} {
# set to lower in order to compare document and docPath later on
# $env(DOCUMENT_ROOT) comes in lower case
				set document [string tolower $document]
				set docPath [string tolower $docPath]
				set sourcePath [string tolower $sourcePath]
				set agreementPath [string tolower $agreementPath]
			}
# destinationHomeDirectoryPath
# added by GJFB in 2012-02-17
			if ${-updateagreement} {
				set destinationHomeDirectoryPath $agreementPath
				if ![file isdirectory $agreementPath] {
					file mkdir $agreementPath
					set htaccessContent {Require user administrator}
					Store htaccessContent $agreementPath/.htaccess
					Store htaccessContent $agreementPath/.htaccess2
				}
			} else {
				if ${-copytosource} {
					set destinationHomeDirectoryPath $sourcePath
				} else {
					set destinationHomeDirectoryPath $docPath
#					if ${-movetosource} #	; commented by GJFB in 2021-05-27
					if {${-movetosource} || ${-movebacktodoc}} {
						set sourceHomeDirectoryPath $sourcePath
					}
				}
			}
			
			if {${-repositorytype} != "new"} {
# not a new repository
# set xxx [pwd]
# Store xxx C:/tmp/bbb.txt auto 0 a
#				cd $col/$repName/doc	;# commented by GJFB in 2012-02-17
				file mkdir $destinationHomeDirectoryPath	;# for old repositories that have no source directory
				cd $destinationHomeDirectoryPath	;# added by GJFB in 2012-02-17
#				regsub {\. \.\.} [glob -nocomplain -- * .*] {} fileList	;# not operational system robust
				set fileList [glob -nocomplain -- * .?*]
				set index [lsearch -exact $fileList {..}]
				set fileList [lreplace $fileList $index $index]
				if {$fileList != ""} {
####
					if {$test && [string equal $docPath $destinationHomeDirectoryPath]} {
# doc
# warning
# non empty doc - warning
						set choice ""
						set choice $choice[Dialog \
{Yes No} {disabled active} {0 0} DD \
{depositing a document from the file system in a non empty doc} \
$document $repName]
						if $choice {
							cd $pwd
							return 1
						}
					}
###
					if !$test {
# set xxx $document
# Store xxx C:/tmp/bbb auto 0 a
# set xxx $docPath
# Store xxx C:/tmp/bbb auto 0 a
#						if ![string equal $document $docPath] #
						if ![string equal $document $destinationHomeDirectoryPath] {
# $document and $docPath may be the same (see Submit (ePrint) and ProcessReview)
# Delete the existing document in the detination directory of the repository
							if ${-deletedoccontentbeforeupdate} {
#							if {${-deletedoccontentbeforeupdate} && !${-copytosource}} #
								set fileList2 {}
								foreach fileName $fileList {
									lappend fileList2 ./$fileName	;# ~WRD0000.tmp -> ./~WRD0000.tmp - added by GJFB in 2011-03-09, otherwise ~WRD0000.tmp is interpreted as a "~user" path
								}
								set cmd "file delete -force -- $fileList2"	;# warning: may not remove files whose name is not ascii (accent problem)
								eval $cmd
								if ${-updateagreement} {
										set htaccessContent {Require user administrator}
										Store htaccessContent $agreementPath/.htaccess
										Store htaccessContent $agreementPath/.htaccess2
								}
							}
# Delete the existing document in the detination directory of the repository - end
						}
					}
				}
				cd ../doc	;# added by GJFB in 2012-02-17
			}
###
# puts ${-option}
# puts [CallTrace]
			if !$test {
# Search for the selected files
				set selectedFiles ""
				if [string equal yes ${-selectedfiles}] {
# THIS PART RUNS ONLY WITH TK
					if {$applicationName == "start"} {
						if [winfo exists .xxdirectory] {
# Find the selected files
							foreach tagName \
								[.xxdirectory.f.t tag names] {
								set color [.xxdirectory.f.t tag \
									cget $tagName -background]
								if {$color == "#000088"} {
									lappend selectedFiles $tagName
# reset the background color because when using CreateRepMetadataRep
# the created metadata repository must not have any selected files
									.xxdirectory.f.t tag configure \
										$tagName -background #dddddd
								}
							}
# Find the selected files - end
						}
					}
# THIS PART RUNS ONLY WITH TK - END
				}
# Search for the selected files - end

				cd ${-documentpath}	;# source - recall: regsub {/$} ${-documentpath} {} document
#				regsub {\. \.\.} [glob -nocomplain -- * .*] {} folderContent	;# not operational system robust
				set folderContent [glob -nocomplain -- * .?*]
				set index [lsearch -exact $folderContent {..}]
				set folderContent [lreplace $folderContent $index $index]
# set xxx --$folderContent--
# Store xxx C:/tmp/bbb.txt auto 0 a
				if {$selectedFiles == ""} {
# there are no selected files
# web submitted files belong to this case
# Drop unsecure files
# security issue
					set flag 0
					set folderContent2 {}
					foreach file $folderContent {
#						if [regexp {.exe$|.php$} $file] #	;# commented by GJFB in 2024-05-11
						if [regexp {.exe$} $file] {	;# added by GJFB in 2024-05-11 - required to allow remote editing of .php file
							set flag 1
							continue
						}
						lappend folderContent2 $file
					}
					if $flag {
						set selectedFiles $folderContent2
					} else {
						set selectedFiles *
					}
# Drop unsecure files - end
				} else {
# there are selected files
					set folderContent2 $folderContent
				}
				if {$folderContent != ""} {
# non-empty source folder
#					set docPath $homePath/col/$repName/doc
# set xxx [list $document $docPath]
# Store xxx C:/tmp/bbb auto 0 a
# puts ${-documentpath}	;# => C:/Gerald/URLib 2/clipboard2/
# puts --$folderContent2--	;# => --index.zip--
# puts [list $document $destinationHomeDirectoryPath]	;# => {c:/gerald/urlib 2/clipboard2} {c:/gerald/urlib 2/col/iconet.com.br/banon/2003/03.14.19.34/doc}
#					if ![string equal $document $docPath] #
					if ![string equal $document $destinationHomeDirectoryPath] {
# $document and $docPath may be the same (see command UpdateRepository2 in CreatePDFFile called in Submit (ePrint) and ProcessReview)
# the document to deposit is not already in docPath
						if {[llength $folderContent2] > 1} {
# the folderContent2 has MORE than one file
# set xxx --$selectedFiles--
# Store xxx C:/tmp/bbb.txt auto 0 a
							foreach fileName $selectedFiles {
								if [catch {exec \
$zipPath -r \
$homePath/col/$URLibServiceRepository/auxdoc/.t$pid $fileName} error] {
#									puts $error	;# may produce: error writing "stdout": I/O error (when starting post in unix using putty.exe and without: at now + 1 minute)
									StoreLog {error} {DDRoutine (1)} $::errorInfo
								}
							}
#							set docPath $homePath/col/$repName/doc
							cd $destinationHomeDirectoryPath	;# change to destination
# DEPOSITE
# UNZIP
							if [catch {exec \
$unZipPath -o \
$col/$URLibServiceRepository/auxdoc/.t$pid} error] {
#								puts $error	;# may produce: error writing "stdout": I/O error (when starting post in unix using putty.exe and without: at now + 1 minute)
								StoreLog {error} {DDRoutine (2)} $::errorInfo
							}
							if {$tcl_platform(platform) == "unix"} {
								exec chgrp -R [lindex [exec ls -l $homePath/col/$URLibServiceRepository/doc/post] 3] .	;# e.g., urlib
							}
							file delete $homePath/col/$URLibServiceRepository/auxdoc/.t$pid
						} else {
# the folderContent2 has zero file or just ONE file
# more efficient coding
# folderName2
							set fileName [lindex $folderContent2 0] ;# folderContent2 is a list
							if [string equal {} ${-foldername}] {
								set folderName2 {}
							} else {
								file mkdir $destinationHomeDirectoryPath/${-foldername}
								set folderName2 ${-foldername}/
							}
# set xxx ${-unzip}
# Store xxx C:/tmp/aaa auto 0 a
# puts --${-unzip}--
# DEPOSITE
# destinationDirectoryPath - added by GJFB in 2010-12-05
							set destinationDirectoryPath $destinationHomeDirectoryPath/$folderName2

# Move to source
# added by GJFB in 2016-05-10
							if ${-movetosource} {
# move to source
# puts --$destinationHomeDirectoryPath--
# puts --$sourceHomeDirectoryPath--

if 0 {
# commented by GJFB in 2021-05-27
								cd $destinationHomeDirectoryPath	;# doc directory
								set docFolderContent [glob -nocomplain -- * .?*]
								set index [lsearch -exact $docFolderContent {..}]
								set docFolderContent [lreplace $docFolderContent $index $index]
								foreach fileName2 $docFolderContent {
									if ![regexp {^\.htaccess} $fileName2] {
										if [catch {file rename -force -- $destinationHomeDirectoryPath/$fileName2 $sourceHomeDirectoryPath/$fileName2} message] {	;# doc -> source
# catch possible error in order to execute the next step (cd), otherwise pwd becomes wrong
# nothing deposited
											StoreLog {error} {DDRoutine (5)} "nothing deposited\n$::errorInfo"
										}
									}
								}
} else {
# added by GJFB in 2021-05-27
								MoveBetweenDirectories $destinationHomeDirectoryPath $sourceHomeDirectoryPath	;# from doc to source
}
							}
# Move to source - end

# Move back to doc
# added by GJFB in 2021-05-27
							if ${-movebacktodoc} {
# move back to doc
								MoveBetweenDirectories $sourceHomeDirectoryPath $destinationHomeDirectoryPath	;# from source to doc
							}
# Move back to doc - end

							if ${-unzip} {
# UNPACK
# unzip the deposited document
#								set arquiveName [join [glob *]]	;# in /doc - e.g., [glob *] == {ce paper.zip} - [join [glob *]] == ce paper.zip
# puts [pwd]
#								set fileNameList [glob *]
								set fileNameList [glob ${-documentpath}*]
# puts --$fileNameList--
								set arquiveName [lindex [Grep {.zip$|.rar$} $fileNameList -nocase] 0]	;# takes the first						
# puts --$arquiveName--
# deposite the document in the destination directory
# puts --$destinationDirectoryPath--
								cd $destinationDirectoryPath	;# change to destination
								UnPack $arquiveName							
# deposite the document in the destination directory - end
								if {${-option} != "copy"} {
									file delete $arquiveName
								}
								unset arquiveName							
							} else {
# RENAME (is faster than copy)
# puts RENAME
# deposite the document in the destination directory
# puts ${-option}	;# => preserve
# puts "${-documentpath}$fileName $destinationDirectoryPath$fileName"	;# => C:/Gerald/URLib 2/clipboard2/044_96.pdf c:/gerald/urlib 2/col/iconet.com.br/banon/2003/03.14.19.34/doc/044_96.pdf
								if {${-option} == "copy"} {
# copy
# added by GJFB in 2012-06-26 - useful when adding (using the URLibService window) a new repository from one containing just one file (otherwise the source file is removed because of the rename command)
									if [catch {file copy -force -- ${-documentpath}$fileName $destinationDirectoryPath$fileName} message] {
# catch possible error in order to execute the next step (cd), otherwise pwd becomes wrong
# nothing deposited
										StoreLog {error} {DDRoutine (3)} "nothing deposited\n$::errorInfo"
									}
								} else {
									if ![string equal {} $fileName] {	;# added by GJFB in 2018-08-20 - filename is empty when submitting a .exe (or .php) file - in this case, file rename must not be executed otherwise it renames the clipboard2 directory which must not be removed
										if [catch {file rename -force -- ${-documentpath}$fileName $destinationDirectoryPath$fileName} message] {
# catch possible error in order to execute the next step (cd), otherwise pwd becomes wrong
# nothing deposited
											StoreLog {error} {DDRoutine (4)} "nothing deposited\n$::errorInfo"
										}
									}
								}
# deposite the document in the destination directory - end
								unset fileName
							}
						}
					}
					cd $pwd

# Post-submission processing
					ConditionalSet postSubmissionScriptRepList -postsubmissionscriptreplist {}
					ConditionalSet reference -reference {}
					set targetFile [RunPostSubmissionScript $repName $postSubmissionScriptRepList $reference]
# Post-submission processing - end

if [info exists oldTargetFile] {
	TraceProcedure [list oldTargetFile = $oldTargetFile]
} else {
	TraceProcedure [list oldTargetFile doesn't exist]
}

					if [string equal {} $targetFile] {
# puts --${-targetfile}--
						if {${-targetfile} == "enable"} {
# enable
							set docContent ""
							DirectoryContent docContent $docPath $docPath
							set i 0	;# added by GJFB in 2019-12-21 (like in AjustTargetFile)
							foreach file $docContent {
								if ![regexp -nocase {^\.htaccess2?$} $file] {
									incr i
									if {$i == 2} {break}
									set firstFile $file
								}
							}
#							if {[llength $docContent] == 1} #	;# commented by GJFB in 2019-12-21
							if {$i == 1} {	;# added by GJFB in 2019-12-21 to ignore the .htaccess files
#								set targetFile [join $docContent]
								set targetFile $firstFile
							} else {
								if [info exists oldTargetFile] {
									if {[lsearch -exact $docContent $oldTargetFile] != -1} {
										set targetFile $oldTargetFile
									} elseif {[TestContentType $repName {Mirror} $homePath]} {
										set targetFile mirror.cgi	;# preserve the target file (mirror.cgi)
									} else {
# Looking for the target file name
# example of target file: {*,*/*,*/*/*}.[pP][dD][fF]
# example of target file: {fullpaper,*/fullpaper,*/*/fullpaper}.pdf
# puts --$oldTargetFile--
										set fileNameList [glob -nocomplain $homePath/col/$repName/doc/$oldTargetFile]
# puts --$fileNameList--
										if {[llength $fileNameList] == 1} {
											regsub $homePath/col/$repName/doc/ $fileNameList {} targetFile	;# {edicoes.pdf}
											set targetFile [join $targetFile]	;# edicoes.pdf
										}
# puts --$targetFile--
# Looking for the target file name - end
									}
								}
							}
						} else {
# disable
## no target file
							if [info exists oldTargetFile] {
								set targetFile $oldTargetFile	;# added by GJFB in 2025-01-07 to preserve the old target file name - useful when compiling a .tex file in a Misc repository because the for such repository the targetFileOption is set to 'disable' in the default displayControl.tcl ('disable' means disable any change value of the target file name)
							}
						}
					}

					if {${-option} != "copy"} {
# delete the source folder content
						set fileList2 {}
						foreach fileName $folderContent {
							lappend fileList2 ./$fileName	;# ~WRD0000.tmp -> ./~WRD0000.tmp - added by GJFB in 2011-03-09, otherwise ~WRD0000.tmp is interpreted as a "~user" path
						}
						set cmd "file delete -force -- $fileList2"
						cd ${-documentpath}
						eval $cmd
						LogInsert [list [list Insert $log \
							end {document\
<$var1> moved into the repository <$var2>} {} $document $repName] \
							[list TagAdd $log fixed9 \
							{<$var1>} -forward $document] \
							[list TagAdd $log fixed9 \
							{<$var2>} -forward {} $repName]] 1 0
						LogInsert [list [list Insert $log insert {new line}]] 0 1
# delete - end
					} else {
						LogInsert [list [list Insert $log \
							end {document\
<$var1> copied into the repository <$var2>} {} $document $repName] \
							[list TagAdd $log fixed9 \
							{<$var1>} -forward $document] \
							[list TagAdd $log fixed9 \
							{<$var2>} -forward {} $repName]] 1 0
						LogInsert [list [list Insert $log insert {new line}]] 0 1
					}
				} else {
# empty source folder
# Move to source
# added by GJFB in 2021-05-25
					if ${-movetosource} {
# move to source
# same code as above
# puts --$destinationHomeDirectoryPath--
# => --c:/users/geral/urlib 2/col/urlib.net/www/2021/04.27.01.57/doc--
# puts --$sourceHomeDirectoryPath--
# => --c:/users/geral/urlib 2/col/urlib.net/www/2021/04.27.01.57/source--
if 0 {
# commented by GJFB in 2021-05-27
						cd $destinationHomeDirectoryPath	;# doc directory
						set docFolderContent [glob -nocomplain -- * .?*]
						set index [lsearch -exact $docFolderContent {..}]
						set docFolderContent [lreplace $docFolderContent $index $index]
						foreach fileName2 $docFolderContent {
							if ![regexp {^\.htaccess} $fileName2] {
								if [catch {file rename -force -- $destinationHomeDirectoryPath/$fileName2 $sourceHomeDirectoryPath/$fileName2} message] {	;# doc -> source
# catch possible error in order to execute the next step (cd), otherwise pwd becomes wrong
# nothing deposited
									StoreLog {error} {DDRoutine (5)} "nothing deposited\n$::errorInfo"
								}
							}
						}
} else {
# added by GJFB in 2021-05-27
						MoveBetweenDirectories $destinationHomeDirectoryPath $sourceHomeDirectoryPath	;# from doc to source
}
					}
# Move to source - end

# Move back to doc
# added by GJFB in 2021-05-27
							if ${-movebacktodoc} {
# move back to doc
# same code as above
								MoveBetweenDirectories $sourceHomeDirectoryPath $destinationHomeDirectoryPath	;# from source to doc
							}
# Move back to doc - end

					LogInsert [list [list Insert $log \
						end {document\
<$var1> deposited in the repository <$var2>} {} $document $repName] \
						[list TagAdd $log fixed9 \
						{<$var1>} -forward $document] \
						[list TagAdd $log fixed9 \
						{<$var2>} -forward {} $repName]] 1 0
					LogInsert [list [list Insert $log insert {new line}]] 0 1
				}
				cd $pwd
				if {${-option} == "delete"} {
# delete the folder
					file delete ${-documentpath}
					LogInsert [list [list Insert $log end \
						{document folder deleted\n}]]
# delete - end
				} else {
					if {${-option} != "copy"} {
						LogInsert [list [list Insert $log end \
							{document folder preserved\n}]]
					}
				}
			}
		} else {
# improper directory entry - retry
			Retry ${-documentpath}
			return 1
		}
	}
###
# set xxx [CallTrace]
# Store xxx C:/tmp/bbb auto 0 a
# Store -fileinfo C:/tmp/bbb auto 0 a
	if !$test {

		if {[info exists targetFile] && $targetFile != ""} {
			LogInsert [list [list Insert $log end \
				{<$var1> selected as target file} \
				{} $targetFile] \
				[list TagAdd $log fixed9 \
				{<$var1>} -forward $targetFile]] 1 0
			LogInsert [list [list Insert $log insert {new line}]] 0 1
		} else {
#			LogInsert [list [list Insert $log end \
				{target file not defined\n}]]
		}

# Create history
# CREATE A NEW VERSION STAMP
		set docPath $homePath/col/$repName/doc
		ConditionalSet userName -username {}
		set versionStamp [CreateVersionStamp [DirectoryMTime $docPath] $userName]
# history
		Eval UpdateHistory $repName $versionStamp
# Create history - end
# Set target file name
# puts OK1
		if {[info exists targetFile] && $targetFile != ""} {
# puts $targetFile
			Set repositoryProperties($repName,targetfile) $targetFile
# Create service/targetFile
			Store targetFile $col/$repName/service/targetFile
# set xxx --$targetFile--
# Store xxx C:/tmp/bbb auto 0 a
# puts stored
# Create service/targetFile - end
		}
# puts OK2
# Set target file name - end
# Create service/hostCollection
		StoreHostCollection $repName $loCoInRep
		Set repositoryProperties($repName,hostcollection) $loCoInRep
# Create service/hostCollection - end
# Create service/transferableFlag
#		set transferableFlag 1
		if {([info exists loCoInRep] && [string equal $loCoInRep $repName]) || \
		([info exists loBiMiRep] && [string equal $loBiMiRep $repName])} {
			set transferableFlag 0
		} else {
			set transferableFlag 1
		}
		StoreService transferableFlag $repName transferableFlag 1 1
# Create service/transferableFlag - end
# Create service/type
		if ![string equal {} ${-contenttype}] {
			set contentType ${-contenttype}
			Store contentType $homePath/col/$repName/service/type
			Set repositoryProperties($repName,type) $contentType
		}
# Create service/type - end
# Create service/size and service/numberOfFiles
#		set size [ComputeSize $repName]
		if ${-fileinfo} {
			foreach {size numberOfFiles} [ComputeInfo $repName] {break}
#			if ![string equal {0 Kbyte} $size] #
			if ![string equal {0 KiB} $size] {
				Store size $homePath/col/$repName/service/size
				Set repositoryProperties($repName,size) $size
			}
			if ![string equal {0} $numberOfFiles] {
				Store numberOfFiles $homePath/col/$repName/service/numberOfFiles
				Set repositoryProperties($repName,numberoffiles) $numberOfFiles
			}
		}
# Create service/size and service/numberOfFiles - end

# set xxx [CallTrace]
# Store xxx C:/tmp/bbb.txt auto 0 a
# Tcl Call Trace
# 4: DDRoutine { -targetfile enable -documenttype directory -repositorytype repository -option preserve -reverse 0 -documentpath {C:/Gerald/URLib 2/clipboard2/} -repositoryentry {:: iconet.com.br/banon/2009/06.16.21.10} -unzip 0 -selectedfiles no -username banon -postsubmissionscriptreplist {} -reference {} -deletedoccontentbeforeupdate 0 -copytosource 0 -foldername }
# 3: UpdateRepository iconet.com.br/banon/2009/06.16.21.10 directory {C:/Gerald/URLib 2/clipboard2/} enable preserve 0 banon {} {} 0 0 {}
# 2: UpdateRepMetadataRep iconet.com.br/banon/2009/06.16.21.10 iconet.com.br/banon/2009/06.16.21.10.51 banon 33 preserve 0 0 {} 1 {deny from all and allow from 150.163} banon {} enable {} {} {} 0 Portuguese 0 0 {}
# 1: ServeLocalCollection sock376 127.0.0.1 1129
# Tcl Call Trace - end

# Create service/identifier
if 0 {
# now in MakeRepository - done by GJFB in 2010-07-31
		if {${-repositorytype} == "new"} {
			if {[string equal $devLoCoInRep $loCoInRep] || [regexp {/.*@.*/.*/} $repName]} {
# developing collection or not a standalone mode
# puts $serverAddressWithIP
				foreach {ip urlibPort} [ReturnCommunicationAddress $serverAddressWithIP] {break}
				set dateTime [eval file join [lrange [file split $repName] 2 3]]
				set id [ConvertToCaseInsensitiveIdentifier $ip $urlibPort $dateTime]
				StoreService id $repName identifier 1 1
			}
		}
}
# Create service/identifier - end
		return $repName
	}
####
	if $test {return 0}	;# no problem
}

# DDRoutine - end
# ----------------------------------------------------------------------
# Retry

proc Retry {var} {
# runs with start and post
	global applicationName
	if {$applicationName == "post"} {return}
	if [regexp -nocase {^[c-z]:/$|^/$} $var] {
# cannot deposit the all disk
		Dialog OK disabled -1 DD {all disk}
		return
	}
	if [regexp "^\[ \t]*$" $var] {
# empty entry - retry
		Dialog OK disabled -1 DD {empty entry}
	} else {
# not a directory - retry
		Dialog OK disabled -1 DD {not a directory} $var
	}
}

# Retry - end
# ----------------------------------------------------------------------
# MakeRepository
# Makes a repository
# used in DDRoutine only
# makeDirectories values are 0 or 1;
# if makeDirectories is 0 then no directories are made (used only when testing - see below)
# if repName is not empty then MakeRepository just makes some directories (depending on makeauxdoc, makesource and makeDirectories)

proc MakeRepository {repName makeauxdoc makesource {makeDirectories 1}} {
# runs with start and post
	global col
	global pwd
	global homePath
	global loCoInRep	;# set first (at installation) in this procedure and then in LoadGlobalVariables
#	global loCoInMetadataRep	;# set in StartService
#	global loBiMiRep	;# set in StartService
	global loBiMiMetadataRep	;# set in StartService
	global serverAddressWithIP
	global installInitialCollection	;# set in start and post
#	global staticIPFlag	;# set in InformURLibSystem at post - added by GJFB in 2014-09-09
	global environmentArray	;# added by GJFB in 2017-04-28
	global applicationName
	global URLibServiceRepository
	global registrationKey	;# set in StartService

# puts [CallTrace]
# =>
# call stack
# 6: MakeRepository {} 1 1
# 5: DDRoutine { -targetfile enable -documenttype directory -repositorytype new -option copy -reverse 0 -documentpath {C:/Users/geral/URLib 2/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/} -unzip 0 -fileinfo 0 -contenttype {} -copytosource 0 -username {} -postsubmissionscriptreplist {} -reference {}} 0 {}
# 4: CreateNewRepository directory {C:/Users/geral/URLib 2/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/} enable copy 0 {} 0 {} 0 {}
# 3: CreateRepMetadataRep directory {C:/Users/geral/URLib 2/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/} {} 0 enable {} copy
# 2: DDOK .window.main.dd 0
# 1: OK dd
# call stack - end
# call stack
# 6: MakeRepository {} 0 0
# 5: DDRoutine { -documenttype directory -repositorytype new -option preserve -reverse 0 -documentpath {C:/Users/geral/URLib 2/clipboard/} -makeauxdoc 0 -makesource 0 -fileinfo 0 -username } 0 {}
# 4: LoadMetadata {%0 Computer Program
# %4 urlib.net/www/2021/06.19.18.42
# %3 mirrorHomePage.html
# %A URLib Librarian,
# %T Default mirror home page
# %I Deposited in the URLib collection.
# %K displayControl.
# %1 Any computer running TclTk} {} {} 1 enable
# 3: CreateRepMetadataRep directory {C:/Users/geral/URLib 2/col/dpi.inpe.br/banon/2000/01.23.20.24/doc/} {} 0 enable {} copy
# 2: DDOK .window.main.dd 0
# 1: OK dd
# call stack - end

	if {![info exists applicationName] || $applicationName == "start"} {
		source $homePath/col/$URLibServiceRepository/auxdoc/.environmentArray.tcl	;# set environmentArray(staticIPFlag)
#		set staticIPFlag $environmentArray(staticIPFlag)	;# set in InformURLibSystem at post - commeted by GJFB in 2017-04-28
	}
	
if 1 {
# used when urlib.net is running
	if [string equal {} $repName] {
#		if [info exists loBiMiMetadataRep] #	;# commented by GJFB in 2020-05-27
## loBiMiMetadataRep exists
		if [info exists loCoInRep] {	;# added by GJFB in 2020-05-27
# loCoInRep exists
			set loCoInRep2 $loCoInRep
			if [LoadService $loCoInRep registrationPassword registrationPassword 1 1] {
# corrupted password
				error [StoreLog {alert} {MakeRepository (1)} "$loCoInRep has a corrupted registration password"]
			}
		} else {
## loBiMiMetadataRep doesn't exist - installation
# loCoInRep doesn't exist - installation
			set loCoInRep2 {}
#			set registrationPassword {}
			set registrationPassword $registrationKey
		}

#		if $staticIPFlag #	;# commented by GJFB in 2017-04-28 - if urlib.net was down when running post, staticIPFlag is empty
# environmentArray(staticIPFlag) may be empty, then the if below produces an error (empty expression) resulting in the warning message: "Submission NOT completed..."
		if $environmentArray(staticIPFlag) {	;# added by GJFB in 2017-04-28 to overcome the problem of staticIPFlag being empty when urlib.net is down (see InformURLibSystem)
			set serviceAddress $serverAddressWithIP
		} else {
# dynamic IP - use a service with static IP
			set serviceAddress urlib.net:80
		}

# CREATEIBI		
		if [catch {Execute $serviceAddress [list CreateIBI $loCoInRep2 $registrationPassword] 0} m] {
# couldn't open socket: connection refused
# error writing "sock1884": connection refused
# error writing "sock240": socket is not connected
			global errorInfo
			error [StoreLog {alert} {MakeRepository (2)} $errorInfo"]
		} else {
			if [string equal {} $m] {
				error [StoreLog {alert} {MakeRepository (3)} "CreateIBI returns empty while executing: [list CreateIBI $loCoInRep2 $registrationPassword]"]
			}
			foreach {repName id} $m {break}
		}		
	}
} else {
# used when urlib.net is NOT running
# urlib.net/www/2017/11.02.15.45
# ConvertFromCaseInsensitiveIdentifier J8LNKB5R7W/3PTLMQ2
# => 150.163.34.64 800 2017/11.02.15.45
#
# urlib.net/www/2017/11.11.23.46
# ConvertToCaseInsensitiveIdentifier 150.163.34.64 800 2017/11.11.23.46
# => J8LNKB5R7W/3Q27M3S
	set makeRepository 0; after 1000 {set makeRepository 1}; vwait makeRepository
	set time [clock format [clock seconds] -format %Y/%m.%d.%H.%M.%S -gmt 1]
	set repName urlib.net/www/$time
	set id [ConvertToCaseInsensitiveIdentifier 150.163.34.64 800 $time]
}
# set xxx [list $makeDirectories $makesource]
# Store xxx C:/tmp/aaa auto 0 a
	cd $col
	if $makeDirectories {
		if $makeauxdoc {file mkdir $repName/auxdoc}
		if $makesource {file mkdir $repName/source}
		file mkdir $repName/doc
		file mkdir $repName/service
		if [info exists id] {
			StoreService id $repName identifier 1 1
		}
	}
	cd $pwd
# SET loCoInRep
	if ![info exists loCoInRep] {set loCoInRep $repName}	;# loCoInRep is the first repository to be created
	return $repName
}

if 0 {
	set environmentArray(spMailEntry) banon@iconet.com.br
	set environmentArray(domainName) iconet.com.br
	set environmentArray(hostName) banon-pc
	set environmentArray(spPortEntry) 1905
	set col ../../../../..
	set pwd C:/usuario/gerald/URLib/col/dpi.inpe.br/banon/1998/08.02.08.56/doc
	puts [MakeRepository {} 0 0 0]
}

# MakeRepository - end
# ----------------------------------------------------------------------
# CreateIBI
# creates IBIp
# used only remotely
# remoteLoCoInRep and localCollectionPassword are used to identify the client
# remoteLoCoInRep is loCoInRep name of the local collection requiring an IBI
# localCollectionPassword is the local collection password stored in service/registrationPassword of loCoInRep of the local collection requiring an IBI
# lastRepTime value is the time of creation of the last repository
# examples: 
# 1945/05.20.11.45
# 2010/07.20.01.14.50
# returns repName and id

proc CreateIBI {remoteLoCoInRep localCollectionPassword} {
# runs with post
	global col
	global environmentArray
	global createIBIOn	;# set in this procedure and used (only) in this procedure at the next call
	global lastRepTime	;# set in this procedure and used (only) in this procedure at the next call
	global lastRepTimeInFractionOfSecond	;# set in this procedure and used (only) in this procedure at the next call
	global installInitialCollection	;# set by post
#	global localCollectionPasswordArray ;# commented by GJFB in 2020-05-23
	global loCoInRep
	global loBiMiRep
	global serverAddressWithIP	;# set by post
	global temporalResolution	;# set in LoadGlobalVariables and used in this procedure

if 0 {
# commented by GJFB in 2020-05-23
#	if !$installInitialCollection #	;# commented by GJFB in 2017-12-26
	if {!$installInitialCollection && ![string equal $loCoInRep $remoteLoCoInRep]} {	;# added by GJFB in 2017-12-26 - to simplify installation
# not installation and the client local collection is not the current local collection (i.e., the current local collection is urlib.net)
		if {![info exists localCollectionPasswordArray] && \
		([file exists $col/$loBiMiRep/auxdoc/localCollectionPasswordArray.tcl] || \
		[file exists $col/$loBiMiRep/auxdoc/localCollectionPasswordArrayBackup.tcl])} {
			SourceWithBackup $col/$loBiMiRep/auxdoc/localCollectionPasswordArray.tcl localCollectionPasswordArray	;# set localCollectionPasswordArray
		}
		if ![info exists localCollectionPasswordArray($remoteLoCoInRep)] {return}	;# do nothing - unfair request - unknown local collection
		if ![string equal $localCollectionPassword $localCollectionPasswordArray($remoteLoCoInRep)] {return}	;# do nothing - unfair request - wrong registration key
	}
} else {
# added by GJFB in 2020-05-23 - localCollectionPasswordArray.tcl might have been changed manually (when installing a new local collection) and localCollectionPasswordArray must be up-to-date
	if ![string equal $loCoInRep $remoteLoCoInRep] {
# the client local collection is not the current local collection (i.e., the current local collection is urlib.net)
		SourceWithBackup $col/$loBiMiRep/auxdoc/localCollectionPasswordArray.tcl localCollectionPasswordArray 1	;# set localCollectionPasswordArray
# localCollectionPasswordArray: loCoInRep |-> localCollectionPassword
# example: set localCollectionPasswordArray(dpi.inpe.br/banon/1999/01.09.22.14) 896322016416
# localCollectionPasswordArray must contain the local collection password of all the created local collection
#		if ![info exists localCollectionPasswordArray($remoteLoCoInRep)] {return}	;# commented by GJFB in 2020-05-27
		if ![info exists localCollectionPasswordArray($remoteLoCoInRep)] {	;# added by GJFB in 2020-05-27 to update localCollectionPasswordArray.tcl at initial collection installation
			if {[info exists localCollectionPasswordArray()] && [string equal $localCollectionPassword $localCollectionPasswordArray()]} {
# initial collection installation - localCollectionPasswordArray must be updated
				unset localCollectionPasswordArray()
				set localCollectionPasswordArray($remoteLoCoInRep) $localCollectionPassword
				StoreArrayWithBackup localCollectionPasswordArray $col/$loBiMiRep/auxdoc/localCollectionPasswordArray.tcl w list array 1
			} else {
				return	;# do nothing - unfair request - unknown local collection
			}
		}
		if ![string equal $localCollectionPassword $localCollectionPasswordArray($remoteLoCoInRep)] {return}	;# do nothing - unfair request - wrong registration key
	}
}

# Waiting room
	global createIBI
	while {[info exists createIBIOn]} {
		set createIBI 0; after 100 {set createIBI 1}; vwait createIBI
	}
# Waiting room - end

	set createIBIOn 1	;# could be anything

	if {[info tclversion] > 8.4} {
# new code - added by GJFB in 2011-05-01
# entier works with unlimited integer range - added by GJFB in 2011-04-23
# lastRepTimeInFractionOfSecond
#		set currentTimeInFractionOfSecond [expr (entier([clock microseconds] / 1000000. / $temporalResolution)) / (1 / $temporalResolution)]
# same code as in post
		set currentTimeInFractionOfSecond [expr [clock microseconds] / 1000000.]	;# ct - ex: 1337778731.322527
		if ![info exists lastRepTimeInFractionOfSecond] {
			Load ../auxdoc/lastRepTimeInFractionOfSecond lastRepTimeInFractionOfSecond
			if [string equal {} $lastRepTimeInFractionOfSecond] {
				set lastRepTimeInFractionOfSecond [expr (entier($currentTimeInFractionOfSecond / $temporalResolution)) / (1 / $temporalResolution) - $temporalResolution]	;# [i] = 1, lrt == rct - 1, therefore s == nrt == rnrt == rct - ex: 1337778730.0
			}
		}
# CREATESUFFIX
		foreach {lastRepTimeInFractionOfSecond suffix} [CreateSuffix $currentTimeInFractionOfSecond $lastRepTimeInFractionOfSecond $temporalResolution] {break}
		Store lastRepTimeInFractionOfSecond ../auxdoc/lastRepTimeInFractionOfSecond
		set currentTime $suffix
	} else {
# old code - still in use
# lastRepTime
		if ![info exists lastRepTime] {
			Load ../auxdoc/lastRepTime lastRepTime
			if [string equal {} $lastRepTime] {
				set lastRepTime [clock format [clock seconds] -format %Y/%m.%d.%H.%M.%S -gmt 1]
			}
		}
# currentTime	
		set currentTime [clock format [clock seconds] -format %Y/%m.%d.%H.%M -gmt 1]
		while {[string compare $lastRepTime $currentTime] != -1} {
# the above compare will work up to year 9999 - comment added by GJFB in 2010-09-19
# lastRepTime >= currentTime
# while is needed because of a possible computer clock small ajustment (that is, a newer repository may exist)
			after 100	;# 0.1 second delay
			set currentTime [clock format [clock seconds] -format %Y/%m.%d.%H.%M.%S -gmt 1]
			if [regexp {00$} $currentTime] {
# wait for one more second - second must not be 00 since the second value can be omitted
				after 1000	;# 1 second delay
				set currentTime [clock format [clock seconds] -format %Y/%m.%d.%H.%M.%S -gmt 1]
			}
		}
		set lastRepTime $currentTime
		Store lastRepTime ../auxdoc/lastRepTime
	}

# environmentArray(spPortEntry) == {banon-pc3 800}
	if [regexp {(.*) +(.*)} $environmentArray(spPortEntry) m hostName urlibPortNumber] {
		regsub {.$} $urlibPortNumber {} httpPortNumber	;# drop the last digit
	} else {
# old usage
		set hostName $environmentArray(hostName)
		set httpPortNumber $environmentArray(spPortEntry)
	}
#	set user $hostName@$httpPortNumber	;# could be @ ; , from the e-mail address syntax point of view - could not be , because of referenceTable (see GetCitedRepositoryList)
# >>> here it is assumed that the complete host name without domain doesn't contain any periods (.)
	if [regexp {\.} $hostName] {
# host name is already a full server name, e.g., www.urlib.net banon-pc2.dpi.inpe.br
		regexp {^(.*?)\.(.*)$} $hostName m hostName domainName	;# www urlib.net
	} else {
		set domainName $environmentArray(domainName)
	}
	if {$httpPortNumber == 80} {
		set user $hostName	;# now without port 80 - change by GJFB in 2010-08-05
	} else {
		set user $hostName.$httpPortNumber	;# now using . instead of @ - change by GJFB in 2010-08-05 - because a name with @ is recognized as an e-mail address by most of software
	}
	
# repName
	set repName $domainName/$user/$currentTime
# id			
	foreach {ip urlibPort} [ReturnCommunicationAddress $serverAddressWithIP] {break}
	set dateTime [eval file join [lrange [file split $repName] 2 3]]	;# e.g., 2008/07.28.13.00
	set id [ConvertToCaseInsensitiveIdentifier $ip $urlibPort $dateTime]
	
	unset createIBIOn
	
	return [list $repName $id]
}

# port value depends whether the computer uses static or dynamic IP
# if it uses static IP, the port value should be the port used by the resource
# that is requesting IBIs - for example, when using URLibService, common port values
# are 800, 802 and 19050, nevertheless, it is possible, without losing the identification
# property, to drop the trailing 0, i.e., using here 80, 802 and 1905.
# if it uses dynamic IP, the port value must be empty
# example of created IBI (using port 80): 150.163/2.174/2010/07.20.01.23
# example of created IBI (using port 1905): 150.163/2.174/2010/07.20.01.23-1905
# example of created IBI (using dynamic IP): 187.2/131.154/2010/07.20.01.23-2667

# not used because two clients with dynamic IP from the same domain
# may each request an IBI to two different unsyncrhonized servers
# (reuse of client port may be a problem in this case)

proc CreateIBI2 {lastRepTime {port {}}} {
# runs with post
	upvar clientAddress clientAddress

	if ![regexp {^\d{4,}/\d{2}\.\d{2}\.\d{2}\.\d{2}(\.\d{2}|$)} $lastRepTime] {
# unexpected lastRepTime
		return
	}

# ip port2
	foreach {ip port2} $clientAddress {break}
# ip1 ip2
	regexp {(\d+\.\d+)\.(\d+\.\d+)} $ip m ip1 ip2

# currentTime	
	set currentTime [clock format [clock seconds] -format %Y/%m.%d.%H.%M -gmt 1]
	while {[string compare $lastRepTime $currentTime] != -1} {
# lastRepTime >= currentTime
# while is needed because of a possible computer clock small ajustment (that is, a newer repository may exist)
		after 100	;# 0.1 second delay
		set currentTime [clock format [clock seconds] -format %Y/%m.%d.%H.%M.%S -gmt 1]
		if [regexp {00$} $currentTime] {
# wait for one more second - second must not be 00 since the second value can be omitted
			after 1000	;# 1 second delay
			set currentTime [clock format [clock seconds] -format %Y/%m.%d.%H.%M.%S -gmt 1]
		}
	}

	if [string equal {} $port] {
		set repName $ip1/$ip2/$currentTime-$port2
	} elseif {$port == 80} {
# 80
		set repName $ip1/$ip2/$currentTime
	} else {
		set repName $ip1/$ip2/$currentTime-$port
	}

	return $repName
}

# CreateIBI - end
# ----------------------------------------------------------------------
# CreateSuffix
# is an implementation of Algorithm 4 presented in http://urlib.net/LK47B6W/362SFKH (p. 24)
# temporalResolution (temporal granularity) value is 60 or 1 or 0.1 or 0.01 or ... 0.000001
# 60 means the resolution is at most minute
# 1 means the resolution is at most second
# 0.1, 0.01, ..., 0.000001 define the resolution in terms of the maximum number of digits used in the decimal fraction of second
# returns shorterNewRepTime and suffix

# >>> newRepTimeInFractionOfSecond (nrt)
# lrt == rct - 1                             if [i] = 1
# lrt == last repository time (t(][i] - 1[)) if [i] > 1
# ct == current time (t_i)
# rct == round-off current time
# nrt == new repository time (t'_i) = max(lrt+1, rct) (==> lrt < nrt)
# unit is $temporalResolution
# 
#                            +
#              <-------------------------->
# |------------|------|-------------------|-------
# 1                   2                   3
#               ct    lrt                 lrt+1
# rct
#                                         nrt
# 
#                                   +
#                             <----------->
# |-------------------|-------|-----------|-------
# 1                   2                   3
#                     lrt      ct         lrt+1
#                     rct
#                                         nrt
# 
# [i] = 1:
#                                              -
#                                         <---------->
# |-------------------|-------------------|----------|--
# 1                   2                   3
#                     lrt                 lrt+1      ct
#                                         rct
#                                         nrt
# 
#                                                                  -
#                                                             <---------->
# |-------------------|-------------------|-------------------|----------|--
# 1                   2                   3                   4
#                     lrt                 lrt+1                          ct
#                                                             rct
#                                                             nrt
# >>> suffix (s)
# rnrt == round-off nrt (up to minute)
# s == suffix
# s = rnrt if rnrt - lrt > 0 (lrt < rnrt)
# s = nrt if rnrt - lrt <= 0
# unit is minute or second or fraction of second
# 
# [i] = 1:
#          +
# <------------------->
# |-------------------|-------------------|-------
# 1                   2                   3
# lrt                 nrt
#                     rnrt
#                     s
# 
# [i] > 1:
#   -
# <---->
# |----|-------|------|-------------------|-------
# 1                   2                   3
#      lrt     nrt
# rnrt
#              s
# 
#                 +
#              <------> 
# |------------|------|-------|-----------|-------
# 1                   2                   3
#              lrt            nrt
#                     rnrt
#                     s
# 
#                           +
#              <--------------------------> 
# |------------|------|-------------------|-----|--
# 1                   2                   3
#              lrt                              nrt
#                                         rnrt
#                                         s

proc CreateSuffix {
	currentTimeInFractionOfSecond lastRepTimeInFractionOfSecond temporalResolution
} {
# puts [list $currentTimeInFractionOfSecond $lastRepTimeInFractionOfSecond]
# expr 1304257193.722 + 0.001
# => 1304257193.7229998
# hence, format must be used

# same code as in post
	set roundOffCurrentTimeInFractionOfSecond [expr (entier($currentTimeInFractionOfSecond / $temporalResolution)) / (1 / $temporalResolution)]
	set lastRepTimeInFractionOfSecond [expr (entier($lastRepTimeInFractionOfSecond / $temporalResolution)) / (1 / $temporalResolution)]	;# useful because temporalResolution may have changed and its value increased (e.g., from 0.001 to 0.1)
	set numberOfFractionalDigits [expr int(log10(1 / $temporalResolution))]
# MAX
	set newRepTimeInFractionOfSecond [Max [format %.${numberOfFractionalDigits}f [expr $lastRepTimeInFractionOfSecond + $temporalResolution]] $roundOffCurrentTimeInFractionOfSecond]	;# t'
# puts $newRepTimeInFractionOfSecond	;# t'
	set delay [expr $newRepTimeInFractionOfSecond - $currentTimeInFractionOfSecond]
	set delayInMillisecond [expr entier($delay * 1000)]
# AFTER
# guarantees that the newRepTimeInFractionOfSecond will be the time of the IBI creation - unposting will occur after the last newRepTimeInFractionOfSecond
#	if {$delayInMillisecond > 0} {after $delayInMillisecond}	;# commented by GJFB in 2011-08-20 - does not respond to events
	if {$delayInMillisecond > 0} {
		set clicks [clock clicks]
		global x$clicks
		if [info exists x$clicks] {unset x$clicks}
		after $delayInMillisecond "set x$clicks 1"
		vwait x$clicks
		unset x$clicks	;# free memory
	}
	set shorterNewRepTime $newRepTimeInFractionOfSecond
	set s $temporalResolution
	while {$lastRepTimeInFractionOfSecond < $shorterNewRepTime} {
# puts $s
		set s [expr $s * 10]
		if {$s == 10} {set s 60.}	;# for minute
		set timeInFractionOfSecond $shorterNewRepTime
		if {$s > 60} {break}
		set shorterNewRepTime [expr double(entier($newRepTimeInFractionOfSecond / $s)) / (1 / $s)]
	}
	if ![regexp {^(.*)(\.)(.*)$} $timeInFractionOfSecond m seconds period fractionOfSecond] {
		set seconds $timeInFractionOfSecond; set fractionOfSecond 0
	}
	set suffix [clock format $seconds -format %Y/%m.%d.%H.%M.%S -gmt 1]
	if {$fractionOfSecond == 0} {
# expr double(entier(123.0056 * 100)) / 100 returns 123.0
		regsub {\.00$} $suffix {} suffix
	} else {
		set suffix $suffix.$fractionOfSecond
	}
	
	return [list $timeInFractionOfSecond $suffix]
}

# testing AFTER
if 0 {
	source utilities1.tcl
	source DDDialog.tcl
	set currentTimeInFractionOfSecond 1303488251.784811
	set lastRepTimeInFractionOfSecond 1303488254.7838
	set resolution 1.
	
	CreateSuffix $currentTimeInFractionOfSecond $lastRepTimeInFractionOfSecond $resolution
}

# CreateSuffix - end
# ----------------------------------------------------------------------
# GetRepName
# Gets the repository name (if any) specified in the dd(result2)
# Example:
# GetRepName .window.main.dd.dir.h1.h2.v2.entry ddDirectory .dir. \
# dd(result1) 

proc GetRepName {widget entryName type varName} {
	global dd
	global homePath
	global dd.dirPostMenu
	global ddChoice2
	if ${dd.dirPostMenu} {return}	;# the button2.2.menu is posted, don't get the rep Name
# rep
	if ![regexp {^(.*/.*/.*/.*) .*} $dd(result2) m rep] {
		regexp {^.* (.*/.*/.*/.*)} $dd(result2) m rep
	}
	if ![info exists rep] {return}
	if [string equal $ddChoice2 new] {return}
	set string $homePath/col/$rep/doc/ 
	UpdateEntry $widget $entryName $type $string $varName {}
}

# GetRepName
# ----------------------------------------------------------------------
# RunPostSubmissionScript
# returns the target file name specified within the last script
# Examples of repositories containing post submission scripts:
# iconet.com.br/banon/2005/12.29.23.16 (A script to process the INPE Clippings)
# iconet.com.br/banon/2005/09.07.19.12 (A script to process the INPE CRI-Clippings)

proc RunPostSubmissionScript {repName postSubmissionScriptRepList reference} {
	global homePath
	set targetFile {}
	foreach rep $postSubmissionScriptRepList {
		if ![file isdirectory $homePath/col/$rep] {continue}
#		source $homePath/col/$rep/doc/script.tcl	;# for testing Script
		if {[string compare {} [info commands ${rep}::Script]] == 0} {source $homePath/col/$rep/doc/script.tcl}
# EXECUTE
# puts >>>execute
		set targetFile [${rep}::Script $repName $reference]
	}
	return $targetFile
}

# RunPostSubmissionScript - end
# ----------------------------------------------------------------------
# UnPack
# unpacks arquiveName in the current directory
# used by DDRoutine only

proc UnPack {arquiveName} {
	global unZipPath
	global unRarPath
	global tcl_platform
	
	set fileExtension [file extension $arquiveName]
	if {[string equal -nocase {.zip} $fileExtension]} {
# zip file
# puts OK
# -o is for overwriting (needed when -deletedoccontentbeforeupdate is 0)
# -P xxx is for skipping encrypted file in zip (unless the password was xxx)
# UNZIP
# security issue - drop unsecure files
		if [string equal {} $unZipPath] {
#			puts {UnPack: unzip not found}	;# may produce: error writing "stdout": I/O error (when starting post in unix using putty.exe and without: at now + 1 minute)
			StoreLog {alert} {UnPack} {unzip not found}
		} else {
#			if [catch {exec $unZipPath -o -P xxx $arquiveName -x *.php *.exe} error] #	;# commented by GJFB in 2024-05-11
			if [catch {exec $unZipPath -o -P xxx $arquiveName -x *.exe} error] {	;# added by GJFB in 2024-05-11 - required to allow remote editing of .php file
#				puts "UnPack: $error"	;# may produce: error writing "stdout": I/O error (when starting post in unix using putty.exe and without: at now + 1 minute)
				StoreLog {alert} {UnPack} $error
			}
		}
	} elseif {[string equal -nocase {.rar} $fileExtension]} {
# rar file
# UNRAR
		if [string equal {} $unRarPath] {
#			puts {UnPack: unrar not found}	;# may produce: error writing "stdout": I/O error (when starting post in unix using putty.exe and without: at now + 1 minute)
			StoreLog {alert} {UnPack} {unrar not found}
		} else {
#			if [catch {exec $unRarPath e $arquiveName -x@'*.php,*.exe'} error] #	;# commented by GJFB in 2024-05-11
			if [catch {exec $unRarPath e $arquiveName -x@'*.exe'} error] {	;# added by GJFB in 2024-05-11 - required to allow remote editing of .php file
#				puts "UnPack: $error"	;# may produce: error writing "stdout": I/O error (when starting post in unix using putty.exe and without: at now + 1 minute)
				StoreLog {alert} {UnPack} $error
			}
		}

	}
	if {$tcl_platform(platform) == "unix"} {
# permissions of stored directories are restored under Unix and they might be inadequate
		exec chmod -R g+r .
		exec chmod -R o+r .
		exec chmod -R g+w .
	}
}

# UnPack - end
# ----------------------------------------------------------------------
# MoveBetweenDirectories
# added by GJFB in 2021-05-27
# used in DDRoutine only
# examples:
# MoveBetweenDirectories $destinationHomeDirectoryPath $sourceHomeDirectoryPath	;# from doc to source
# MoveBetweenDirectories $sourceHomeDirectoryPath $destinationHomeDirectoryPath	;# from source to doc

proc MoveBetweenDirectories {from to} {
	cd $from	;# doc directory
	set docFolderContent [glob -nocomplain -- * .?*]
	set index [lsearch -exact $docFolderContent {..}]
	set docFolderContent [lreplace $docFolderContent $index $index]
	foreach fileName2 $docFolderContent {
		if ![regexp {^\.htaccess} $fileName2] {
			if [catch {file rename -force -- $from/$fileName2 $to/$fileName2} message] {	;# from -> to
# catch possible error in order to execute the next step (cd), otherwise pwd becomes wrong
# nothing moved
				StoreLog {error} {MoveBetweenDirectories} "nothing moved\n$::errorInfo"
			}
		}
	}
}

# MoveBetweenDirectories - end
# ----------------------------------------------------------------------
