writeAccountSize.pl

From Sepiola Wiki
Jump to: navigation, search
#!/usr/bin/perl -w
#
# Copyright (C) 2011 stepping stone GmbH
#                    Switzerland
#                    http://www.stepping-stone.ch
#                    support@stepping-stone.ch
#
# Authors:
#  Michael Rhyner <michael.rhyner@stepping-stone.ch>
#  
# Licensed under the EUPL, Version 1.1 or – as soon they
# will be approved by the European Commission - subsequent
# versions of the EUPL (the "Licence");
# You may not use this work except in compliance with the
# Licence.
# You may obtain a copy of the Licence at:
#
# http://www.osor.eu/eupl
#
# Unless required by applicable law or agreed to in
# writing, software distributed under the Licence is
# distributed on an "AS IS" basis,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied.
# See the Licence for the specific language governing
# permissions and limitations under the Licence.
#
# $Id$
#
#
######################################################################################################
# writeAccountSize.pl
######################################################################################################
# Description
#  This script writes the current account size into a file for each account
#  This information can be used by client software or other scripts.
######################################################################################################
 
######################################################################################################
# Incorporate code with use (evaluates the included file at compile time).
######################################################################################################
use warnings;
use strict;
use Config::IniFiles;
use Getopt::Std;
use Sys::Syslog;
 
# This defines the variables in the symbol table of the current package.
use vars qw($opt_d $opt_C $opt_D $opt_U $opt_h $totalQuota $usedQuota $incomingSize $snapshotsSize);
 
$| = 1;                        # Turn buffering off, so that the output is flushed immediately
 
######################################################################################################
# Start the POD documentation information
######################################################################################################
=pod
 
=head1 NAME
 
writeAccountSize.pl
 
=head1 DESCRIPTION
 
This Script gets quota information from filesystem, size of incoming and (optionally) snapshots directories, optionally write the data to a file and sends an e-mail message for each account that is over quota to users e-mail address (from ldap directory) or to a fixed e-mail address.
 
The configuration file for this script is stored in the same directory
and is called writeAccountSize.conf.
 
The script needs access to the quota program to get quota information.
The script needs ldap access to get users e-mail address.
The script uses syslog for logging purposes.
 
Command Line Interface (CLI) parameters:
 
=over
 
=item -C configfile
 
The configuration file.
 
=item -D directory
 
The users home directory.
 
=item -U uid
 
The user id.
 
=item -d debug
 
Turns the debug mode on.
 
=item -h help
 
This online help.
 
=back
 
=head1 USAGE
 
writeAccountSize.pl [-C configuration file] [-D directory] [-U uid ] [-d debug] [-h help]
 
=head1 CREATED
 
2009-04-16 michael.rhyner@stepping-stone.ch created
 
=head1 VERSION
 
=over
 
=item 2009-04-16 michael.rhyner@stepping-stone.ch created
 
=item 2009-04-30 michael.rhyner@stepping-stone.ch changed position based quota output parsing with correctly parsed elements
 
=item 2009-06-15 michael.rhyner@stepping-stone.ch added over quota check and sending e-mail
 
=item 2009-06-16 michael.rhyner@stepping-stone.ch renamed script and make it more general usable (e.g. for online backup, online storage, ...)
 
=item 2009-06-17 michael.rhyner@stepping-stone.ch changed mail message to read from a text file instead from configuration parameter
 
=item 2009-06-18  michael.rhyner@stepping-stone.ch corrected wrong regex to weed out the asterisk (*) in getQuotaSize
 
=item 2009-06-19  michael.rhyner@stepping-stone.ch corrected wrong evaluation success from subroutines and avoid message output when not in debug mode
 
=item 2009-06-22  michael.rhyner@stepping-stone.ch getQuotaSize: return immediately if no quota was set
 
=item 2009-06-24  michael.rhyner@stepping-stone.ch alert when used certain percentge of allowed space instead of more than allowed space
 
=item 2009-06-26  michael.rhyner@stepping-stone.ch values are presented in Gigabytes within notification message
 
=item 2009-07-23  michael.rhyner@stepping-stone.ch corrected wrong syslog severities for errors 
 
=item 2009-07-24  michael.rhyner@stepping-stone.ch made e-mail address available within message body
 
=back
 
=head1 INCORPORATED CODE
 
Incorporate code with use:
 
=over
 
=over
 
=item warnings;
 
=item strict;
 
=item Config::IniFiles;
 
=item Getopt::Std;
 
=item Sys::Syslog;
 
=back
 
=back
 
=cut
 
######################################################################################################
# End the POD documentation information
######################################################################################################
 
######################################################################################################
# Process the single character command line arguments.
######################################################################################################
getopts('dC:D:U:h');
 
######################################################################################################
# Read the configuration file
######################################################################################################
 
my $cfg;
if ($opt_C) {
  $cfg = Config::IniFiles->new( -file => $opt_C);
} else {
  $cfg = Config::IniFiles->new( -file => "writeAccountSize.conf");
}
 
######################################################################################################
# Variable definitions
######################################################################################################
my $debug             = 0;   # Debug modus: 0: off, 1: on
 
my $incomingDirectory   = $cfg->val('Global', 'INCOMING_DIRECTORY');
my $accountSizeFile    = $cfg->val('Global', 'ACCOUNT_SIZE_FILE');
my $syslogName        = $cfg->val('Syslog', 'SYSLOG');
my $accountSizeFileMode = 0644;
my $ldapServer        = $cfg->val('Directory', 'LDAP_SERVER');
my $ldapBindDN        = $cfg->val('Directory', 'LDAP_BIND_DN');
my $ldapBindPw        = $cfg->val('Directory', 'LDAP_BIND_PW');
my $ldapBaseDN        = $cfg->val('Directory', 'LDAP_BASE_DN');
my $ldapEmailAttribute = $cfg->val('Directory', 'LDAP_EMAIL_ATTRIBUTE');
my $emailSender       = $cfg->val('Notification', 'EMAIL_SENDER');
my @emailCCRecipient;
$emailCCRecipient[0]  = $cfg->val('Notification', 'EMAIL_CC_RECIPIENT');
my $emailToRecipient = $cfg->val('Notification', 'EMAIL_TO_RECIPIENT');
my %emailSubjects;
$emailSubjects{'EN'}     = $cfg->val('Notification', 'EMAIL_SUBJECT_EN');
$emailSubjects{'GE'}     = $cfg->val('Notification', 'EMAIL_SUBJECT_GE');
$emailSubjects{'FR'}     = $cfg->val('Notification', 'EMAIL_SUBJECT_FR');
$emailSubjects{'IT'}     = $cfg->val('Notification', 'EMAIL_SUBJECT_IT');
my %emailMessageFiles;
$emailMessageFiles{'EN'}  = $cfg->val('Notification', 'EMAIL_MESSAGE_FILE_EN');
$emailMessageFiles{'GE'}  = $cfg->val('Notification', 'EMAIL_MESSAGE_FILE_GE');
$emailMessageFiles{'FR'}  = $cfg->val('Notification', 'EMAIL_MESSAGE_FILE_FR');
$emailMessageFiles{'IT'}  = $cfg->val('Notification', 'EMAIL_MESSAGE_FILE_IT');
my $snapshots = $cfg->val('Global', 'SNAPSHOTS');
my $defaultLanguage       = $cfg->val('Notification', 'EMAIL_DEFAULT_LANGUAGE');
my $emailAlertThreshold   = $cfg->val('Notification', 'EMAIL_ALERT_THRESHOLD');
 
######################################################################################################
# Help text
######################################################################################################
my $help = "\nPlease use pod2text $0 for the online help\n\n";
 
######################################################################################################
# Error Messages
######################################################################################################
my $errorHomeDirectory = "\nPlease pass a users home directory to the script\n\n";
my $errorUserID = "\nPlease pass a user ID to the script\n\n";
 
######################################################################################################
# Main Programme
######################################################################################################
 
# Start logging
openlog ($syslogName, 0, 'root');
syslog('info', "$0 started");
 
# Check the command line arguments
checkCommandLineArguments();
 
# Make sure, that the users home directory exists
if (!checkUsersHomeDirectory($debug, $opt_D)) { exit 1; }
 
# Make sure, that the users backup directory exists
if (!checkUsersIncomingDirectory($debug, $opt_D, $incomingDirectory)) { exit 1; }
 
# Get the current quota
($totalQuota,$usedQuota) = getQuotaSize($debug, $opt_U);
exit 1 if ( ($totalQuota < 0) && ($usedQuota < 0) );
 
# Get the current incoming size
$incomingSize = getIncomingSize($debug, $opt_D, $incomingDirectory);
exit 1 if ($incomingSize < 0);
 
if ($snapshots == 1) {
  # Get the current size of the snapshots
  $snapshotsSize = getSnapshotsSize($debug, $usedQuota, $incomingSize);
  exit 1 if ($snapshotsSize < 0);
} else {
  $snapshotsSize = 0;
}
 
my $chrootPath = join('/',(split(/\//,$opt_D))[0..7]);
 
if ($accountSizeFile ne "") {
  # Write the values into a file
  if ($debug) {
    print "Debug writeAccountSize: Working on $chrootPath$accountSizeFile\n";
  } # End of if ($debug)        
  syslog ('info', "writeAccountSize: Working on $chrootPath$accountSizeFile");
 
  my $quotaLine = round($totalQuota/1024) . " " . round($incomingSize/1024) . " " . round($snapshotsSize/1024);
 
  if (! open ACCOUNTSIZEFILE, ">$chrootPath$accountSizeFile") { exit 1; }
 
  print ACCOUNTSIZEFILE "$quotaLine";
 
  if ($debug) {
    print "Debug: wrote $quotaLine to $chrootPath$accountSizeFile\n";
  } # End of if ($debug)
  syslog ('info', "wrote $quotaLine to $chrootPath$accountSizeFile");
 
  close ACCOUNTSIZEFILE;
  chmod ($accountSizeFileMode, "$chrootPath$accountSizeFile");
}
 
# Check if quota is reached and send message to user
if (100/$totalQuota*$usedQuota >= $emailAlertThreshold) {
  my @userEmailAddress;
  my $ldap_email = getLDAPValue ($ldapServer,$ldapBindDN,$ldapBindPw,$ldapBaseDN,$opt_U, $ldapEmailAttribute);
  # Check if e-mail address should be replaced by the one within LDAP directory
  if ($emailToRecipient =~ /\@EMAILADDR\@/) {
    $emailToRecipient =~ s/\@EMAILADDR\@/$ldap_email/;
  }
  $userEmailAddress[0] = $emailToRecipient;
 
  my $emailSubject = $emailSubjects{$defaultLanguage};
  # replace UID Placeholder with real User ID
  $emailSubject =~ s/\@UID\@/$opt_U/g;
 
  # compose message body
  my $emailMessage = composeMessageBody (\%emailMessageFiles, $defaultLanguage, $ldap_email);
 
  print "Sending E-Mail to: " . $userEmailAddress[0] . "\n" if $debug;
  my $result = sendMessage ($emailSender,\@userEmailAddress,\@emailCCRecipient,$emailSubject,$emailMessage);
 
  if ($result == 0) {
    if ($debug) {
      print "Debug: Successfully sent quota notification message\n";
    } # End if if ($debug)  
 
    # Write some information to the syslog daemon
    syslog ('info', "Successfully sent quota notification message");
  } else {
    if ($debug) {
      print "Debug: Failed to send quota notification message\n";
    } # End if if ($debug)  
 
    # Write some information to the syslog daemon
    syslog ('err', "Failed to send quota notification message");
  }
}
 
syslog('info', "$0 successfully finished");
 
######################################################################################################
# Subroutines
######################################################################################################
 
######################################################################################################
# checkCommandLineArguments
######################################################################################################
# Description:
#  Check the single character command line arguments
######################################################################################################
sub checkCommandLineArguments{
 
  # Check, if help was chosen. If yes, display help and exit
  if ($opt_h){
    print $help;
    exit 1;
  } # End of if ($opt_h)
 
  # Check, if debug modus was chosen
  if ($opt_d){
    $debug = "1";
    print "Debug modus was turned on\n";
    syslog('debug', "Debug modus was turned on");
  } # End of if ($opt_d)
 
  # Check, if the users home directory was passed
  if (!$opt_D){
    print $errorHomeDirectory;
    syslog('err', "No users home directory was passed to $0");
    exit 1;
  } # End of if ($opt_d)
 
  # Check, if the user id was passed
  if (!$opt_U){
    print $errorUserID;
    syslog('err', "No user id was passed to $0");
    exit 1;
  } # End of if ($opt_u)
 
} # End of sub checkCommandLineArguments
 
######################################################################################################
# checkUsersHomeDirectory
######################################################################################################
# Description:
#  Checks, if the passed users home directory exists. 
######################################################################################################
# Usage:
#   checkUsersHomeDirectory($debug,$opt_D);
# Example:  
#   my $result = checkUsersHomeDirectory("1","/var/backup/7/687/723/3723687/chroot","3723687");
# Return values:
#  0: if the users home directory exists
#  1: if the users home directory does not exist
######################################################################################################
sub checkUsersHomeDirectory {
 
  my $localDebug = $_[0];
  my $localUsersHomeDirectory = $_[1];
 
  if ($localDebug) {
    print "\n";
    print "Debug sub checkUsersHomeDirectory: \$localUsersHomeDirectory: $localUsersHomeDirectory\n";
    syslog ('debug', "sub checkUsersHomeDirectory: \$localUsersHomeDirectory: $localUsersHomeDirectory");
  } # End if if ($localDebug)  
 
  if (-d $localUsersHomeDirectory) {
    if ($localDebug) {
      print "Debug sub checkUsersHomeDirectory: The \$localUsersHomeDirectory $localUsersHomeDirectory exists\n";
    } # End if if ($localDebug)  
 
    # Write some information to the syslog daemon
    syslog ('info', "sub checkUsersHomeDirectory: The \$localUsersHomeDirectory $localUsersHomeDirectory exists");
 
    # Return true, if the users home directory exists
    return 1;
  } else {
    # Return false, if the users home directory doesn't exist
    return 0;
  } # End of if (-d $localUsersHomeDirectory)  
} # End of sub checkUsersHomeDirectory
 
######################################################################################################
# checkUsersIncomingDirectory
######################################################################################################
# Description:
#  Checks, if the passed users backup directory exists.
######################################################################################################
# Usage:
#   checkUsersIncomingDirectory($debug,$opt_D,$incomingDirectory);
# Example:
#   my $result = checkUsersIncomingDirectory("1","/var/backup/7/687/723/3723687/chroot","/incoming");
# Return values:
#  0: if the users home directory exists
#  1: if the users home directory does not exist
######################################################################################################
sub checkUsersIncomingDirectory {
 
  my $localDebug = $_[0];
  my $localUsersHomeDirectory = $_[1];
  my $localUsersIncomingDirectory = $_[2];
  my $localIncomingPath = "$localUsersHomeDirectory$localUsersIncomingDirectory";
 
  if ($localDebug) {
    print "\n";
    print "Debug sub checkUsersIncomingDirectory: \$localUsersHomeDirectory:   $localUsersHomeDirectory\n";
    syslog ('debug', "sub checkUsersIncomingDirectory: \$localUsersHomeDirectory:   $localUsersHomeDirectory");
    print "Debug sub checkUsersIncomingDirectory: \$localUsersIncomingDirectory: $localUsersIncomingDirectory\n";
    syslog ('debug', "sub checkUsersIncomingDirectory: \$localUsersIncomingDirectory: $localUsersIncomingDirectory");
    print "Debug sub checkUsersIncomingDirectory: \$localIncomingPath:           $localIncomingPath\n";
    syslog ('debug', "sub checkUsersIncomingDirectory: \$localIncomingPath:           $localIncomingPath");
    print "\n";
  } # End if if ($localDebug)
 
  if (-d $localIncomingPath) {
    if ($localDebug) {
      print "Debug sub checkUsersIncomingDirectory: The \$localIncomingPath $localIncomingPath exists\n";
    } # End if if ($localDebug)
 
    # Write some information to the syslog daemon
    syslog ('info', "sub checkUsersHomeDirectory: The \$localIncomingPath $localIncomingPath exists");
 
    # Return true, if the users home directory exists
    return 1;
  } else {
    # Return false, if the users home directory doesn't exist
    return 0;
  } # End of if (-d $localIncomingPath)
} # End of sub checkUsersIncomingDirectory
 
######################################################################################################
# getIncomingSize
######################################################################################################
# Description:
#   Get backup size for a certain user account
#   For example:
#     231
#   /var/backup/5/705/723/3723705/chroot/./home/3723705 : The users home directory
#   /incoming                                           : The users backup directory
######################################################################################################
# Usage:
#   getIncomingSize($debug, $opt_D, $incomingDirectory)
# Example:
#   my $incomingSize = getIncomingSize("1","/var/backup/7/687/723/3723687/chroot","/incoming");
# Return values:
#  <size in KB>: if backup size can be retrieved successfully
#  -1: If the backup size cannot be determined
######################################################################################################
sub getIncomingSize {
 
  my $localDebug = $_[0];
  my $localUsersHomeDirectory = $_[1];
  my $localUsersIncomingDirectory = $_[2];
  my $localIncomingPath = "$localUsersHomeDirectory$localUsersIncomingDirectory";
  my $localDuCmdPath = "/usr/bin/du";
 
  if ($localDebug) {
    print "Debug sub getIncomingSize: \$localUsersHomeDirectory:   $localUsersHomeDirectory\n";
    syslog ('debug', "sub getIncomingSize: \$localUsersHomeDirectory:   $localUsersHomeDirectory");
    print "Debug sub getIncomingSize: \$localUsersIncomingDirectory: $localUsersIncomingDirectory\n";
    syslog ('debug', "sub getIncomingSize: \$localUsersIncomingDirectory: $localUsersIncomingDirectory");
    print "Debug sub getIncomingSize: \$localIncomingPath:           $localIncomingPath\n";
    syslog ('debug', "sub getIncomingSize: \$localIncomingPath:           $localIncomingPath");
  } # End if ($localDebug)
 
  my $localIncomingSize=((split(/\t/,`$localDuCmdPath -ks $localIncomingPath`))[0])*1;
  if ( $? == 0) {
    if ($localDebug) {
      print "Debug sub getIncomingSize: Successfully got $localIncomingSize KB for $localIncomingPath\n";
    }
    syslog ('info', "sub getIncomingSize: Successfully got $localIncomingSize KB for $localIncomingPath");
  } else {
    if ($localDebug) {
      print "Debug sub getIncomingSize: Failed getting backup size for $localIncomingPath\n";
    }
    syslog ('err', "sub getIncomingSize: Failed getting backup size for $localIncomingPath");
    $localIncomingSize = -1;
  };
 
  return $localIncomingSize;
 
} # End if sub getIncomingSize
 
######################################################################################################
# getQuotaSize
######################################################################################################
# Description:
#   Get quota size for a certain user account
#   For example:
#     5120,699
######################################################################################################
# Usage:
#   getQuotaSize($debug, $opt_U)
# Example:
#   my ($totalQuota,$usedQuota = getQuotaSize("1","3723705");
# Return values:
#  <size of total quota in KB>, <size of used quota in KB>: if quota size can be retrieved successfully
#  -1: If the quota size cannot be determined
######################################################################################################
sub getQuotaSize {
  my $localDebug = $_[0];
  my $localUserID = $_[1];
  my $localQuotaCmdPath = "/usr/bin/quota";
  my $localQuotaOutput;
  my $localTotalQuota;
  my $localUsedQuota;
 
  if ($localDebug) {
    print "Debug sub getQuotaSize: \$localUserID:   $localUserID\n";
    syslog ('debug', "sub getQuotaSize: \$localUserID:   $localUserID");
  } # End if ($localDebug)
 
    my $localQuotaCmdOutput = `$localQuotaCmdPath -u $localUserID -w`;
    return (-1, -1) if ($localQuotaCmdOutput =~ /Disk quotas for user .+ \(uid .+\): none/);
    my @localQuotaOutput = split(/ +/,(split(/\n/,$localQuotaCmdOutput))[2]);
  if ($localDebug) {
    print "Debug sub getQuotaSize: Successfully got \"@localQuotaOutput\" as quota command output\n";
    syslog ('debug', "sub getQuotaSize: Successfully got \"@localQuotaOutput\" as quota command output");
  }
 
  if ( $? >= 0) {
    $localTotalQuota=$localQuotaOutput[3];
    $localUsedQuota=$localQuotaOutput[1];
    $localUsedQuota =~ s/([0-9]+).*/$1/;
    if ($localDebug) {
      print "Debug sub getQuotaSize: Successfully got $localTotalQuota KB, $localUsedQuota KB for $localUserID\n";
    }
    syslog ('info', "sub getQuotaSize: Successfully got $localTotalQuota KB, $localUsedQuota for $localUserID");
  } else {
    if ($localDebug) {
      print "Debug sub getQuotaSize: Failed getting quota information for $localUserID\n";
    }
    syslog ('err', "sub getQuotaSize: Failed getting quota information for $localUserID");
    $localTotalQuota = -1;
    $localUsedQuota = -1;
  };
 
  return ($localTotalQuota, $localUsedQuota);
}
 
######################################################################################################
# getSnapshotsSize
######################################################################################################
# Description:
#   Get snapshots size for a certain user account
#   For example:
#     468 
######################################################################################################
# Usage:
#   getSnapshotsSize($debug, $usedQuota, $incomingSize)
# Example:
#   my ($snapshotsSize = getSnapshotsSize("1","699","231");
# Return values:
#  <size in KB>: if snapshots size can be calculated successfully
#  -1: If the snapshots size cannot be determined
######################################################################################################
sub getSnapshotsSize {
  my $localDebug = $_[0];
  my $localUsedQuota = $_[1];
  my $localIncomingSize = $_[2];
 
  if ($localDebug) {
    print "Debug sub getSnapshotsSize: \$localUsedQuota:   $localUsedQuota\n";
    syslog ('debug', "sub getSnapshotsSize: \$localIncomingSize:   $localIncomingSize");
  } # End if ($localDebug)
 
  my $localSnapshotsSize = $localUsedQuota - $localIncomingSize;
 
  if ($localSnapshotsSize >= 0) {
    if ($localDebug) {
      print "Debug sub getSnapshotsSize: \$localSnapshotsSize:   $localSnapshotsSize\n";
    } # End if ($localDebug)
    syslog ('info', "sub getSnapshotsSize: \$localSnapshotsSize:   $localSnapshotsSize");
  } else {
    if ($localDebug) {
      print "Debug sub getSnapshotsSize: Got impossible snapshots size\n";
    }
    syslog ('err', "sub getSnapshotsSize: Got impossible snapshots size");
  }
 
  return $localSnapshotsSize;
 
}
 
######################################################################################################
# round
######################################################################################################
# Description:
# Rounds a float to an integer
######################################################################################################
# Usage: round (float)
# Example: round (3.14)
# Return values: <integer>
######################################################################################################
sub round {
  my($number) = shift;
  return int($number + .5);
}
 
######################################################################################################
# getLDAPValue
######################################################################################################
# Description:
# Retrieves a value of an attribute of a certain entry from an LDAP directory
######################################################################################################
# Usage: getLDAPValue <ldap server>, <bind dn>, <bind pw>, <dn of entry>, <attribute>
# Example: getLDAPValue ldapm.stepping-stone.ch, 'cn=manager, o=example, c=org', 'secret', 'uid=3729999,ou=people,ou=backup,ou=service,o=example,c=org', 'cn'
# Return values: <string> if value could be retrieved
#               -1 if retrival of value failed
######################################################################################################
sub getLDAPValue {
  my ($ldapserver,$binddn,$bindpw,$basedn,$uid,$attr) = @_;
  my $retval;
  my $mesg;
 
  use Net::LDAP;
  my $ldap = Net::LDAP->new( $ldapserver ) or die "$@";
  $mesg = $ldap->bind( $binddn,
                       password => $bindpw );
 
  $mesg = $ldap->search ( base => $basedn,
                          filter => "(uid=$uid)"
                        );
 
  $mesg->code && die $mesg->error;
 
  foreach my $entry ($mesg->entries) {
  #  $entry->dump;
    $retval = $entry->get_value ($attr);
  }
 
  $mesg = $ldap->unbind;   # take down session
 
  return $retval;
 
}
 
######################################################################################################
# sendMessage
######################################################################################################
# Description:
# Sends an e-mail message to the user
######################################################################################################
# Usage: sendMessage <sender address>, <to address(es)>, <cc address(es)>, <subject>, <message>
# Example: sendMessage support@stepping-stone.ch, user@example.org, other_user@example.org, "Quota Warning", "Your account is over quota"
# Return values: 0 if sending of message succeeded
#               -1 if sending of message failed
######################################################################################################
sub sendMessage {
  use MIME::Lite;
   my $sender = $_[0];
   my $to_list;
   for my $recipient (@{$_[1]}){
     $to_list = $to_list . $recipient;
     $to_list = $to_list . "," if ( \$recipient != \${$_[1]}[-1]);
   }
   my $cc_list;
   for my $recipient (@{$_[2]}){
     $cc_list = $cc_list . $recipient;
     $cc_list = $cc_list . "," if ( \$recipient != \${$_[2]}[-1]);
   }
   my $subject = $_[3];
   my $message = $_[4];
 
   ### Create a new single-part message
   my $msg = MIME::Lite->new(
       From     => $sender,
       To       => $to_list,
       Cc       => $cc_list,
       Subject  => $subject,
       Type     => 'text/plain; charset=UTF-8',
       Encoding => 'quoted-printable',
       Data     => $message
  );
  if ($msg->send) {
    return 0;
  } else {
    return -1;
  }
 
}
 
######################################################################################################
# composeMessageBody
######################################################################################################
# Description:
# Prepares an e-mail message
######################################################################################################
# Usage: composeMessageBody <message file table> <language> <e-mail address>
# Example: composeMessageBody %email_message_file 'EN' 'user@example.org'
# Return values: message to be sent
#                -1 if the message file cannot be read
######################################################################################################
sub composeMessageBody {
  my %localMsgfilemap = %{$_[0]};
  my $localLang = $_[1];
  my $localEmailAddress = $_[2];
  my $localRetval = "";
  my $localMsgbody;
 
  # open appropriate message file for given language
  if (! open (FH, '<', $localMsgfilemap{$localLang}) ) {
    $localRetval = "-1";
 
  if ($debug) {
    print "Failed to open " . $localMsgfilemap{$localLang} . "\n";
  } # End if ($localDebug)
  syslog ('debug', "Failed to open " . $localMsgfilemap{'$localLang'});
 
  }
 
  while (<FH>) {
    $localMsgbody .= $_;
  }
 
  close (FH);
 
  my $localUsedQuota = sprintf("%.2f",$usedQuota/1024/1024);
  my $localTotalQuota = sprintf("%.2f",$totalQuota/1024/1024);
  my $localIncomingSize = sprintf("%.2f",$incomingSize/1024/1024);
  my $localSnapshotsSize = sprintf("%.2f",$snapshotsSize/1024/1024);
  my $localUsedPercent = round (100/$totalQuota*$usedQuota);
  # replace quota placeholders with really used values
  $localMsgbody =~ s/\@UID\@/$opt_U/g;
  $localMsgbody =~ s/\@USEDQUOTA\@/$localUsedQuota/g;
  $localMsgbody =~ s/\@TOTALQUOTA\@/$localTotalQuota/g;
  $localMsgbody =~ s/\@INCOMINGSIZE\@/$localIncomingSize/g;
  $localMsgbody =~ s/\@SNAPSHOTSSIZE\@/$localSnapshotsSize/g;
  $localMsgbody =~ s/\@USEDPERCENT\@/$localUsedPercent/g;
  $localMsgbody =~ s/\@EMAILADDR\@/$localEmailAddress/g;
 
  if ($localRetval ne "-1") {
    $localRetval = $localMsgbody;
  }
 
  return $localRetval;
}

Back to Backup server set up

Personal tools
Namespaces

Variants
Actions
Navigation
Wiki
sepiola.org
Toolbox