前の日記で予告した修正版。コード部分。
PHPにしました。画像データを使ったWEBページをPHPで書いてるので合わせました。
#! /usr/local/php/bin/php <?php require_once 'Mail/mimeDecode.php'; require_once 'db_login.php'; // DBのログイン情報 // 画像保存ディレクトリ $image_dir = "/var/www/html/mfeeling/images"; // 標準出力のリダイレクトがprocmailでできない?とりあえず直接ログファイル指定。 $logfile = "$home_dir/mailparse.log"; debug_out("called"); // 標準入力からメール取得 $source = file_get_contents("php://stdin"); if(!$source) { exit; } // いろいろパラメータセットしてデコード $params['include_bodies'] = true; $params['decode_bodies'] = true; $params['decode_headers'] = true; $decoder = new Mail_mimeDecode($source); $structure = $decoder->decode($params); // 送信元アドレス抜き出し $from = $structure->headers['from']; $from = addslashes($from); $from = str_replace('"','',$from); if(preg_match('/<(.*?)>$/', $from, $match)){ $from = $match[1]; } $from = strtolower(trim($from)); debug_out("mail from $from"); // DB接続 $connection = mysql_connect($db_host, $db_username, $db_password); if(!$connection){ debug_out("Could not connect to the database:" . mysql_error()); return false; } $db_select = mysql_select_db($db_database); if(!$db_select){ debug_out("Could not select the database:" . mysql_error()); return false; } // 知らないアドレスなら終了 $query = "SELECT SID FROM authdb WHERE mail='$from'"; $result = mysql_query($query); if(! $result){ debug_out("Could not query the database:" . mysql_error()); return false; } $row = mysql_fetch_row($result); $sid = $row[0]; if(! $sid){ debug_out("Could not find the mail-address:$from"); return false; } // 添付ファイル処理 if(strcasecmp($structure->ctype_primary, 'multipart') == 0){ foreach($structure->parts as $part){ if(strcasecmp($part->ctype_primary, 'image') == 0){ $filename = $part->d_parameters['filename']; $filetype = $part->ctype_secondary; // DB登録 $query = "insert into images values(null,'$sid','$filename','$filetype')"; $result = mysql_query($query); debug_out("execute query: $query"); if(! $result){ debug_out("Could not query the database:" . mysql_error()); return false; } // 画像ファイル自体はファイル保存。 $image_path = $image_dir.'/'.mysql_insert_id() . "_$filename"; if($fp = fopen($image_path, 'w')){ $length = strlen($part->body); fwrite($fp, $part->body, $length); fclose($fp); chmod($image_path, 0644); } } } }else{ debug_out("attached not found"); } // 終了処理 mysql_close($connection); debug_out("finish"); // ログ出力関数 function debug_out($msg) { global $logfile; file_put_contents($logfile, date("Y/m/d H:i:s") . " $msg\n", FILE_APPEND); # print(date("Y/m/d H:i:s") . " $msg\n"); } ?>
修正予定
・DBにタイムスタンプくらい登録しようよ・・・
・コード汚い。