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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/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.nnThe new schedule is $time_interpolation old.nnIt 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);
  
}

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *