Search form

Perl File Change Notifier

This notifies users by email (sendmail) when a particular file changes on a Unix-style filesystem. This was originally written for a page that was being modified by multiple people in the wiki software shipped with Appleā€™s OS X Server. This worked all right as a hack, but if you need extensive content management or granular permissions, I'd find a more sophisticated platform than Apple's wiki.

#!/usr/bin/perl -cw
#
# Check for updates to page.html, send email if 'modified' timestamp is within last 24 hours 
 
# Put your file paths and email addresses here, example: 
$file = "/Library/Collaboration/Groups/OurGroup/page.html";
$email_to = "me@yahoo.com";
$cc_to = "you@yahoo.com";
$email_from = "them@yahoo.com";
$URL = "usable web link to the page";

# set some default values
my $now = time;
$. = 0;
 
# Determine how old the file is
my $mtime = (lstat $file)[9];
my @diff = reverse +(gmtime $now - $mtime)[0 .. 5];
 
# Adjust year and day for Unix epoch
$diff[0] -= 70;
$diff[2]--;
 
# Determine if maintainer made the last change
open (FILE, "</Library/Collaboration/Groups/OurGroup/page.plist");
do { $LINE = <FILE> } until $. == 18 || eof;
#print $LINE;
$LINE =~ s/^s+//;
$LINE =~ s/s+$//;
$LINE =~ s/<string>//;
$LINE =~ s/</string>//;
close FILE;
 
# Put your file owner and mail recipients here
if ($diff[2] < 1 and $diff[1] < 1 and $diff[0] < 1 and $LINE ne "JohnDoe") {
     
    # i.e., file is less than 1 year, 1 month, and 1 day old,
    # and wasn't last updated by the maintainer
 
    $mailto = $email_to;
    $mailcc = $cc_to;
    $mailfrom = $email_from;
    $mailsubject = "Schedule Updated";
    $time_interpolation = sprintf("%d year%s, %d month%s, %d day%s, %d hour%s, %d minute%s and %d second%s", map { $_ == 1 ? ($_, '') : ($_, 's') } @diff);
 
    $mailbody = "The schedule ($URL) was modified in the last 24 hours.\n\nThe new schedule is $time_interpolation old.\n\nIt was last updated by $LINE.";
 
    &sendEmail($mailto, $mailcc, $mailfrom, $mailsubject, $mailbody);
    #print("$mailto, $mailcc, $mailfrom, $mailsubject, $mailbody");
 
} else {
 
    die();
     
}
 
sub sendEmail {
 
    my ($to, $cc, $from, $subject, $message) = @_;
    my $sendmail = '/usr/sbin/sendmail';
    open(MAIL, "|$sendmail -oi -t");
    print MAIL "From: $fromn";
    print MAIL "To: $ton";
    print MAIL "Cc: $ccn";
    print MAIL "Subject: $subjectnn";
    print MAIL "$messagen";
    close(MAIL);
 
}

Categories: