Subversion Repositories computer_asset_manager_v1

Rev

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

Rev Author Line No. Line
23 rodolico 1
<?php
2
 
3
/*
4
 * getBackupMail.php
5
 * 
6
 * Author: R. W. Rodolico
7
 * Copyright: 20160218, 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
 * V0.1 201602018 RWR
38
 * copied from getSysinfoMail.php
39
 * 
40
 * 
41
 * 
42
 */
43
 
44
$VERSION = '0.1';
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
// where to load the configuration file from
48
$confFileName = "rsbackupRead.conf.yaml";
49
$searchPaths = array( '/etc/camp', '/opt/camp', '/opt/camp/backups', $_SERVER['SCRIPT_FILENAME'], getcwd() );
50
 
51
/*
52
 * function loadConfig
53
 * Parameters $confFileName - the name of the configuration file
54
 *            $searchPaths - an array of paths to be searched
55
 * Returns    An array containing the configuration 
56
 * will search for a configuration file in $searchPaths for $confFileName
57
 * in order (so as to give priorities). The configuration file is
58
 * assumed to be a YAML file
59
 */
60
 
61
function loadConfig ( $confFileName, $searchPaths ) {
62
 
63
   /*
64
    * we don't know where the configuration file will be, so we have a list
65
    * below (searchPaths) to look for it. It will load the first one it 
66
    * finds, then exit. THUS, you could have multiple configuration files
67
    * but only the first one in the list will be used
68
    */
69
 
70
   $configuration = array();
71
 
72
 
73
   foreach ( $searchPaths as $path ) {
74
      if ( file_exists( "$path/$confFileName" ) ) {
75
         print "Found $path/$confFileName\n";
76
         $configuration = yaml_parse_file( "$path/$confFileName" );
77
         #require "$path/$confFileName";
78
         break; // exit out of the loop; we don't try to load it more than once
79
      } // if
80
   } // foreach
81
   return $configuration;
82
}
83
 
84
/* 
85
 * function    OpenMailbox
86
 * Parameters: $username
87
 *             $password
88
 *             $server
89
 *             $ssl=true
90
 *             $port=null
91
 *             $mailbox='INBOX'
92
 * 
93
 * Returns:    The IMAP instance handle
94
 *             The server string (used by some functions)
95
 */
96
function OpenMailbox ( $username, $password, $server, $ssl = true, $port=null, $mailbox = 'INBOX' ) {
97
   if ( $port == null )
98
      if ( $ssl ) $port = 993;  else $port = 143;
99
   $server = gethostbyname( $server );
100
   $serverString = "$server:$port/imap";
101
   if ( $ssl ) $serverString .= '/ssl';
102
   $serverString .= '/novalidate-cert';
103
   $serverString = '{' . $serverString . '}' . $mailbox;
104
   $server = imap_open( $serverString, $username, $password );
105
 
106
   return array($server, $serverString);
107
}
108
 
109
 
110
/*
111
 * function  getContents
112
 * Paramters $mail - handle to the connection
113
 *           $n    - the # of the message to get
114
 * Returns   An array containing all attachments
115
 * 
116
 */
117
 
118
function getContents( $mail, $n ) {
119
 
120
   $header = imap_header( $mail, $n );
121
   $structure = imap_fetchstructure( $mail, $n );
122
   $attachments = array();
123
   if(isset($structure->parts) && count($structure->parts)) {
124
 
125
      for($i = 0; $i < count($structure->parts); $i++) {
126
 
127
         $attachments[$i] = array(
128
            'is_attachment' => false,
129
            'filename' => '',
130
            'name' => '',
131
            'attachment' => ''
132
         );
133
 
134
         if($structure->parts[$i]->ifdparameters) {
135
            foreach($structure->parts[$i]->dparameters as $object) {
136
               if(strtolower($object->attribute) == 'filename') {
137
                  $attachments[$i]['is_attachment'] = true;
138
                  $attachments[$i]['filename'] = $object->value;
139
               }
140
            }
141
         }
142
 
143
         if($structure->parts[$i]->ifparameters) {
144
            foreach($structure->parts[$i]->parameters as $object) {
145
               if(strtolower($object->attribute) == 'name') {
146
                  $attachments[$i]['is_attachment'] = true;
147
                  $attachments[$i]['name'] = $object->value;
148
               }
149
            }
150
         }
151
 
152
         if($attachments[$i]['is_attachment']) {
153
            $attachments[$i]['attachment'] = imap_fetchbody($mail, $n, $i+1);
154
            if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
155
               $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
156
            }
157
            elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
158
               $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
159
            }
160
         } else {
161
            $attachments[$i]['attachment'] = imap_fetchbody( $mail, $n, $i+1 );
162
         }
163
      }
164
   }
165
   return array( $header, $attachments );
166
}
167
 
168
 
169
function saveAttachments ( $attachments, $mailDate ) {
170
   $body = '';
171
   foreach ( $attachments as $thisOne ) {
172
      if ( $thisOne['is_attachment'] ) {
173
         saveFile( makeFileName( $thisOne['filename'] ), $thisOne['attachment'], $mailDate );
174
      } else {
175
         $body .= $thisOne['attachment'];
176
      }
177
   }
178
   return $body;
179
}
180
 
181
/* function makeFileName
182
 * Parameter $data
183
 *           $type - the type of the file
184
 * Returns   properly formatted file name for saving
185
 * 
186
 * The file name is created as a combination of the report date
187
 * client name, hostname and serial number, separated by the underscore
188
 * character. The type of the file is appended, and the configuration
189
 * value for outpath is prepended
190
 */
191
function makeFileName ( $body ) {
192
   global $configuration;
193
   $outpath = $configuration['outpath'];
194
   return $outpath . '/' . $body;
195
} 
196
 
197
/*
198
 * function saveFile
199
 * parameter $filename
200
 *           $contents
201
 *           $timestamp
202
 * returns   Number of bytes written
203
 * 
204
 * Saves $contents to file $filename, then sets the timestamp to
205
 * $timestamp. It is assumed $filename was created by makeFileName
206
 * and $contents is the content of a report. $timestamp is the actual
207
 * report timestamp
208
 */
209
function saveFile( $filename, $contents, $timestamp ) {
210
   $bytesWritten = file_put_contents( $filename, $contents );
211
   if ( $bytesWritten ) {
212
      if ( ! touch( $filename, $timestamp ) ) logError( "could not set timestamp of $filename to $timestamp" );
213
   }
214
   return $bytesWritten;
215
}
216
 
217
function logError ( $message ) {
218
   global $configuration;
219
   error_log( "$message\n", 3, $configuration['logFile'] );
220
}
221
 
222
/**************************************************************************************************************
223
 * Begin Main Program
224
 **************************************************************************************************************/
225
 
226
// get the configuration
227
$configuration = loadConfig( $confFileName, $searchPaths );
228
#print_r( $configuration ) ; die;
229
 
230
// ensure the path we want to write to exists
231
if ( ! is_dir( $configuration['outpath'] ) ) {
232
   if ( ! mkdir( $configuration['outpath'], 0777, true ) ) {
233
      die( "Could not create path " . $configuration['outpath'] . "\n" );
234
   }
235
}
236
 
237
$listMailboxes =  isset( $argv[1] ) ; // anything passed on cli results in a list of mailboxes instead of the job
238
 
239
foreach ( $configuration['servers'] as $thisServer ) {
240
   if ($MAXDOWNLOAD <= 0 ) break;
241
   if ( ! $thisServer['enabled'] ) continue; // ignore anything that is not enabled
242
   print "Working on " . $thisServer['servername'] . "\n";
243
   $messagesToDelete = array(); // trap the UID's of messages to delete, more accurate than using message number
244
   print "Opening " . $thisServer['servername'] . "\n";
245
 
246
 
247
   // open the mail server connection. NOTE: the $connectString is used in other functions, so we need to preserve it
248
   list( $server, $connectString ) = OpenMailbox(  $thisServer['username'], 
249
                                                   $thisServer['password'], 
250
                                                   $thisServer['servername'] , 
251
                                                   $thisServer['ssl'],
252
                                                   $thisServer['port'], 
253
                                                   $listMailboxes ? '' : $thisServer['mailbox'] 
254
                                                );
255
   print "Success with $connectString\n";
256
   if ( $listMailboxes ) {
257
      $list = imap_list($server, $connectString, "*");
258
      print_r( $list ); print "\n";
259
      continue;
260
   }
261
   $count = 0;
262
   if ( $server ) {
263
      $folderCount = imap_num_msg( $server );
264
      for ( $num = 1; ($num <= $folderCount) && $MAXDOWNLOAD; $num++ ) {
265
         list( $header, $attachments ) = getContents( $server, $num );
266
         # $mailDate = getMailDate( $header );
267
         $body = saveAttachments( $attachments, strtotime($header->date) );
268
         $messagesToDelete[] = imap_uid( $server, $num );
269
         $count++;
270
         if ( $CLI ) print '.'; // only do this if interactive session
271
         $MAXDOWNLOAD--;
272
      } // for
273
      /*
274
      if ( $thisServer['deleteProcessed'] ) {
275
         foreach ( $messagesToDelete as $uid ) {
276
            imap_delete( $server, $uid, FT_UID ) or logError( "Can't delete [$uid]: imap_last_error()" );
277
         }
278
         imap_expunge( $server );
279
      }  // if delete
280
      */
281
      imap_close( $server );
282
   } else {
283
      print "Could not open server " . $thisServer['servername'] . "\n";
284
   } // if..else
285
   print "\nProcessed $count messages\n\n";
286
} // outer for
287
?>