Subversion Repositories computer_asset_manager_v1

Rev

Rev 3 | Rev 6 | Go to most recent revision | Details | Compare with Previous | 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
 * 
5 rodolico 37
 * V1.1 20160203 RWR
38
 * Changed to use yaml for the configuration file. Had to take the
39
 * anonymous functions which parsed the different file types and convert
40
 * them to simpl eval() blocks.
41
 * 
3 rodolico 42
 */
43
 
5 rodolico 44
$VERSION = '1.1';
3 rodolico 45
$MAXDOWNLOAD = 5000; // maximum number of e-mails to download at one time
46
$CLI = isset( $_SERVER["TERM"]); // only set if we are not in a cron job
47
 
5 rodolico 48
/*
49
 * we don't know where the configuration file will be, so we have a list
50
 * below (searchPaths) to look for it. It will load the first one it 
51
 * finds, then exit. THUS, you could have multiple configuration files
52
 * but only the first one in the list will be used
53
 */
3 rodolico 54
 
5 rodolico 55
$confFileName = "sysinfoRead.conf.yaml";
56
$searchPaths = array( '/etc/camp', '/opt/camp', '/opt/camp/sysinfo', $_SERVER['SCRIPT_FILENAME'], getcwd() );
57
$configuration = array();
3 rodolico 58
 
59
 
5 rodolico 60
foreach ( $searchPaths as $path ) {
61
   if ( file_exists( "$path/$confFileName" ) ) {
62
      print "Found $path/$confFileName\n";
63
      $configuration = yaml_parse_file( "$path/$confFileName" );
64
      #require "$path/$confFileName";
65
      break; // exit out of the loop; we don't try to load it more than once
66
   } // if
67
} // foreach
68
 
69
 
70
/* 
71
 * function    OpenMailbox
72
 * Parameters: $username
73
 *             $password
74
 *             $server
75
 *             $ssl=true
76
 *             $port=null
77
 *             $mailbox='INBOX'
78
 * 
79
 * Returns:    The IMAP instance handle
80
 *             The server string (used by some functions)
81
 */
3 rodolico 82
function OpenMailbox ( $username, $password, $server, $ssl = true, $port=null, $mailbox = 'INBOX' ) {
83
   if ( $port == null )
84
      if ( $ssl ) $port = 993;  else $port = 143;
85
   $server = gethostbyname( $server );
86
   $serverString = "$server:$port/imap";
87
   if ( $ssl ) $serverString .= '/ssl';
88
   $serverString .= '/novalidate-cert';
89
   $serverString = '{' . $serverString . '}' . $mailbox;
90
   $server = imap_open( $serverString, $username, $password );
91
 
92
   return array($server, $serverString);
93
}
94
 
5 rodolico 95
/*
96
 * function  getContents
97
 * Paramters $mail - handle to the connection
98
 *           $n    - the # of the message to get
99
 * Returns   The type of report (yaml,xml,ini)
100
 *           The contents of the above
101
 * 
102
 * See getBody() below
103
 * 
104
 * At the very end, calls getBody, which evaluates the type of file
105
 * for a valid yaml/xml/ini file
106
 */
3 rodolico 107
function getContents ($mail, $n ) {
108
   $body = '';
109
   $st = imap_fetchstructure($mail, $n);
110
   if (!empty($st->parts)) {
111
       for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
112
           $part = $st->parts[$i];
113
           if ($part->subtype == 'PLAIN') {
114
                $body = imap_fetchbody($mail, $n, $i+1);
115
           }
116
        }
117
   } else {
118
       $body = imap_body($mail, $n);
119
   }
120
   return getBody( $body );
121
}
122
 
5 rodolico 123
/*
124
 * function  getBody
125
 * Parameter $body
126
 * Returns   type of report (yaml, ini, xml)
127
 *           contents of the report
128
 * Returns (false,'') if nothing found
129
 * 
130
 * Removes all cruft from the message, leaving only a yaml, xml
131
 * or ini. For example, anything before --- in a yaml file is remove
132
 * as is everything after ..., and in this case, the first return
133
 * would be the string 'yaml' and the second the actual yaml document
134
 */
3 rodolico 135
function getBody ( $body ) {
5 rodolico 136
   global $configuration;
137
   foreach ( $configuration['bodyContents'] as $key => $regexes ) {
3 rodolico 138
      $matches;
139
      $pattern = $regexes['startTag'] . '.*' . $regexes['endTag'];
140
      if ( preg_match( "/$pattern/ms", $body, $matches ) ) 
141
         return array( $key, $matches[0] );
142
   }
143
   return array( false, '' );
144
}
145
 
146
 
5 rodolico 147
/* function makeFileName
148
 * Parameter $data
149
 *           $type - the type of the file
150
 * Returns   properly formatted file name for saving
151
 * 
152
 * The file name is created as a combination of the report date
153
 * client name, hostname and serial number, separated by the underscore
154
 * character. The type of the file is appended, and the configuration
155
 * value for outpath is prepended
156
 */
3 rodolico 157
function makeFileName ( $data, $type ) {
5 rodolico 158
   global $configuration;
159
   $outpath = $configuration['outpath'];
3 rodolico 160
   // we will create filename as yyyy-mm-dd_HH:mm:ss_client_hostname_serial
161
   $date =  empty( $data['report']['date'] ) ? '' : strtotime( $data['report']['date'] ); // store in Unix timestamp
162
   $date = strftime( '%F_%T', $date ); // save a copy of the date in SQL format
163
 
164
   // add client name
165
   $client = empty( $data['report']['client'] ) ? '' : $data['report']['client'];
166
 
167
   // add hostname
168
   $hostname = empty ( $data['system']['hostname'] ) ? '' : $data['system']['hostname'];
169
 
170
   // add serial number if it exists, otherwise use '00000' (5 0's)
171
   $serial = empty ( $data['system']['serial'] ) ? '00000' : $data['system']['serial'];
172
   return ( $date && $client && $hostname && $serial ) ? "$outpath/$date" . '_' . $client . '_' . $hostname . '_' . "$serial.$type" : false;
173
 
174
} 
175
 
5 rodolico 176
/*
177
 * function saveFile
178
 * parameter $filename
179
 *           $contents
180
 *           $timestamp
181
 * returns   Number of bytes written
182
 * 
183
 * Saves $contents to file $filename, then sets the timestamp to
184
 * $timestamp. It is assumed $filename was created by makeFileName
185
 * and $contents is the content of a report. $timestamp is the actual
186
 * report timestamp
187
 */
3 rodolico 188
function saveFile( $filename, $contents, $timestamp ) {
189
   $bytesWritten = file_put_contents( $filename, $contents );
190
   if ( $bytesWritten ) {
191
      if ( ! touch( $filename, $timestamp ) ) logError( "could not set timestamp of $filename to $timestamp" );
192
   }
193
   return $bytesWritten;
194
}
195
 
196
function logError ( $message ) {
5 rodolico 197
   global $configuration;
198
   error_log( "$message\n", 3, $configuration['logFile'] );
3 rodolico 199
}
200
 
201
/**************************************************************************************************************
202
 * Begin Main Program
203
 **************************************************************************************************************/
204
 
205
 
206
// ensure the path we want to write to exists
5 rodolico 207
if ( ! is_dir( $configuration['outpath'] ) ) {
208
   if ( ! mkdir( $configuration['outpath'], 0777, true ) ) {
209
      die( "Could not create path " . $configuration['outpath'] . "\n" );
3 rodolico 210
   }
211
}
212
 
213
$listMailboxes =  isset( $argv[1] ) ; // anything passed on cli results in a list of mailboxes instead of the job
214
 
5 rodolico 215
foreach ( $configuration['servers'] as $thisServer ) {
3 rodolico 216
   if ($MAXDOWNLOAD <= 0 ) break;
217
   if ( ! $thisServer['enabled'] ) continue; // ignore anything that is not enabled
218
   print "Working on " . $thisServer['servername'] . "\n";
219
   $messagesToDelete = array(); // trap the UID's of messages to delete, more accurate than using message number
220
   print "Opening " . $thisServer['servername'] . "\n";
221
 
222
   // open the mail server connection. NOTE: the $connectString is used in other functions, so we need to preserve it
223
   list( $server, $connectString ) = OpenMailbox(  $thisServer['username'], 
224
                                                   $thisServer['password'], 
225
                                                   $thisServer['servername'] , 
226
                                                   $thisServer['ssl'],
227
                                                   $thisServer['port'], 
228
                                                   $listMailboxes ? '' : $thisServer['mailbox'] 
229
                                                );
230
   print "Success with $connectString\n";
231
   if ( $listMailboxes ) {
232
      $list = imap_list($server, $connectString, "*");
233
      print_r( $list ); print "\n";
234
   }
235
   $count = 0;
236
   if ( $server ) {
237
      $folderCount = imap_num_msg( $server );
238
      for ( $num = 1; ($num <= $folderCount) && $MAXDOWNLOAD; $num++ ) {
239
         list( $type,$body ) = getContents( $server, $num );
240
         if ( ! $type ) {
241
            logError( "Unknown File Type" );
242
            continue;
243
         }
5 rodolico 244
         $data = eval( $configuration['bodyContents'][$type]['eval'] );
245
         if ( ! $data ) {
3 rodolico 246
            logError( "Unable to parse file" );
247
            continue;
248
         }
249
         if ( !(  $filename  = makeFileName( $data, $type ) ) ) {
250
            logError( "unable to create a file name" );
251
            continue;
252
         }
253
         if ( !(  $bytesWritten = saveFile( $filename, $body, strtotime( $data['report']['date'] ) ) ) ) {
254
            logError( "unable to save file $filename" );
255
            continue;
256
         }
257
         $messagesToDelete[] = imap_uid( $server, $num );
258
         $count++;
259
         if ( $CLI ) print '.'; // only do this if interactive session
260
         $MAXDOWNLOAD--;
261
      } // for
262
      if ( $thisServer['deleteProcessed'] ) {
263
         foreach ( $messagesToDelete as $uid ) {
264
            imap_delete( $server, $uid, FT_UID ) or logError( "Can't delete [$uid]: imap_last_error()" );
265
         }
266
         imap_expunge( $server );
267
      }  // if delete
268
      imap_close( $server );
269
   } else {
270
      print "Could not open server " . $thisServer['servername'] . "\n";
271
   } // if..else
272
   print "\nProcessed $count messages\n\n";
273
} // outer for
274
?>