ePages 6.17.9 - DE_EPAGES/Core/API/File.pm

Package DE_EPAGES::Core::API::File

This module provides file and directory access.

Example
use DE_EPAGES::Core::API::File qw( GetFileContent WriteFile ...);
@EXPORT_OK
RealPath
AbsolutePath
WindowsPath
RelativePath
MakePathWriteable
MakePathReadable
ResolveSymbolicLink
fsplit
SetAccessRights
GetAccessRights
GetExecBit
IsInPath
CreateDirectory
DeleteDirectory
DeleteStaticAtDirectory
ExistsDirectory
CopyDirectory
BackupDirectory
RebuildDirectory
RenameDirectory
GetInfoDirectory
GetSubDirectories
GetTrashRoot
GetFileNames
CompareDirectories
GetDirectorySize
PathGlob2TypeGlob
FilesOnlyInDir1
GetDOSReadOnlyFiles
MergeIniFiles
WriteFile
LockFile
OpenFile
MoveFile
DeleteFile
DeleteListedFiles
CopyFile
BackupFile
MoveToDateDir
GetFileContent
GetFileContentLines
GetMountPoint
SameDevice
GetFileInfo
GetFileSize
GetFileMD5Digest
GetSimilarFileName
CompareMD5File
CompareMD5TextFile
ExistsFile
ExistsFileCaseSensitive
GetCachedFile
IsTextFile
IsImageFile
IsCustomizedFile
Text2Unix
Text2Dos
DetectFileEncoding
GetBOM
IsFileNewer
ConvertPathChars
CorrectPathSlashes
RunOnDirectory
RunOnGlob
CaptureStream
CreateSymLink
DeleteSymLink
IsSymLink

Functions

AbsolutePath
BackupDirectory
BackupFile
CaptureStream
CompareDirectories
CompareMD5File
CompareMD5TextFile
ConvertPathChars
CopyDirectory
CopyFile
CorrectPathSlashes
CreateDirectory
CreateSymLink
DeleteDirectory
DeleteFile
DeleteListedFiles
DeleteStaticAtDirectory
DeleteSymLink
DetectFileEncoding
ExistsDirectory
ExistsFile
ExistsFileCaseSensitive
FilesOnlyInDir1
GetAccessRights
GetBOM
GetCachedFile
GetDOSReadOnlyFiles
GetDirectorySize
GetExecBit
GetFileContent
GetFileContentLines
GetFileInfo
GetFileMD5Digest
GetFileNames
GetFileSize
GetInfoDirectory
GetMountPoint
GetSimilarFileName
GetSubDirectories
GetTrashRoot
IsCustomizedFile
IsFileNewer
IsImageFile
IsInPath
IsSymLink
IsTextFile
LockFile
MakePathReadable
MakePathWriteable
MergeIniFiles
MoveFile
MoveToDateDir
OpenFile
PathGlob2TypeGlob
RealPath
RebuildDirectory
RebuildFile
RelativePath
RenameDirectory
ResolveSymbolicLink
RunOnDirectory
RunOnGlob
SameDevice
SetAccessRights
Text2Dos
Text2Unix
WindowsPath
WriteFile
fsplit

AbsolutePath

Converts relative paths (as sub1/sub2) to absolute paths (as C:temp\sub1\sub2 or /tmp/sub1/sub2) by prepending $BaseDir (if given) or cwd().

Syntax
$AbsPath = AbsolutePath($RelPath);
$AbsPath = AbsolutePath($RelPath, $BaseDir);
Input
$RelPath (string)
relative path
$BaseDir (string)
(optional, default=cwd()) base directory
Return
$AbsPath (string)
absolute path

BackupDirectory

Copies files which exist in both, source directory and target directory, but not in the backup directory from the target directory to the backup directory.

Syntax
BackupDirectory( $SourceDir, $TargetDir, $BackupDir, $Flags );
Input
$SourceDir (string)
source directory
$TargetDir (string)
target directory
$BackupDir (string)
backup directory
$Flags (hash ref)
flags to modify the behaviour of BackupDirectory.
The following flags can be used:
  • ignore - Ignore files with path names (quoted) relative to $SourceDir
  • stat - defines how to handle UNIX file attributes:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)

BackupFile

If BackupFile doesn't exist and SourceFile and TargetFile are not equal this function copies TargetFile to BackupFile.

Syntax
BackupFile( $SourceFile, $TargetFile, $BackupFile );
Input
$SourceFile (string)
source file
$TargetFile (string)
target file
$BackupFile (string)
backup file
$Flags (hash ref)
flags to modify the behaviour of BackupFile.
The following flags can be used:
  • stat - defines how to handle UNIX file attributes:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)

Return
$BackupDone (boolean)
0 or 1

CaptureStream

redirects $FileHandle output of function $Sub to $Variable

Syntax
$Variable = CaptureStream($FileHandle, $Sub);
Example
my $Variable = CaptureStream( *STDERR, sub {
                   print STDERR 11111;
               });
Input
$FileHandle (file handle)
name of the file handle
$Sub (coderef)
reference to function that would be executed
Return
$Variable (string)
string that otherwise would be sent to $FileHandle

CompareDirectories

Compares contents (file names) of two directories.

Syntax
$Compare = CompareDirectories($Path1, $Path2);
Input
$Path1 (string)
relative or absolute directory name
$Path2 (string)
relative or absolute directory name
Return
(1 - $Path2 contains all file names of $Path1, 0 - $Path1
contains file names not included in $Path2.)
$Compare

CompareMD5File

if it is a TextFile IsTextFile returns CompareMD5TextFile($File, $MD5Digest); else returns true if GetFileMD5Digest eq $MD5Digest

Syntax
$IsEqual = CompareMD5File($File, $MD5Digest);
Example
$IsEqual = CompareMD5File('testtemp.txt','4c832c34a88de899dab3d00b7ccca632');
Input
$File (string)
filename
$MD5Digest (string)
md5 hex digest
Return
$IsEqual (boolean)
true if the file content matches the MD5Digest

CompareMD5TextFile

returns 1 if the MD5Hash of the file content, or the MD5Hash of the dos2unix converted file content or the MD5Hash of the unix2dos converted file content is equal $MD5Digest

Syntax
$IsEqual = CompareMD5TextFile($File, $MD5Digest);
Example
$IsEqual = CompareMD5TextFile('testtemp.txt','4c832c34a88de899dab3d00b7ccca632');
Input
$File (string)
filename
$MD5Digest (string)
md5 hex digest
Return
$IsEqual (boolean)
true if the file content matches the MD5Digest

ConvertPathChars

Encodes a normal string to a string, which can be used as direcory name. The following characters are converted to a 4-digit hex code surrounded by underline: \ / : * ? " | & ' % # . \x{0000}-\x{0020} \x{0080}-\x{ffff} For example: '.' -> '_002E_' Note on dots in file names: Windows silently removes a trailing dot from directry or file names. UrlScan for IIS rejects all directory names containing dots.

Syntax
$DirectoryName = ConvertPathChars( $Alias );
Example
$DirectoryName = ConvertPathChars( "IBN-08/25.1234" );
Input
$Alias (string)
alias of object
Return
$DirectoryName (string)
directory name

CopyDirectory

Copies all files from one directory to another. This function works recursively and creates the necessary sub directories. If a file already exists in the target directory, then it will be saved in the backup directory unless there is already a backup file. In this case the target file is overwritten by the source file. The source directory must exist. The target and backup directories will be created if they don't exist.

Syntax
CopyDirectory( $SourceDir, $TargetDir, $BackupDir, $Flags );
Example
CopyDirectory( 'c:\\Temp','d:\\Temp', 'e:\\backup', { recursive => 1 } );
Input
$SourceDir (string)
source directoy
$TargetDir (string)
target directory
$BackupDir (string)
backup directory (optional)
$Flags (hash ref)
flags to modify the behaviour of CopyDirectory.
The following flags can be used:
  • recursive - copies directory recursively
  • link - If set, create hard link instead of copying.
    If set to 'orCopy', copies file if devices differ.
    If set to 'noCheck', don't check devices.
  • unlink - If set, remove target before copying
  • ignore - ignore files with path names (quoted) relative to $SourceDir
  • stat - defines how to handle UNIX file attributes for $TargetDir:
    - epages: set file attributes according to epages rules
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)
    If stat is not set, default values are either 'epages' or 'preserve':
    stat is set to 'epages' if: a) 'by' is perl
    b) target is located inside epages, but source not
    c) source and target are located in different epages parts
    stat is set to 'preserve' if: a) target is located outside epages
    b) source and target are located in the same epages part
  • bakstat - defines how to handle UNIX file attributes for $BackupDir:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)
  • md5sum - name of an ini file
    - sections: file names relative to $SourceDir
    - keys:
    - - md5sum: md5sums to compare
    - - type: text (default) or binary. If text then md5sums
    are compared ignoring EOLs for text files
    - example:
    [License.xml]
    type=text
    md5sum=1f99100011f69ed8d81500facad25da3 # 6.11.0 mysql
    - the ini file defines how to handle a file to be copied:
    - - skips file if identical in $TargetDir and $SourceDir
    - - creates new file if does not exist in $TargetDir
    - - overrides file in $TargetDir if the MD5 sum matches one in the list
    - - creates a file with extension .latest if MD5 sum does not match
  • by - defines the tool that is used for copying:
    - perl: use File::Copy
    - exe: use cp/copy executable (default for UNIX)
    Default value for 'by' is 'perl' if:
    - Windows
    - $Flags->{stat} is set to 'epages'
    - $Flags->{recursive} is unset
    - $Flags->{md5sum} is set
    - $Flags->{ignore} is set
  • Print - print the command line (only used with by => exe) - boolean

CopyFile

Copies a file in binary mode and sets the access rights.

Syntax
CopyFile( $Source, $Target, $hFlags );
Input
$Source (string)
source file name
$Target (string)
target file name
$Flags (hash ref)
flags to modify the behaviour of CopyFile.
The following flags can be used:
  • create_directory - CreateDirectory or not
  • link - If set, create hard link instead of copying.
    If set to 'orCopy', copies file if devices differ.
    If set to 'noCheck', don't check devices.
    If stat is 'epages', set file attributes accordingly;
    otherwise do not set file attributes
  • unlink - If set, remove target before copying
  • stat - defines how to handle UNIX file attributes:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)
  • md5info - hash ref, keys:
    - md5sum: md5sums to compare (scalar or array ref)
    - type: text (default) or binary. If text then md5sums are
    compared ignoring EOLs for text files
    md5sum defines how to handle a file to be copied:
    - skips file if identical in $Source and $Target
    - creates new file if $Target does not exist
    - overrides $Target if the MD5 sum matches one in the list
    - creates $Target with extension .latest if MD5 sum does not match

CorrectPathSlashes

Execute WindowsPath($AnyPath) if running on windows, else do nothing.

Syntax
$CorrectedPath = CorrectPathSlashes($AnyPath);
Input
$AnyPath (string)
directory/file path (unix/windows format)
Return
$WindowsPath (string)
directory/file path (right format)

CreateDirectory

Creates the directory path. Does nothing if the directory already exists.

Syntax
$CountCreated = CreateDirectory($Path, $hFlags);
Example
$CountCreated = CreateDirectory('C:\\Test', {'recursive'=>0,'ExecBit'=>1});
Input
$Path (string)
relative or absolute directory name
$hFlags (hash)
hash (see SetAccessRights, optional), 'recursive' => bool:
if true (default), directory will be created recursively (mkpath) otherwise only
the top directory will be created (mkdir), if its parent path exists
Return
$CountCreated (boolean)
count of created directories, 0 directory did already exists
before

CreateSymLink

Creates a symbolic link from one file or directory to another.

Syntax
CreateSymLink($Source, $Target);
Example
CreateSymLink('/temp/sub1/sub2', '/temp/linked_sub2');
Input
$Source (string)
absolute path of source file or directory (existing directory or file)
$Target (string)
absolute path of target file or directory (link name)

DeleteDirectory

Removes the directory. Throws an error if the directory cannot be deleted, for example because it contains files or sub directories and the recursive flag is not set. If the directory did not exist before, then the function does nothing.

Syntax
$Deleted = DeleteDirectory($Path, $hFlags);
Example
$Deleted = DeleteDirectory('C:\\Test',{'recursive' => 1});
Input
$Path (string)
directory
$hFlags (hash ref)
flags to modify the behaviour of DeleteDirectory.
The following flag can be used:
  • recursive - delete directory recursive with
    all contents like rm -rf (default = 0 )
  • move - instead of deleting the directory files, move it
    to the _TRASH_ folder in EPAGES_STATIC, EPAGES_STORES
    or EPAGES_WEBROOT (default=0, implies recursive)

$TrashRoot (string (optional))
trash directory
Return
$Deleted (boolean)
1 directory was removed , 0 directory doesnt exists

DeleteFile

Removes a file from disk. The function throws an error if the file cannot be deleted. If the file did not exist before, the function does nothing. ErrorCodes:

Syntax
$Deleted = DeleteFile($FileName);
Example
DeleteFile('/var/log/error.log');
Input
$FileName (string)
name of file
Return
$Deleted (boolean)
true if the file existed and was deleted, false if the file
did not exist.

DeleteListedFiles

Removes listed files from patch. If an entry ends in .inexistent assume this as a file file to be handled by DeleteListedFiles. The function throws an error if a file cannot be deleted. If the file did not exist before, the function does nothing.

Syntax
$Deleted = DeleteListedFiles($Path, $FileList);
Example
$Deleted = DeleteListedFiles('C:\\Test','Test.inexistent');
Input
$Path (string)
directory
$FileList (string)
list with file names relative to directory
Return
$Deleted (boolean)
true if at least one file was deleted, false if not

DeleteStaticAtDirectory

Removes _STATIC_ directories in given directory.

Syntax
DeleteStaticAtDirectory($Directory);
Input
$Directory (string)
directory name

DeleteSymLink

Removes a symlink from disk. The function throws an error if the link cannot be deleted. If the link did not exist before, the function does nothing. ErrorCodes:

Syntax
$Deleted = DeleteSymLink($FileName);
Example
DeleteSymLink('/temp/symlink');
Input
$FileName (string)
name of symlink
Return
$Deleted (boolean)
true if the symlink existed and was deleted, false if it
did not exist.

DetectFileEncoding

Checks if the file has a BOM marker (Unicode Byte Order Mark) and retruns the corresponding encoding, for example 'utf-8' or 'utf-7'. Returns undef if the file does not have a BOM.

Syntax
$Encoding = DetectFileEncoding( $FileName );
Input
$FileName (string)
file name
Return
$Encoding (string)
character set name

ExistsDirectory

Returns true if the directory exists.

Syntax
$Exists = ExistsDirectory($Path);
Example
if( ExistsDirectory('C:\\Test') ) { ... }
Input
$Path (string)
directory
Return
$Exists (boolean)
true if the directory exists, otherwise false

ExistsFile

Returns true if the file exits.

Syntax
$Exists = ExistsFile($FileName);
Example
if( ExistsDirectory('C:\\Test\\test.txt') ) { ... }
Input
$FileName (string)
filename
Return
$Exists (boolean)
true if the file exists, otherwise false

ExistsFileCaseSensitive

Returns true if the file exits. Under windows filenames are not case sensitive, this function is needed to guarantee equal behavior for all operating systems. Now these file 'tEsT.XmL' is no longer found under windows.

Syntax
$Exists = ExistsFileCaseSensitive($FileName);
Example
if( ExistsFileCaseSensitive('C:\\Test\\test.txt') ) { ... }
Input
$FileName (string)
filename
Return
$Exists (boolean)
true if the file exists, otherwise false

FilesOnlyInDir1

Returns a list of files that exist in $Dir1, but not in $Dir2. This works with symbolic links.

Syntax
$aFileList =  FilesOnlyInDir1($Dir1, $Dir2);
Input
$Dir1 (string)
directory
$Dir2 (string)
directory
Return
$aFileList (array ref)
list of files

GetAccessRights

Returns ref.hash with mode, uid and gid for FileName (only unix).

Syntax
$hAccess = GetAccessRights($FileName);
Input
$FileName (string)
file to be modified
Return
$hAccess (ref.hash)
flags
  • Mode - constant as defd in DE_EPAGES::Core::API::Constants
  • UserID - user ID - integer
  • GroupID - group ID - integer
  • aTime - access time (seconds since 1.1.1970 UTC)
  • mTime - modified time (seconds since 1.1.1970 UTC)

GetBOM

Returns the Byte Order Mark for the given encoding.

Syntax
$BOM = GetBOM( $Encoding );
Example
$BOM = GetBOM( 'utf16be' );
Input
$Encoding (string)
'utf-7' or 'utf-8' or 'utf16le' or 'utf16be'
Return
$BOM (binary)
Byte Order Mark

GetCachedFile

Return the content of an file. If you call this function twice and the file was not changed the file wasnt read again. The up-to-dateness of the file will be tested each second.

Syntax
$Content = GetCachedFile($FileName, $Sub);
Example
my $IniConfig = GetCachedFile( $CONFIG_FILENAME, sub {
     my ($FileName) = @_;
     return DE_EPAGES::Core::API::IniConfig->new( FileName => $FileName );
 });
Input
$FileName (string)
filename
$Sub (ref.code)
reference to a function (default GetFileContent
Return
$Content (*)
returned content depend on the $Sub function

GetDOSReadOnlyFiles

Returns a ref.array of DOS files with read-only flag

Syntax
$aReadOnlyFiles = GetDOSReadOnlyFiles($AnyPath);
Input
$AnyPath (string)
directory/file path (unix/windows format)
Return
$aReadOnlyFiles (ref.array)
list of files with read-only flag

GetDirectorySize

Returns the size of a directory in bytes. If a block size is specified all file and directory sizes will be ceiled to multiple of block size. Note: On a windows system is the directory entry 0 bytes. ErrorCodes:

Syntax
$Size = GetDirectorySize($Directory, $BlockSize);
Example
my $Size = GetDirectorySize('/var/log', 1024);
Input
$Directory (string)
name of directory
$BlockSize (string)
block size of file system device (default 0)
Return
$Size (integer)
total size of directory, in bytes

GetExecBit

Returns ref.hash with execbit (only unix).

Syntax
$hBits = GetExecBit($FileName);
Input
$FileName (string)
file to be modified
Return
$hBits (ref.hash)
flags
  • ExecBit - 0: not executable by owner
    - 1: executable by owner

GetFileContent

Returns the content of a file as a scalar reference. ErrorCodes:

Syntax
$sContent = GetFileContent($FileName, $hFlags);
Example
my $sContent = GetFileContent('/var/log/error.log');
Input
$FileName (string)
name of file
$hFlags (hash ref)
flags to modify the behaviour of GetFileContent. The following
flags can be used:
  • binary - don't convert newlines
  • flock - block access to the file during the read operation
  • utf8 - reads the stream using perl's internal encoding,
    otherwise the content is marked as binary
  • encoding - character encoding, default: 'iso-8859-1'
  • usebom - use the BOM to detect Unicode files.
    If the files has a byte order mark, then the flags
    'utf8' and 'encoding' are ignored.

Return
$sContent (ref.string)
content of full file

GetFileContentLines

Returns the content of a file as an array of lines. ErrorCodes:

Syntax
$aContent = GetFileContentLines($FileName, $hFlags, $LineSep);
Example
my $aContent = GetFileContentLines('/var/log/error.log');
Input
$FileName (string)
name of file
$hFlags
flags to modify the behaviour of GetFileContent. The following
flags can be used:
  • binary - don't convert newlines
  • flock - block access to the file during the read operation
  • utf8 - reads the stream using perl's internal encoding
  • encoding - character encoding, default: 'iso-8859-1'
  • usebom - use the BOM to detect Unicode files.
    If the files has a byte order mark, then the flags
    'utf8' and 'encoding' are ignored.
$LineSep (string)
line seperator (default is "\n")
Return
$aContent (ref.array.string)
content of full file

GetFileInfo

Returns file size, modification and access time of a file. Returns an empty has if the file does not exist.

Syntax
$hFileInfo = GetFileInfo($FileName);
Input
$FileName (string)
file name to get informations from
Return
$hFileInfo (ref.hash)
flags
  • Name - filename with Path - String
  • FileName - filename without Path - String
  • Extension - extension of file - String
  • Path - path of file - String
  • Size - file size in byte - Integer
  • LastAccess - DateTime - Object
  • LastChange - DateTime - Object
  • Mimetype - Mimetype - String

GetFileMD5Digest

Returns the md5 hex digest of the content of a file

Syntax
$HexDigest = GetFileMD5Digest($FileName);
Example
my $HexDigest = GetFileMD5Digest('/var/log/error.log');
Input
$FileName (string)
name of file
Return
$HexDigest (string)
md5 hex digest ( see perldoc Digest::MD5)

GetFileNames

Returns filenames which are included in the given directory in an array reference.

Syntax
$aFiles = GetFileNames( $DirPath, $hFlags );
Example
$aFiles = GetFileNames( 'C:\\', {'recursive' => 1} );
Input
$DirPath (string)
directory, for which the filenames are wanted (default '.')
$hFlags (ref.hash.string)
(optional) see GetInfoDirectory
Return
$aFiles (ref.array.string)
array of file names

GetFileSize

Returns the size of a file in bytes. ErrorCodes:

Syntax
$Size = GetFileSize($FileName);
Example
my $Size = GetFileSize('/var/log/error.log');
Input
$FileName (string)
name of file
Return
$Size (integer)
total size of file, in bytes

GetInfoDirectory

Returns all items of a directory like files, subdirectories or others (e.g. links).

Syntax
$hInfo = GetInfoDirectory( $DirPath , $hFlags );
Example
$hInfo = GetInfoDirectory( 'C:\\', { recursive => 1, ignore => $raIgnore } );
Input
$DirPath (string)
directory, for which the filenames are wanted (default '.')
$hFlags (ref.hash.string)
(optional) possible flags are:
  • recursive - process sub directories
  • ignore - Ignore files with path names (quoted) relative to $hFlags->{basedir}
  • basedir - see above, default is $DirPath
  • relative - dirs and files are relative to $DirPath
Return
$hInfo (ref.hash.array.string)
directory items keys are:
  • Directories - contains directories - ref.array.string
  • Files - contains files - ref.array.string
  • Other - contains links - ref.array.string

GetMountPoint

returns mount point for $Path (if found in /etc/mtab).

Syntax
$MountPoint = GetMountPoint($Path);
Input
$Path (string)
path
Return
$MountPoint (string)
mount point of $Path

GetSimilarFileName

Returns a file name for a base file name, that does not exist in this directory. This is helpful, when a file has to be copied, but shall not overwrite an existing file.

Syntax
$SimilarFileName = GetSimilarFileName($FileName);
Example
$SimilarFileName = GetSimilarFileName('C:\\Photos\\photo.jpg');
# $SimilarFileName is 'C:\\Photos\\photo1.jpg', if this does not exist
Input
$FileName (string)
absolute file path of base file
Return
$SimilarFileName (string)
absolute, not existing file path

GetSubDirectories

Returns subdirectories of the given directory in an array reference. Please note that the array doesn't contain the '.' and '..' directories.

Syntax
$aSubDirs = GetSubDirectories($Directory, $hFlags);
Example
$aSubDirs = GetSubDirectories('C:\\', {'recursive' => 1});
Input
$DirPath (string)
directory, for which the subdirectories are wanted (default '.')
$hFlags (ref.hash.string)
(optional) see GetInfoDirectory
Return
$aSubDirs (ref.array.string)
array of subdirectories names

GetTrashRoot

Get the EPAGES_STATIC EPAGES_STORES EPAGES_WEBROOT Environment for creating a trash root for this path

Syntax
$TrashRoot = GetTrashRoot($Path);
Example
$TrashRoot = GetTrashRoot($Path);
Input
$Path (string)
directory
Return
$TrashRoot (string)
directory

IsCustomizedFile

checks if md5sum in $hMD5 is same as md5sum of $File

Syntax
IsCustomizedFile($File, $hMD5);
Input
$File (string)
file name
$hMD5 (hash ref)
hash with keys:
  • md5sum - md5sums to compare (scalar or array ref)
  • type - text (default) or binary. If text then md5sums
    are compared ignoring EOLs for text files.

Return
$IsCustomized (boolean)
returns 1 if customized, else 0

IsFileNewer

Checks if the target file is newer than the source file. If the source does not exist it throws the error 'FILE_NOT_FOUND'. If the target file does not exist or is older than this function it returns 'false' (0).

Syntax
IsFileNewer($Source, $Target);
Input
$Source (string)
source file
$Target (string)
target file
Return
$isNewer (boolean)
0 or 1

IsImageFile

Checks if the file is an image file using the file extensions see DE_EPAGES::Core::API::Constants constant IMAGE_FILE_TYPES.

Syntax
$IsImageFile = IsImageFile($FileName);
Input
$FileName (string)
file to be modified
Return
$IsImageFile (boolean)
true if the file has a known image file extension

IsInPath

Test if a file or directory is located at a base directory. @example $IsInPath = IsInPath('C:\Programs\epages\..\..\Windows\some.conf', 'C:\Programs\epages'); // false @example $IsInPath = IsInPath('C:\Programs\epages\..\some.conf', 'C:\Programs'); // true

Syntax
$IsInPath = IsInPath($DirectoryOrFile, $BaseDirectory);
Input
$PathToDirectoryOrFile (string)
path to directory or file
$AllowedPath (string)
allowed path
Return
$IsInPath (boolean)
PathToDirectoryOrFile is part of AllowedPath

IsSymLink

Returns true if the file name is a symlink.

Syntax
$IsSymLink = IsSymLink($FileName);
Example
if( IsSymLink('/temp/symlink') ) { ... }
Input
$FileName (string)
target file or directory link
Return
$IsSymLink (boolean)
true if the target is a symlink, otherwise false

IsTextFile

Checks if the file is a textfile using the file extensions see DE_EPAGES::Core::API::Constants constant TEXT_FILE_TYPES.

Syntax
$IsTextFile = IsTextFile($FileName);
Input
$FileName (string)
file to be modified
Return
$IsTextFile (boolean)
true if the file has a known text file extension

LockFile

Locks a file and unlocks it at the end of the code block. There are 2 locking modes awailable:

Locking is implemented using flock() on Windows. On Unix systems fcntl() is used, because flock() does not work over NFS. Both methods are defined as advisory locks, meaning that processes that do not aquire locks can still access the file regardless of any locks.

Syntax
LockFile( $FileHandle, $Access, $cCode );
Example
OpenFile( '>>', 'test.txt', sub {
    my ($FileHandle) = @_;
    LockFile( $FileHandle, 'w', sub {
        # seek to the end of the file in case someone appended
        # while we were waiting...
        seek( $FileHandle, 0, 2 ) or die $!;
        print $FileHandle, "...\n";
    });
});
Input
$FileHandle (handle)
open file handle
$Access (string)
access mode ('w' or 'r')
$cCode (code ref)
code to execute while the file is locked

MakePathReadable

Returns existing part of $Path and makes it readable.

Syntax
($ExistingMode, $ExistingPath) = MakePathReadable($Path);
Input
$Path (string)
directory/file path
Return
$ExistingMode (string)
file mode
$ExistingPath (string)
directory/file path

MakePathWriteable

Returns existing part of $Path and makes it writeable.

Syntax
($ExistingMode, $ExistingPath) = MakePathWriteable($Path);
($ExistingMode, $ExistingPath) = MakePathWriteable($Path, $ReadOnly);
Input
$Path (string)
directory/file path
$ReadOnly (string)
make it readable, not writeable
Return
$ExistingMode (string)
file mode
$ExistingPath (string)
directory/file path

MergeIniFiles

Adds sections from $Source to $Target if not yet exist in $Target. For all $EditSections, do not simply add/replace $Target section by $Source section but add/replace only the $Target parameters that exist in $Source. Removes duplicate comments in $Target.

Syntax
MergeIniFiles($Target, $Source, $EditSections, $hFlags);
Example
MergeIniFiles("$ENV{EPAGES_CONFIG}/Scheduler.conf",
  "$ENV{EPAGES_CARTRIDGES}/DE_EPAGES/Database/Data/Scheduler/Scheduler.conf",
  [ 'LOOPS' ], { 'replace' => 'parameters' } );
Input
$Target (string)
name of file
$Source (string)
name of file
$EditSections (ref.array)
(optional) list of section names
$hFlags (hash ref)
(optional) flags to modify the behaviour of MergeIniFiles.
  • replace
    if set to 'sections' - overwrites target for all but $EditSections
    if set to 'parameters' - overwrites target only for $EditSections
    if otherwise set - overwrites target for all
    if unset - existing sections/parameters in target are not changed
  • delcomments
    if set to ';' - deletes comments starting with ';'
    if set to '#' - deletes comments starting with '#'
    if otherwise set - deletes all comments
    if unset - comments remain
  • delete
    if set delete sections on the fly

MoveFile

Moves a file on disk if file on same device rename was used. We don't use perlfunc rename because it may not work across file system boundaries.

Syntax
MoveFile($SourceFile, $TargetFile, $hFlags);
Example
MoveFile('/var/log/error.log', '/var/logger/error.b1');
Input
$SourceFile (string)
name of source file
$TargetFile (string)
name of target file
$Flags (hash ref)
flags to modify the behaviour of MoveFile.
The following flags can be used:
  • create_directory - CreateDirectory or not
  • stat - defines how to handle UNIX file attributes:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)

MoveToDateDir

Moves files in $Dir/$FilePrefix* older than $Days (starting from $Now) to $Dir/$Format/$FilePrefix*.

Syntax
MoveToDateDir($Dir, $FilePrefix, $Days, $Now, $Format, $Verbose);
Example
MoveToDateDir($Dir, '[a-z]', '%Y/%m', 7, time());
Input
$Dir
move files in $Dir
$FilePrefix
move files starting with $FilePrefix
$Days
move files older than $Days
$Now
$Now is now (seconds since epoch) (default: time())
$Format
move files to $Format (default: %Y/%m)
$Verbose
send output to stdout (default: 0)
========================================================================================

OpenFile

Opens a file, executes a code reference and closes the file after the code reference is finished. The handle to the open file is passed as first parameter to the code.

Syntax
OpenFile( $Mode, $FileName, $Sub );
Example
OpenFile( '>>', 'LogFile.txt', sub {
    my( $FileHandle ) = @_;
    print $FileHandle $Message;
});
Input
$Mode (string)
file open mode, see "perldoc opn", for example: '', '>>'
$FileName (string)
file name
$Sub (code ref)
code to execute while the file is open

PathGlob2TypeGlob

Changes $Path from path glob (as a/*/z/??) to type glob (as a\/.+\/z\/..)

Syntax
$Path = PathGlob2TypeGlob($Path)
Input
$Path (string)
directory
Return
$Path (string)
directory

RealPath

Converts paths like 'C:/sub1/sub2/..' to 'C:/sub1'.

Syntax
$DetPath = RealPath($Path);
Input
$Path (string)
directory path
Return
$DetPath (string)
directory path

RebuildDirectory

Copies files which exist in the source and backup directory and have the same modification time in source and target from the backup to the target directory. Deletes the backup file if it was copied.

Syntax
RebuildDirectory( $SourceDir, $TargetDir, $BackupDir, $Flags );
Input
$SourceDir (string)
source directory
$TargetDir (string)
target directory
$BackupDir (string)
backup directory
$Flags (hash ref)
flags to modify the behaviour of RebuildDirectory.
The following flags can be used:
  • ignore - Ignore files with path names (quoted) relative to $SourceDir
  • recursive - rebuilds directory recursively
  • stat - defines how to handle UNIX file attributes:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)

RebuildFile

Deletes TargetFile if TargetFile and SourceFile exist and are equal. Moves BackupFile to TargetFile if BackupFile exists.

Syntax
RebuildFile( $SourceFile, $TargetFile, $BackupFile, $Flags );
Input
$SourceFile (string)
source file
$TargetFile (string)
target file
$BackupFile (string)
backup file
$Flags (hash ref)
flags to modify the behaviour of RebuildFile.
The following flag can be used:
  • stat - defines how to handle UNIX file attributes:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)

RelativePath

Returns the relative path to get from $BasePath to $RelatingPath. All output slashes are converted to /.

Syntax
$Path = RelativePath( $BasePath, $RelatingPath );
Example
$Path = RelativePath( 'C:\Windows\System32', 'C:\Windows\Fonts');
# $Path == '../Fonts';
Input
$BasePath (string)
absolute base path
$RelatingPath (string)
absolute path to use get the relative path to base path
Return
$RelativePath (string)
the relative path

RenameDirectory

Returns true if the directory was renamed. Returns false if the source directory does not exist. Throws an error if the source directory exists, but could not be renamed.

Syntax
$Renamed = RenameDirectory($Source, $Target);
$Renamed = RenameDirectory($Source, $Target, $hFlags);
Example
RenameDirectory('C:\\Test\OldDirName','C:\\Test\NewDirName', { create_directory => 1 });
Input
$Source (string)
old directory name
$Target (string)
new directory name
$Flags (hash ref)
flags to modify the behaviour of RenameDirectory.
The following flags can be used:
  • create_directory - create directory or not?
  • stat - defines how to handle UNIX file attributes:
    - epages: set file attributes according to epages rules
    (this is the default behaviour unless flag is defined)
    - preserve: file attributes remain the same
    - ignore: do not set file attributes (makes function faster)

Return
$Renamed (boolean)
true if the directory was renamed, otherwise false

ResolveSymbolicLink

Returns resolved link of path if it exists, otherwise it returns path.

Syntax
$ResolvedLink = ResolveSymbolicLink($Path);
Input
$Path (string)
directory/file path
Return
$SymbolicPart (string)
directory/file path

RunOnDirectory

execute the given function on specific folder and returns the result of given function.

Syntax
$Result = RunOnDirectory($FolderName, $Sub);
Example
my $aOldFiles = RunOnDirectory($OldFolder,
    sub{
        my $aFiles = GetFileNames( undef , {'recursive' => 1} );
        return $aFiles;
    }
);
Input
$Directory (string)
name of folder to run
$Function (coderef)
reference to function that would be executed
Return
$Return (array/scalar)
return the value of given function

RunOnGlob

execute function $Sub for files matching $GlobPattern in $Directory

Syntax
$Result = RunOnGlob($Directory, $GlobPattern, $Sub, $hFlags);
Example
RunOnGlob($XmlDir, 'Hooks*.xml', sub { DeleteHooks($_) }, {reverse => 1});
Input
$Directory (string)
name of folder to run
$GlobPattern (string)
glob pattern
$Sub (coderef)
reference to function that would be executed
$hFlags (ref.hash)
flags
  • reverse - execute function for each file in reverse order
  • force - ignore errors (just warn)

Return
$Return (array/scalar)
return the value of given function

SameDevice

Tests if $Path1 and $Path2 exist on same device. Returns 0 if $Path1 and/or $Path2 do not exist. Returns 0 if $Path1 and/or $Path2 are UNC paths. Returns 0 if $Path1 and/or $Path2 exist on different mount points.

Syntax
$OnSameDevice = SameDevice($Path1, $Path2);
Input
$Path1 (string)
path to compare
$Path2 (string)
path to compare
Return
$OnSameDevice (boolean)
1 - $Path1 and $Path2 exist on same device; 0 -otherwise

SetAccessRights

Changes access rights (chmod and chown) for unix fallbacks for undefined fields:
- UserID: get UID from User
- User: default owner (depends on path of $FileName)
- GroupID: get GID from Group
- Group: default group (depends on path of $FileName)
- ExecBit: -d $FileName ? 1 : 0
- Mode: default mode (depends on path of $FileName) plus ExecBit. Does nothing if:
- function is executed under Windows - $FileName does not exist
- none of $hFlags (UserID GroupID Mode aTime mTime) is defined AND (stat eq ignore OR $FileName is outside of $EPAGES)

Syntax
SetAccessRights($FileName, $hFlags);
Input
$FileName (string)
file to be modified
$hFlags (ref.hash)
flags
  • Mode - constant as defd in DE_EPAGES::Core::API::Constants
  • ExecBit - 0: remove EXECUTE_BIT
    - 1: add EXECUTE_BIT
    - 2: add EXECUTE_BIT (even if digit == 0)
  • UserID - user ID - integer
  • GroupID - group ID - integer
  • User - user name - string
  • Group - group name - string
  • aTime - access time (seconds since 1.1.1970 UTC)
  • mTime - modified time (seconds since 1.1.1970 UTC)
  • stat - return if !$KnownAccessRights and stat eq ignore

Text2Dos

Checks if text and moves newlines to UNIX style newlines.

Syntax
Text2Dos($FileName, $Force);
Input
$FileName (string)
file to be modified
$Force (integer)
file is changed even if is is a binary (opt.)

Text2Unix

Checks if text and moves newlines to UNIX style newlines.

Syntax
Text2Unix($FileName, $Force);
Input
$FileName (string)
file to be modified
$Force (integer)
file is changed even if is is a binary (opt.)

WindowsPath

Replaces slashes of an unix path with back-slashes.

Syntax
$WindowsPath = WindowsPath($AnyPath);
Input
$AnyPath (string)
directory/file path (unix/windows format)
Return
$WindowsPath (string)
directory/file path (windows format)

WriteFile

Writes a file to disk. Several options are accepted for modifying the write behaviour. ErrorCodes:

Syntax
WriteFile($FileName, $rContent, $hFlags);
Example
WriteFile('/var/log/error.log', \$Content, { binary=>1, create_directory=>1} );
Input
$FileName (string)
name of file
$rContent (ref.string)
new content of file
$hFlags (hash ref)
flags to modify the behaviour of WriteFile. The following flags
can be used:
  • create_directory - automatically create the directory if
    it doen't exist
  • append - append to the end of the file instead of
    deleting the previous content
  • binary - don't convert newlines
  • flock - block access to the file during the write operation
  • syswrite - uses 'syswrite' instead of 'print'
  • utf8 - writes the stream using perl's internal encoding
  • encoding - character encoding, default: 'iso-8859-1'
  • usebom - write a byte order mark for unicode files if 'utf8' or
    encoding =~ /^utf/i
  • ignore_error - don't die if write or create directory fails

    (additionally all flags as defd in SetAccessRights)

fsplit

This function splits a path into its parts, this works for unix and dos paths. Parts, not present, are returned empty or undef.

Syntax
($Path, $FileName, $Extension) = fsplit($FilePath);
Example
('/', 'roedel', '.txt') = fsplit('/roedel.txt');<br>
('/', 'roedel', undef ) = fsplit('/roedel');<br>
('.', 'roedel', '.txt') = fsplit('roedel.txt');<br>
('c:/epages', 'roedel', '.txt') = fsplit('c:/epages/roedel.txt');
('\\server\share', 'roedel', '.txt') = fsplit('\\server\share\roedel.txt');
Input
$FilePath
A complete file path.
Return
$Path (string)
path to file
$File (string)
file name without extension
$Extension (string)
file extension (includes '.'), '' if the file name does
not contain a dot