Subversion Repositories computer_asset_manager_v1

Rev

Rev 5 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 rodolico 1
<?php
2
 
3
/*
4
 * getSysinfoMail.php
5
 * 
6
 * Author: R. W. Rodolico
7
 * Copyright: 20151002, Daily Data, Inc.
8
 * 
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation, either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
21
 * 
22
 * Read messages from mail server. If they are YAML or XML sysinfo reports
23
 * save them to local drive, then remove them from mail server.
24
 * Files will be named with the following values, separated by underscores
25
 * report date (YYYY-MM-DD)
26
 * report time (HH:MM:SS) (CONTAINS COLONS)
27
 * client name (MAY CONTAIN SPACES)
28
 * device name
29
 * serial number (default to 00000 if it is not in the report)
30
 * 
31
 * Requires php5-imap
32
 * apt-get install php5-imap
33
 * 
34
 * Good information taken from
35
 * http://docstore.mik.ua/orelly/webprog/pcook/ch17_04.htm
36
 * 
37
 */
38
 
39
$VERSION = '1.0';
40
$MAXDOWNLOAD = 5000; // maximum number of e-mails to download at one time
41
$CLI = isset( $_SERVER["TERM"]); // only set if we are not in a cron job
42
 
43
 
44
 
45
require "sysinfoRead.php.conf";
46
 
47
function OpenMailbox ( $username, $password, $server, $ssl = true, $port=null, $mailbox = 'INBOX' ) {
48
   if ( $port == null )
49
      if ( $ssl ) $port = 993;  else $port = 143;
50
   $server = gethostbyname( $server );
51
   $serverString = "$server:$port/imap";
52
   if ( $ssl ) $serverString .= '/ssl';
53
   $serverString .= '/novalidate-cert';
54
   $serverString = '{' . $serverString . '}' . $mailbox;
55
   $server = imap_open( $serverString, $username, $password );
56
 
57
   return array($server, $serverString);
58
}
59
 
60
function getContents ($mail, $n ) {
61
   $body = '';
62
   $st = imap_fetchstructure($mail, $n);
63
   if (!empty($st->parts)) {
64
       for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
65
           $part = $st->parts[$i];
66
           if ($part->subtype == 'PLAIN') {
67
                $body = imap_fetchbody($mail, $n, $i+1);
68
           }
69
        }
70
   } else {
71
       $body = imap_body($mail, $n);
72
   }
73
   return getBody( $body );
74
}
75
 
76
function getBody ( $body ) {
77
   global $bodyContents;
78
   foreach ( $bodyContents as $key => $regexes ) {
79
      $matches;
80
      $pattern = $regexes['startTag'] . '.*' . $regexes['endTag'];
81
      if ( preg_match( "/$pattern/ms", $body, $matches ) ) 
82
         return array( $key, $matches[0] );
83
   }
84
   return array( false, '' );
85
}
86
 
87
 
88
function makeFileName ( $data, $type ) {
89
   global $outpath;
90
   // we will create filename as yyyy-mm-dd_HH:mm:ss_client_hostname_serial
91
   $date =  empty( $data['report']['date'] ) ? '' : strtotime( $data['report']['date'] ); // store in Unix timestamp
92
   $date = strftime( '%F_%T', $date ); // save a copy of the date in SQL format
93
 
94
   // add client name
95
   $client = empty( $data['report']['client'] ) ? '' : $data['report']['client'];
96
 
97
   // add hostname
98
   $hostname = empty ( $data['system']['hostname'] ) ? '' : $data['system']['hostname'];
99
 
100
   // add serial number if it exists, otherwise use '00000' (5 0's)
101
   $serial = empty ( $data['system']['serial'] ) ? '00000' : $data['system']['serial'];
102
   return ( $date && $client && $hostname && $serial ) ? "$outpath/$date" . '_' . $client . '_' . $hostname . '_' . "$serial.$type" : false;
103
 
104
} 
105
 
106
function saveFile( $filename, $contents, $timestamp ) {
107
   $bytesWritten = file_put_contents( $filename, $contents );
108
   if ( $bytesWritten ) {
109
      if ( ! touch( $filename, $timestamp ) ) logError( "could not set timestamp of $filename to $timestamp" );
110
   }
111
   return $bytesWritten;
112
}
113
 
114
function logError ( $message ) {
115
   global $logFile;
116
   error_log( "$message\n", 3, $logFile );
117
}
118
 
119
/**************************************************************************************************************
120
 * Begin Main Program
121
 **************************************************************************************************************/
122
 
123
 
124
// ensure the path we want to write to exists
125
if ( ! is_dir( $outpath ) ) {
126
   if ( ! mkdir( $outpath, 0777, true ) ) {
127
      die( "Could not create path $outpath\n" );
128
   }
129
}
130
 
131
$listMailboxes =  isset( $argv[1] ) ; // anything passed on cli results in a list of mailboxes instead of the job
132
 
133
foreach ( $servers as $thisServer ) {
134
   if ($MAXDOWNLOAD <= 0 ) break;
135
   if ( ! $thisServer['enabled'] ) continue; // ignore anything that is not enabled
136
   print "Working on " . $thisServer['servername'] . "\n";
137
   $messagesToDelete = array(); // trap the UID's of messages to delete, more accurate than using message number
138
   print "Opening " . $thisServer['servername'] . "\n";
139
 
140
   // open the mail server connection. NOTE: the $connectString is used in other functions, so we need to preserve it
141
   list( $server, $connectString ) = OpenMailbox(  $thisServer['username'], 
142
                                                   $thisServer['password'], 
143
                                                   $thisServer['servername'] , 
144
                                                   $thisServer['ssl'],
145
                                                   $thisServer['port'], 
146
                                                   $listMailboxes ? '' : $thisServer['mailbox'] 
147
                                                );
148
   print "Success with $connectString\n";
149
   if ( $listMailboxes ) {
150
      $list = imap_list($server, $connectString, "*");
151
      print_r( $list ); print "\n";
152
      continue;
153
   }
154
   $count = 0;
155
   if ( $server ) {
156
      $folderCount = imap_num_msg( $server );
157
      for ( $num = 1; ($num <= $folderCount) && $MAXDOWNLOAD; $num++ ) {
158
         list( $type,$body ) = getContents( $server, $num );
159
         if ( ! $type ) {
160
            logError( "Unknown File Type" );
161
            continue;
162
         }
163
         if ( ! ($data = $bodyContents[$type]['eval']($body) ) ) {
164
            logError( "Unable to parse file" );
165
            continue;
166
         }
167
         if ( !(  $filename  = makeFileName( $data, $type ) ) ) {
168
            logError( "unable to create a file name" );
169
            continue;
170
         }
171
         if ( !(  $bytesWritten = saveFile( $filename, $body, strtotime( $data['report']['date'] ) ) ) ) {
172
            logError( "unable to save file $filename" );
173
            continue;
174
         }
175
         $messagesToDelete[] = imap_uid( $server, $num );
176
         $count++;
177
         if ( $CLI ) print '.'; // only do this if interactive session
178
         $MAXDOWNLOAD--;
179
      } // for
180
      if ( $thisServer['deleteProcessed'] ) {
181
         foreach ( $messagesToDelete as $uid ) {
182
            imap_delete( $server, $uid, FT_UID ) or logError( "Can't delete [$uid]: imap_last_error()" );
183
         }
184
         imap_expunge( $server );
185
      }  // if delete
186
      imap_close( $server );
187
   } else {
188
      print "Could not open server " . $thisServer['servername'] . "\n";
189
   } // if..else
190
   print "\nProcessed $count messages\n\n";
191
} // outer for
192
?>