<SCRIPT LANGUAGE="VBScript" RUNAT="Server">

'########################
Sub Application_OnStart
'########################
On Error resume next
Application.Lock
'############################################################################################
' This section contains important LP settings. You can edit them to fit your needs.
' Lines with an apostophe ( ' ) in front of them are commented out and therefore inactive. Uncomment them if necessary.
' The script uses Zip and Image ActiveX controls (regsrv32 the included DLL and OCX controls)
'############################################################################################

'############################################################################################
'### System settings
'############################################################################################
'### General
'Application("Debugging")=True '### If true: All error messages will be shown and script processing is stopped when an error occurs (Normally debugging should be disabled)
Application("DBConnection")="DBQ=" & server.mappath("database/listpics.mdb") & ";Driver={Microsoft Access Driver (*.mdb)}" '### Database connection string.
'Application("DBConnection")="DSN=LP"
'Application("IsAccessDatabase")=True '### True if the Database is MS Access? Empty=auto-detect. (Needed for different DateDif handling in AutoMaintenance) 
Application("Language")="English.dat" '### Default language file to use
Application("GlobalAdminPass")="" '### Global admin password list (separate multiple entries with a comma). Note: only to gain access to and reset settings of folders (not used for image access validation).
Application("DefaultAdminSettings")="1111000011011111111111111111111111101010000" '### Settingsmask for admins (if defined it overrides all folder settings)
Application("DefaultSettings")="1111000011011011111101110000011111001010000" '### Default settingsmask for new rootfolder
Application("ShowInitDBLink")=True '### Show a link to initialize (clear) the entire database. Accessible to any admin!
Application("ShowDBCompactLink")=True '### Show a link to compact the database for admins (folder config view)
Application("AutoRebuild")=True '### Perform database cleanup automatically on each folder listing (delete non-existing items from DB and add new objects). You will have to visit each folder at least once to get the thumbs created properly.
Application("ShowRebuildProgress")=True '### Show rebuild progress for regular users (non-forced rebuild)
Application("ScriptTimeOut")=120 '### Set default script timeout in s
Application("LongScriptTimeOut")=3600 '### Script timeout used when rebuilding the database and Lowres images and uploading (may take very long for large listings)
Application("ValidImageTypes")="BMP,TIF,TIFF,GIF,JPG,JPEG,J2K,JP2,PNG,PCX,TGA,ICO,AVI" '### These types will be treated as images
Application("MaxConfigFolderLevel")=15 '### Maximum folder level to search up for config settings
Application("ExcludeFromSearchbots")=True '### Generate a robots.txt file in the LP folder to prevent your pics from showing up in search engines on the web :o)
Application("HomeLink")="/" '### If defined: show a home button linked to this page
Application("LogFile")="listpics.log"
Application("CropOnChangeRatio")=True '### Crop images to 3:2 ratio when using the change ratio function for commercial digital printing. If disabled, white bars will be added to the image as necessary.
Application("MaxFindItems")=1000 '### Maximum # files to return on find actions to preserve server resources (Uses TOP in query)
Application("LogLevel")=2 '### 0=No logging, 1=basic logging, 2=Full logging, 3=Debug level
Application("MaxZipItems")=500 '### Maximum number of files allowed in a Zip file to prevent server overload. Only for the full version.
Application("MultiMediaTypes")="AVI,WMV,MOV,QT,MPG,MPEG,RM,RAM,SWF,MP3,WAV,MID" '### These types will be treated as video (display media player object in the clients browser)
'Application("BaseURL")="" '### Get the applications base URL as users can access it on the web (e.g.: http"//www.dom.com/listpics/"). Empty=Auto-Detect
Application("MailComponent")="cdo" '### Defines which email component to use. Valid values are: "jmail", "aspmail", "cdo" or "cdonts" (cdonts does not work on server 2003!)
Application("SMTPMailServer")="localhost" '### SMTP server to use to send mail. Make sure relaying is allowed on that server from the IP where LP is hosted!
'Application("CalculateFolderTotalViews")=True '### Calculates # of image views of files in that folder (non-recursive). Slow for folders containing many subfolders!

'### Security
'Application("AllowedIP")="10.*" '### Comma delimited list of allowed IP numbers/ranges. Example: "192.*,10.0.0.*" 
Application("DeniedIP")="" '### Comma delimited list of denied IP numbers/ranges (this setting overrides AllowedIP). Example: "192.*,10.0.0.*" 
Application("ShowIPWithComments")=True '### Include visitor's IP address to image comments added
Application("AllowDirectLinks")=True '### Allow direct links to images (listpics.asp?a=show&ID=2).
'Application("HidePassprotected")=True '### Hide all folders that have a password defined that is different from the users currently entered password.
'Application("HideList")="thumbs.db" '### Do not include files and folders that contain these partial strings in their name (not even for admins). Example: "secret,.dat" Note: will be applied after a rebuild of an existing folder (not realtime)!
'Application("HideAll")=True '### If enabled, this option will hide all folders for browsing. Users can only access images if they have a direct link that you sent them (for example: listpics.asp?dir=MyPics)

'### Upload
Application("DisAllowedTypes")="EXE,BAT,ASP,ASPX,ASA,CFG,CMD,VBS" '### Disallow upload or rename of these file types
Application("NumUploadFields")=6 '### Number of upload slots on the upload page
Application("MaxUploadSize")=50*1024*1024 '### Maximum total size for uploads
Application("UploadInfo")="You can upload images or zip files. Maximum upload size=%MaxSize." '### Display this info on the upload page, for example upload instructions or rules. Use %MaxSize for maximum upload size.
Application("DefaultNewFileStatusAdmins")=2 '### Default status of new images found when an admin is logged in (0=New, 1=Pending, 2=Published, 3=Hidden, 4=Archived)
Application("DefaultNewFileStatusUsers")=2 '### Default status of new images when a user is logged in (0=New, 1=Pending, 2=Published, 3=Hidden, 4=Archived)
Application("AutoUnzip")=True '### Auto unzip images from uploaded zip files
'Application("UploadNotificationEmail")="no-reply@domain.com" '### If defined, an upload notification email will be sent to this email address whenever someone uploads a file (also check the MailComponent setting)
'Application("NoUploadNotificationForAdmins")=True '### Only send a notification if regular users upload images, not for admins

'### Image and lowres settings
Application("PrecacheImages")=True '### Preload the next image on image view/slideshow (may not improve speeds behind a Proxy).
'Application("RootFolder")="d:\temp" '### Folder where picture subfolders are located. If not defined, the \_Images subfolder of the folder containing this ASP script will be used.
'Application("LowResRootFolder")="d:\pics\Lowres" '### Full path to folder where all LowRes material is stored (both Thumbnails and Lowres). If not defined, the \_Lowres subfolder of the folder containing this ASP script will be used.
Application("TNPrefix")="TN_" '### Prefix to use for thumbnail files. Thumbnails are always JPG files.
Application("LowResPrefix")="LR_" '### Prefix to use for low resolution files. 
Application("UseLowRes")=True '### Users can download LowRes sized images (lower bandwidth). Generated on-the-fly on first page load.
Application("LowResImageSize")=800 '### LP will generate LowRes sized images of this size for viewing of larger images (default=800)
'Application("LowResPortraitImageSize")=600 '### If defined, Lowres images of portrait images will be scaled to this size (This way they will be as high as landscape images)
Application("ResizeSmallerImages")=True '### Enlarge images smaller than LowResImageSize
Application("TNSize")=160 '### Default thumbnail size
Application("JPEGQuality")=85 '### Default JPG quality (for TN, Lowres and JPG editing)
Application("UseExifCreationDate")=True '### Use the original creation date from EXIF info of present
Application("RetainExifheaders")=True '### Copy EXIF header on image manipulation (rotate, etc.)
Application("AutoRotate")=True '### If the camera supports the Exif "Orientation" tag (not many do!), the lowres images of original images taken rotated Left or Right (landscape) will be rotated back to upright position. Use only if you do not rotate originals.
Application("MakeBackups")=True '### (Default value for admin setting) Create a backup of original images that are modified by the admin (Rotate, resize, etc.)
Application("DisableImageToolbar")=True '### Disable the image toolbar in IE6+
Application("OverviewCols")=4 '### Number of thumbnail columns to show on image overview page (contact sheet)
Application("OverviewZoom")="1" '### Default zoom factor in image overview (default=1)
Application("OverviewTruncateChars")=25 '### Truncate file names in overview
Application("OverviewShowNumbers")=True '### Show file number with the name
Application("TimelineZoom")="0.5" '### Default zoom factor of thumbs in timeline
Application("TimelineMaxCols")=8 '### Maximum # images in one row in timeline
'Application("TimelineMissingDaySeparator")="..." '### Show a row with this separator for non adjacent days (empty=disabled)
Application("AllowRandomImages")=True '### Allow users to view a random image selection of the current folder + subfolders
'Application("RandomizeAll")=True '### If enabled, the random function will return a selection from all files in the database rather than only from the current folder + subfolders
Application("NumRandomImages")=8 '### Number of random images to show.
'Application("AutocreateFolderKeywords")=True '### Automatically create keywords for new files, based on folder name
'Application("UseExifInfo")=True '### Use Exif info of new images (User comment, Title, Description and Keywords)

'### Copyright/watermark text (used during rebuild of lowres material)
'Application("CopyRightText")="ASP ListPics - %ed - %c" '### If defined, this text will be added to all Lowres images. Variables: %d=Date, %t=Time, %f=Filename. Exif variables (if EXIF is present): %ed=Original date, %c=Camera used)
Application("CopyRightFont")="Arial bold"
Application("CopyRightFontSize")=12
Application("CopyRightColor")="FFFFFF" '### Text color in html color code (example: "BBDDFF")
'Application("CopyRightBGColor")="000000" '### Background color in html color code (example: "000000"). Empty=No background
Application("CopyRightShadow")=True '### Use shadow effect (improve readablility of the text on light images)

'############################################################################################
'### View settings
'############################################################################################
Application("MaxSlideshowTime")=30 '### Maximum time for slideshow to prevent users keeping their show running endlessly (in minutes)
Application("SlideShowDelay")=4 '### Default slideshow delay (s)
Application("AllowLoopSlideshow")=True '### Allow to play slideshow continuously
Application("NumRows")=2 '### Default # images per page
Application("NumCols")=4 '### Default # columns
Application("MultiplePreviewImages")=True '### Use up to 4 preview images in big folder icons
Application("Sortby")="name" '### Default sort order (Name, ModDate, CreDate, Size, NumViews)
Application("BeautifyFilenames")=True '### Format file/folde names ("ThisFILe" becomes "Thisfile") 
Application("AllowChangeRowsAndCols")=True
Application("AllowChangeSortorder")=True
Application("AllowShowImageInfo")=True
Application("AllowChangeLanguage")=True
Application("AllowUseBigFolderIcons")=True
'Application("FolderIconsUseSubfolders")=True '### Use images in subfolders for the current folder's Folder icon (disable if you have many pass-protected folders, otherwise tiny thumbs of protected images may show up in the folder's icon)
Application("UseBigFolderIcons")=True '### Default value for this user setting
Application("UseContextMenu")=True '### Use Right-click context menu (IE only)
Application("MinimalPagingButtons")=True '### Show only Prev/Next and page dropdown
Application("ShowImageBorder")=True '### Show thin border around images in image view
Application("ShowImageDimension")=2 '### Show image dimensions in image info (0=None, 1=inches, 2=cm)
Application("CenterLP")=False '### Center the listpics page instead of Left-align
Application("ShowSaveButton")=True '### Display image save button in view window
Application("ShowOriginalSizeButton")=True '### Display button for original image in view window
Application("UseTitleInsteadOfName")=True '### Use the image title (if defined) instead of the file name in view windows
Application("DontCountAdminViews")=True '### Do not count image views for admin users
Application("UsePopupViewWindow")=True '### Default value for user setting "Popup view window". Note: Extra-fullscreen mode (F11) will only work if this value is enabled in IE6 with XP SP2! 
Application("UseFullscreenPopup")=True '### Use fullscreen popup rather than windowed
'Application("NewItemsTag")=" <font size=1 color=red><i>New!</i></font>" '### HTML Tag to add to items new since last user visit (empty=disable)
'Application("ImageViewExtraInfo")="<i>Click on the image to view the orignal.</i>" '### Add this line of text to the thumbnail view, for example for basic instructions.
'Application("ThumbsViewExtraInfo")="<i>Click on the thumbnail to view the image.</i>" '### Add this line of text to the full image view, for example for basic instructions (only shown in non-fullscreen view).

'### Folder info view settings in listing
Application("UseFolderComments")=True '### Also use Folder comments besides image comments (if AllowComments is also enabled in folder settings)
Application("ShowFolderTotalViews")=True '### Also Calculate and show the Folder Total Views (slow for folders with many subfolders)
Application("ShowFolderSize")=True
Application("ShowFolderName")=True
Application("ShowFolderNumFiles")=True
Application("ShowFolderNumFolders")=True
Application("ShowFolderModDate")=True
'Application("ShowFolderCreDate")=True
Application("ShowFolderDescription")=True

'############################################################################################


Application("Version")="4.1d"
Application("NumLangEntries")=198 '### Maximum index of entries in the language file (UBound of array) to validate language files
Application("StatusNames")=Array("New","Pending","Published","Hidden","Archived")
Application("SettingNames")="ShowFileName,ShowCategory,ShowResolution,ShowSize,ShowFullSize,ShowModDate,ShowCreDate,ShowExifInfo,ShowViewCounter,ShowDescription,ShowRootButton,ShowBackButton,ShowLoginButton,AllowEditDescription,AllowImageOverview,AllowImageRatings,AllowSelectCategories,AllowComments,AllowSlideShow,AllowDownloadSelected,AllowDownloadAll,AllowFullSize,AllowSendByEmail,AllowFind,AllowUpload,AllowCreatefolder,AllowDelete,AllowCutCopyPaste,AllowRename,AllowUserConfig,ShowFileExtensions,ShowImageInfo,ShowImageExifInfo,ShowAllFileTypes,AllowManipulateImages,AllowThumbsOnly,AllowTimeline,AllowEditKeywords,AllowExtraFullScreen,ShowHiddenFiles,ShowHiddenFolders"
Application("AllowedIP")=Replace(Application("AllowedIP"),"*","")
Application("DeniedIP")=Replace(Application("DeniedIP"),"*","")

Application("HideList")=Replace(Application("HideList"),", ",",")
Application("HideList")=Replace(Application("HideList")," ,",",")
Application("HideList")=Split(Application("HideList"),",")

'### Init stuff
Set fso=Server.CreateObject("Scripting.FileSystemObject")
If Application("LogFile")<>"" AND Instr(Application("LogFile"),":\")=0 AND Instr(Application("LogFile"),"\\")=0 Then Application("LogFile")=Server.Mappath(Application("LogFile"))

'### Is Database SQL or Access? (Different DateDif handling in AutoMaintenance) ###
If Application("IsAccessDatabase")="" AND Instr(1,Application("DBConnection"),".mdb",1)>0 Then Application("IsAccessDatabase")=True 

'### Put all exif tags in array (to show full list of tags)
ExifTagsLong="Main.Desc, Image Description|Main.Make, Camera Make|Main.Model, Camera Model|Main.Ori, Orientation|Main.XRes, X Resolution|Main.YRes, Y Resolution|Main.ResUnit, Resolution Unit|Main.Software, Camera Software|Main.ModTime, Last Modification|Main.WPoint, White Point|Main.PrimChr, Primary Chromaticities|Main.YCbCrCoef, YCbCrCoefficients|Main.YCbCrPos, YCbCrPositioning|Main.RefBW, Reference Black/White point|Main.Copy, Copyright|Main.ExifOffset, Sub IFD Offset|Main.Title, Image Title|Main.Comments, Image Comments|Main.Author, Image Author|Main.Keywords, Image Keywords|Main.Subject, Image Subject|Sub.s, Exposure Time|Sub.f, F-Stop|Sub.prog, Program|Sub.iso, Equivalent ISO speed|Sub.ExifVer, Exif Version|Sub.OrigTime, Original Time|Sub.DigTime, Digitized Time|Sub.CompConfig, Components Configuration|Sub.bpp, Average compression ratio|Sub.sa, Shutter Speed APEX|Sub.aa, Aperture APEX|Sub.ba, Brightness APEX|Sub.eba, Exposure Bias APEX|Sub.maa, Maximum Aperture APEX|Sub.dist, Subject Distance|Sub.meter, Metering Mode|Sub.ls, Light Source|Sub.flash, Flash Used|Sub.focal, Focal Length|Sub.Maker, Maker Note|Sub.User, User Comment|Sub.sTime, Subsecond Time|Sub.sOrigTime, Subsecond Original Time|Sub.sDigTime, Subsecond Digitized Time|Sub.flashpix, Flash Pix Version|Sub.ColorSpace, Color Space|Sub.Width, Image Width|Sub.Height, Image Height|Sub.SndFile, Sound File|Sub.ExitIntOff, Exif Interoperability Offset|Sub.FPXRes, Focal Plan X Resolution|Sub.FPYRes, Focal Plan Y Resolution|Sub.FPResUnit, Focal Plan Unit|Sub.ExpIndex, Exposure Index|Sub.SenseMethod, Sensing Method|Sub.FileSource, File Source|Sub.SceneType, Scene Type|Sub.CFAPat, CFA Pattern|Nikon.ISO, Nikon ISO Setting|Nikon.Color, Nikon Color Mode|Nikon.Quality, Nikon Quality|Nikon.WhiteBal, Nikon White Balance|Nikon.Sharp, Nikon Image Sharpening|Nikon.Focus, Nikon Focus Mode|Nikon.Flash, Nikon Flash|Nikon.FlashMode, Nikon Flash Mode|Nikon.ISOSel, Nikon ISO Selection|Nikon.ImgAdjust, Nikon Image Adjustment|Nikon.Adapter, Nikon Adapter Setting|Nikon.Lens, Nikon Lens|Nikon.ManFocus, Nikon Manual Focus Distance|Nikon.DigZoom, Nikon Digital Zoom|Nikon.AFPos, Nikon Auto Focus Position|Oly.SpcMode, Olympus Special Mode|Oly.Quality, Olympus JPG Quality|Oly.Macro, Olympus Macro|Oly.DigZoom, Olympus Digital Zoom|Oly.Software, Olympus Software|Oly.CameraID, Olympus Camera ID|Oly.Flash, Olympus Flash Mode|Oly.Sharp, Olympus Sharpness Mode|Oly.SharpScale, Olympus Sharpness|Canon.Set1, Canon Settings 1|Canon.Set2, Canon Settings 2|Canon.ImageType, Canon Image Type|Canon.Software, Canon Firmware Version|Canon.ImageNo, Canon Image Number|Canon.Owner, Canon Owner Name|Canon.SerialNo, Canon Serial Number|Canon.CustomFnc, Canon Custom Functions|Canon.Macro, Canon Macro Mode|Canon.Flash, Canon Flash Mode|Canon.Focus, Canon Focus Mode|Canon.Shoot, Canon Easy Shooting Mode|Canon.Contrast, Canon Contrast Setting|Canon.Saturation, Canon Saturation Setting|Canon.Sharpness, Canon Sharpness Setting|Canon.AFPoint, Canon AutoFocus Point|Canon.ExpMode, Canon Exposure Mode|Canon.FlashDet, Canon Flash Details|Canon.FocusMode, Canon Focus Mode|Canon.WhiteBal, Canon White Balance|Canon.FlashBias, Canon Flash Bias|Canon.SubjectDist, Canon Subject Distance (0.01m or 0.001m)"
Application("AllExifTags")=Split(Replace(ExifTagsLong,", ",","),"|")

'### SatusList
For i=0 To Ubound(Application("StatusNames"))
	StatusList=StatusList & "<Option value=" & i & ">" & Application("StatusNames")(i) & "</a>"
Next
Application("StatusList")=StatusList

'### Images rootfolder
If Application("RootFolder")="" Then
	Application("RootFolder")=fso.GetParentfolderName(Server.Mappath("listpics.asp")) & "\_Images\"
Else
	If Right(Application("RootFolder"),1)<>"\" Then Application("RootFolder")=Application("RootFolder") & "\"
End If

'### LowRes rootfolder
If Application("LowResRootFolder")="" AND Instr(Application("LowResRootFolder"),":\")=0 AND Instr(Application("LowResRootFolder"),"\\")=0 Then 
	Application("LowResRootFolder")=fso.GetParentfolderName(Server.Mappath("listpics.asp")) & "\_LowRes\"
Else
	If Right(Application("LowResRootFolder"),1)<>"\" Then Application("LowResRootFolder")=Application("LowResRootFolder") & "\"
End If

'### Language
GetLanguageList
GetLanguage Application("Language")
GetIconList

If fso.fileexists(Server.Mappath("admin.asp")) Then Application("FullVersion")=True Else Application("FullVersion")=False
Application("AppIsInitialized")=True
Application.UnLock
Writelogline "Application start"
Writelogline "Rootfolder: " & Application("RootFolder")

'### Header/footer
Application("Header")= ReadIncFile(Server.MapPath("header.htm"))
Application("Footer")= ReadIncFile(Server.MapPath("footer.htm"))
End SUB

'########################
Sub Session_OnStart
'########################
On error resume next
Session("SessionIsInitialized")=True
If Application("ExcludeFromSearchbots") Then CreateRobotsExclude 'Needs to be in Session_OnStart!
If Request.ServerVariables("HTTP_X_FORWARDED_FOR")<>"" Then
	Session("Proxy")="Proxy: " & Request.ServerVariables("HTTP_VIA") & VbTab & Request.ServerVariables("REMOTE_ADDR")
	Session("IP")=Request.ServerVariables("HTTP_X_FORWARDED_FOR")
Else
	Session("IP")=Request.ServerVariables("REMOTE_ADDR")
End If
'Session("Host")="http://" & Request.ServerVariables("HTTP_Host") & Request.ServerVariables("URL")
'Session("Host")=Left(Session("Host"),Instrrev(Session("Host"),"/")-1)

'### Get apps base URL
If Instr(1,Application("BaseURL"),"http://",1)=1 Then 
	Session("BaseURL")=Application("BaseURL")
Else
	Session("BaseURL")="http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("SCRIPT_NAME")
	Session("BaseURL")=Left(Session("BaseURL"),InstrRev(Session("BaseURL"),"/"))
End If

'### Get NT user (Anonymous if not found)
Session("NTUser")=Request.ServerVariables("AUTH_USER")

'### Set Language resource + LCID
Session("Str")=Application("Str")
If IsNumeric(Session("Str")(1)) Then Session.LCID = Session("Str")(1)

'### Put exif names in an Array
s=Session("Str")(139)
s=Replace(s,", ",",")
Session("ExifNames")=Split(s,",")

'### Put filter names in an Array
s=Trim(Session("Str")(143))
s=Replace(s,", ",",")
Session("FilterList")=Split(s,",")

'### Base paths (move to a login page later on)
Session("RootFolder")=Application("RootFolder") 
If User<>"" Then Session("RootFolder")=Session("RootFolder") & User & "\"
Createpath Session("RootFolder")
Session("LowResRootFolder")=Application("LowResRootFolder")
If User<>"" Then Session("LowResRootFolder")=Session("LowResRootFolder") & User & "\"
Createpath Session("LowResRootFolder")

'### Set defaults
Session("LoginTime")=Now
Session("TNSize")=Application("TNSize")
Session("CurFolder")=Session("RootFolder")
Session("ZipName")=Session("LowResRootFolder") & "root.zip"
Session("LowResRootFolder")=Session("LowResRootFolder")
Session("IsRootFolder")=True
Session("AllowChangeRowsAndCols")=Application("AllowChangeRowsAndCols")
Session("AllowChangeSortorder")=Application("AllowChangeSortorder")
Session("AllowShowImageInfo")=Application("AllowShowImageInfo")
Session("AllowChangeLanguage")=Application("AllowChangeLanguage")
Writelogline "Session start"
Application("ActiveUsers")=Application("ActiveUsers")+1

End Sub

'########################
Sub Session_OnEnd
'########################
Application("ActiveUsers")=Application("ActiveUsers")-1
Writelogline "Session end"
End Sub

'########################
Sub Application_OnEnd
'########################
End Sub

'########################
Function ReadIncFile(path)
'########################
Set f=Server.CreateObject("Scripting.FileSystemObject")
ReadIncFile=""
If f.FileExists(path) Then
	Set ts=f.OpenTextFile(path)
	If NOT ts.AtEndOfStream Then ReadIncFile=ts.ReadAll
	ts.Close
	Set ts=Nothing
End If
Set f=Nothing
End Function

'########################
Function CreatePath(sPath)
'########################
If Instr(sPath,"\")>0 Then
	Set f=Server.CreateObject("Scripting.FileSystemObject")
	pos=Instr(3,sPath,"\",1)
	aTmp=Split(Mid(sPath,pos+1),"\")
	sNewPath=Left(sPath,pos-1)
	For n = 0 to Ubound(aTmp)
		On Error resume next 'Ignore permission problems on higher levels
		sNewPath = sNewPath & "\" & aTmp(n)
		If aTmp(n)<>"" AND NOT f.FolderExists(sNewPath) Then f.CreateFolder sNewPath
	Next
	If f.FolderExists(sPath) Then CreatePath=True Else CreatePath=False
	Set f=Nothing
End If
End Function

'########################
SUB WriteLogLine(msg)
'########################
On Error resume next
If Application("LogFile")<>"" Then
		If err<>0 then sErr=VbTab & "Error: " & err.description Else sErr=""
		Set f=Server.CreateObject("Scripting.FileSystemObject")
		Set fLog=f.OpenTextFile(Application("LogFile"),8,True)
		fLog.WriteLine Now & Vbtab & Session("IP") & VbTab & Session("NTUser") & VbTab & msg & sErr
		fLog.close
		Set f=Nothing
End If
End SUB

'########################
Sub CreateRobotsExclude
'########################
On Error resume next
Set fso=Server.CreateObject("Scripting.FileSystemObject")
Set fw=fso.OpenTextFile(Server.Mappath("robots.txt"),2,True)
s=Request.ServerVariables("URL")
s=left(s,InstrRev(s,"/"))
fw.writeline "User-agent: *"
fw.writeline "Disallow: " & s
fw.close
Set fso=Nothing
Application("ExcludeFromSearchbots")=False ' Set to false so it will not run until next app start
End SUB

'########################
Sub GetLanguage(LangFile)
'########################
Set fso=Server.CreateObject("Scripting.FileSystemObject")
ReDim aTmp(0)
f=Server.Mappath("lang/"& langfile)
If fso.fileexists(f) Then
	Set fr=fso.OpenTextFile(f,1,False)
	aLines=Split(fr.readall,VbCrLf)
	fr.close
	For n = 0 To UBound(aLines)
		s=Trim(aLines(n))
		Pos=Instr(s,"=")
		If s<>"" AND Pos>1 AND Pos<10 AND left(s,1)<>"'" AND left(s,1)<>";" Then 
			If Instr(s,";") Then s=Left(s,Instr(pos,s,";",1)-1)
			If IsNumeric(Left(s,Pos-1)) Then
				i=Int(Left(s,Pos-1))
					If i>Hi Then
					Hi=i
					Redim Preserve aTmp(i)
				End If
				aTmp(i)=EscapeQuote(Trim(Mid(s,Pos+1)))
			End If
		End If
	Next
	Application("Str")=aTmp
End If
If Application("LogLevel")>0 Then WriteLogLine "Collected default language strings for " & Application("Language")
Set fso=Nothing
End SUB

'########################
Sub GetLanguageList
'########################
Set fso=Server.CreateObject("Scripting.FileSystemObject")
Set ofolder=fso.getfolder(Server.Mappath("lang"))
Set oFiles=oFolder.files
For each f in oFiles
	If UCase(fso.GetExtensionName(f))="DAT" Then 
		s=fso.getbasename(f)
		s=UCase(Left(s,1)) & LCase(Mid(s,2))
		Application("LanguageList")=Application("LanguageList") & "<Option value=" & f.name & ">" & s
	End If
Next
Set oFiles=Nothing
Set ofolder=Nothing
If Application("LogLevel")>0 Then WriteLogLine "Enumerated languages"
Set fso=Nothing
End SUB

'########################
Function EscapeQuote(str)
'########################
	EscapeQuote=Replace(str,"'","&#39;")
End Function

'########################
Sub GetIconList
'########################
Set fso=Server.CreateObject("Scripting.FileSystemObject")
Set ofolder=fso.getfolder(Server.Mappath("Img"))
Set oFiles=oFolder.files
Application("TypeIcons")=""
For each f in oFiles
	Ext=UCase(fso.GetExtensionName(f))
	If Ext="GIF" AND Instr(1,f.name,"t_",1)=1 Then Application("TypeIcons")=Application("TypeIcons") & Mid(fso.getbasename(f),3) & ","
Next
Set oFiles=Nothing
Set ofolder=Nothing
If Application("LogLevel")>0 Then WriteLogLine "Enumerated file type icons"
Set fso=Nothing
End SUB

</SCRIPT>