From 3b4291c110d0ae723fbfcce3cc93507953d97a58 Mon Sep 17 00:00:00 2001 From: xblack Date: Wed, 21 Dec 2016 10:43:46 +0100 Subject: [PATCH] Added possibility to send invoice mails via SwiftMailer * SwiftMailer support SMTP tls authorization --- bin/lms-sendinvoices_swiftmailer.php | 345 +++++++++++++++++++++++++++ lib/swiftmailer | 1 + 2 files changed, 346 insertions(+) create mode 100644 bin/lms-sendinvoices_swiftmailer.php create mode 160000 lib/swiftmailer diff --git a/bin/lms-sendinvoices_swiftmailer.php b/bin/lms-sendinvoices_swiftmailer.php new file mode 100644 index 00000000..3e0ea127 --- /dev/null +++ b/bin/lms-sendinvoices_swiftmailer.php @@ -0,0 +1,345 @@ +#!/usr/bin/php + 'config-file:', + 'q' => 'quiet', + 'h' => 'help', + 'v' => 'version', + 't' => 'test', + 'f:' => 'fakedate:', + 'i:' => 'invoiceid:', +); + +foreach ($parameters as $key => $val) { + $val = preg_replace('/:/', '', $val); + $newkey = preg_replace('/:/', '', $key); + $short_to_longs[$newkey] = $val; +} +$options = getopt(implode('', array_keys($parameters)), $parameters); +foreach ($short_to_longs as $short => $long) + if (is_array($options) && array_key_exists($short, $options)) { + $options[$long] = $options[$short]; + unset($options[$short]); + } + +if (is_array($options) && array_key_exists('version', $options)) { + print <<GetAll('SELECT section, var, value FROM uiconfig WHERE disabled=0')) + foreach ($cfg as $row) + $CONFIG[$row['section']][$row['var']] = $row['value']; + +// Include required files (including sequence is important) + +require_once(LIB_DIR . '/language.php'); +include_once(LIB_DIR . '/definitions.php'); +require_once(LIB_DIR . '/unstrip.php'); +require_once(LIB_DIR . '/common.php'); +require_once(LIB_DIR . '/LMS.class.php'); +require_once(LIB_DIR . '/swiftmailer/lib/swift_required.php'); + +$lms_url = (!empty($CONFIG['sendinvoices']['lms_url']) ? $CONFIG['sendinvoices']['lms_url'] : 'http://localhost/lms/'); +$lms_user = (!empty($CONFIG['sendinvoices']['lms_user']) ? $CONFIG['sendinvoices']['lms_user'] : ''); +$lms_password = (!empty($CONFIG['sendinvoices']['lms_password']) ? $CONFIG['sendinvoices']['lms_password'] : ''); + +if (!empty($CONFIG['sendinvoices']['smtp_host'])) + $CONFIG['mail']['smtp_host'] = $CONFIG['sendinvoices']['smtp_host']; +if (!empty($CONFIG['sendinvoices']['smtp_port'])) + $CONFIG['mail']['smtp_port'] = intval($CONFIG['sendinvoices']['smtp_port']); +if (!empty($CONFIG['sendinvoices']['smtp_user'])) + $CONFIG['mail']['smtp_username'] = $CONFIG['sendinvoices']['smtp_user']; +if (!empty($CONFIG['sendinvoices']['smtp_pass'])) + $CONFIG['mail']['smtp_password'] = $CONFIG['sendinvoices']['smtp_pass']; +if (!empty($CONFIG['sendinvoices']['smtp_auth'])) + $CONFIG['mail']['smtp_auth_type'] = strtolower($CONFIG['sendinvoices']['smtp_auth']); + +$filetype = (!empty($CONFIG['invoices']['type']) ? $CONFIG['invoices']['type'] : ''); +$debug_email = (!empty($CONFIG['sendinvoices']['debug_email']) ? $CONFIG['sendinvoices']['debug_email'] : ''); +$sender_name = (!empty($CONFIG['sendinvoices']['sender_name']) ? $CONFIG['sendinvoices']['sender_name'] : ''); +$sender_email = (!empty($CONFIG['sendinvoices']['sender_email']) ? $CONFIG['sendinvoices']['sender_email'] : ''); +$mail_subject = (!empty($CONFIG['sendinvoices']['mail_subject']) ? $CONFIG['sendinvoices']['mail_subject'] : 'Invoice No. %invoice'); +$mail_body = (!empty($CONFIG['sendinvoices']['mail_body']) ? $CONFIG['sendinvoices']['mail_body'] : $CONFIG['mail']['sendinvoice_mail_body']); +$invoice_filename = (!empty($CONFIG['sendinvoices']['invoice_filename']) ? $CONFIG['sendinvoices']['invoice_filename'] : 'invoice_%docid'); +$notify_email = (!empty($CONFIG['sendinvoices']['notify_email']) ? $CONFIG['sendinvoices']['notify_email'] : ''); + +if (empty($sender_email)) + die("Fatal error: sender_email unset! Con't continue, exiting.\n"); + +if (empty($CONFIG['mail']['smtp_auth_type'])) + die("Fatal error: smtp_auth setting not supported! Can't continue, exiting.\n"); + +$fakedate = (array_key_exists('fakedate', $options) ? $options['fakedate'] : NULL); +$invoiceid = (array_key_exists('invoiceid', $options) ? $options['invoiceid'] : NULL); + +function localtime2() +{ + global $fakedate; + if (!empty($fakedate)) { + $date = explode("/", $fakedate); + return mktime(0, 0, 0, intval($date[1]), intval($date[2]), intval($date[0])); + } else + return time(); +} + +$ftype = 'text/html'; +$fext = 'html'; + +if ($filetype == 'pdf') { + $ftype = 'application/pdf'; + $fext = 'pdf'; +} + +$timeoffset = date('Z'); +$currtime = localtime2() + $timeoffset; +$month = intval(date('m', $currtime)); +$day = intval(date('d', $currtime)); +$year = intval(date('Y', $currtime)); +$daystart = (intval($currtime / 86400) * 86400) - $timeoffset; +$dayend = $daystart + 86399; +$from = $sender_email; + +if (!empty($sender_name)) + $from = "$sender_name <$from>"; + +// prepare customergroups in sql query +$customergroups = " AND EXISTS (SELECT 1 FROM customergroups g, customerassignments ca + WHERE c.id = ca.customerid + AND g.id = ca.customergroupid + AND (%groups)) "; +$groupnames = $CONFIG['sendinvoices']['customergroups']; +$groupsql = ""; +$groups = preg_split("/[[:blank:]]+/", $groupnames, -1, PREG_SPLIT_NO_EMPTY); +foreach ($groups as $group) { + if (!empty($groupsql)) + $groupsql .= " OR "; + $groupsql .= "UPPER(g.name) = UPPER('" . $group . "')"; +} +if (!empty($groupsql)) + $customergroups = preg_replace("/\%groups/", $groupsql, $customergroups); + +// Initialize Session, Auth and LMS classes + +$AUTH = NULL; +$LMS = new LMS($DB, $AUTH, $CONFIG); +$LMS->ui_lang = $_ui_language; +$LMS->lang = $_language; + +$query = "SELECT d.id, d.number, d.cdate, c.email, d.name, d.customerid, n.template + FROM documents d + LEFT JOIN customers c ON c.id = d.customerid + LEFT JOIN numberplans n ON n.id = d.numberplanid + WHERE c.deleted = 0 AND d.type = 1 AND c.email <> '' AND c.invoicenotice = 1 " + . (!empty($invoiceid) ? "AND d.id = " . $invoiceid : "AND d.cdate >= $daystart AND d.cdate <= $dayend") + . (!empty($groupnames) ? $customergroups : "") + . " ORDER BY d.number"; +$docs = $DB->GetAll($query); + +define('USER_AGENT', "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); +define('COOKIE_FILE', tempnam('/tmp', 'lms-sendinvoices-cookies-')); + +$ch = curl_init(); +if (!$ch) + die("Fatal error: Can't init curl library!\n"); + +if (!empty($docs)) { + if (array_key_exists('test', $options)) { + $test = TRUE; + printf("WARNING! You are using test mode.\n"); + } + + $log = ""; + printf("\n\nTrying to send mails to:\n\n"); + foreach ($docs as $doc) { + curl_setopt_array($ch, array( + CURLOPT_URL => $lms_url . '/?m=invoice&override=1&original=1&id=' . $doc['id'] + . '&loginform[login]=' . $lms_user . '&loginform[pwd]=' . $lms_password, + CURLOPT_HTTPGET => TRUE, + CURLOPT_POST => FALSE, + CURLOPT_RETURNTRANSFER => TRUE, + CURLOPT_COOKIEJAR => COOKIE_FILE, + CURLOPT_COOKIEFILE => COOKIE_FILE, + CURLOPT_SSLVERSION => 3, + CURLOPT_SSL_VERIFYHOST => 2, + CURLOPT_SSL_VERIFYPEER => FALSE, + CURLOPT_USERAGENT => USER_AGENT + )); + $res = curl_exec($ch); + if (!empty($res)) { + $custemail = (!empty($debug_email) ? $debug_email : $doc['email']); + $invoice_number = (!empty($doc['template']) ? $doc['template'] : '%N/LMS/%Y'); + $body = $mail_body; + $subject = $mail_subject; + + $invoice_number = docnumber($doc['number'], $invoice_number, $doc['cdate'] + date('Z')); + $body = preg_replace('/%invoice/', $invoice_number, $body); + $body = preg_replace('/%balance/', $LMS->GetCustomerBalance($doc['customerid']), $body); + $day = sprintf("%02d", $day); + $month = sprintf("%02d", $month); + $year = sprintf("%04d", $year); + $body = preg_replace('/%today/', $year . "-" . $month . "-" . $day, $body); + $body = str_replace('\n', "\n", $body); + $subject = preg_replace('/%invoice/', $invoice_number, $subject); + $filename = preg_replace('/%docid/', $doc['id'], $invoice_filename); + $filename = preg_replace('/%day/', sprintf("%02d", $day), $filename); + $filename = preg_replace('/%month/', sprintf("%02d", $month), $filename); + $filename = preg_replace('/%year/', sprintf("%04d", $year), $filename); + + + if (!$quiet || $test) + // var_dump([ + // 'host' => $CONFIG['mail']['smtp_host'], + // 'port' => ($CONFIG['mail']['smtp_port']), + // 'protocol' => $CONFIG['mail']['smtp_auth_type'], + // 'user' => $CONFIG['mail']['smtp_username'], + // 'pass' => $CONFIG['mail']['smtp_password'] + // ]); + printf("Invoice No. $invoice_number for " . $doc['name'] . " <$custemail>\n"); + + if (!$test) { + $transport = Swift_SmtpTransport::newInstance($CONFIG['mail']['smtp_host'], $CONFIG['mail']['smtp_port'], $CONFIG['mail']['smtp_auth_type']) + ->setUsername($CONFIG['mail']['smtp_username']) + ->setPassword($CONFIG['mail']['smtp_password']); + + $message = Swift_Message::newInstance(); + $message->setTo(array($custemail => $doc['name'])); + $message->setSubject($subject); + $message->setBody($body, $CONFIG['sendinvoices']['mail_body_type']); + //$message->addPart($res, $ftype); + $message->setFrom($from, $CONFIG['sendinvoices']['mail_sent_from']); + $message->attach(Swift_Attachment::newInstance($res, $filename . '.' . $fext, $ftype)); + + $mailer = Swift_Mailer::newInstance($transport); + + if (!$mailer->send($message, $failures)) { + fprintf(STDERR, "Error sending mail:" . $failures[0] . "\n"); + } else { + $log .= "[" . date("d.m.Y H:i:s") . "] Sent message to $custemail with subject \"$subject\"\n"; + } + } + } + } + + if (strlen($log) > 1) { + $transport = Swift_SmtpTransport::newInstance($CONFIG['mail']['smtp_host'], $CONFIG['mail']['smtp_port'], $CONFIG['mail']['smtp_auth_type']) + ->setUsername($CONFIG['mail']['smtp_username']) + ->setPassword($CONFIG['mail']['smtp_password']); + + $message = Swift_Message::newInstance(); + $message->setTo(array($from => $CONFIG['sendinvoices']['mail_sent_from'])); + $message->setSubject($CONFIG['sendinvoices']['mail_log_subject']); + $message->setBody('
' . $log . '
', $CONFIG['sendinvoices']['mail_body_type']);; + $message->setFrom($from, $CONFIG['sendinvoices']['mail_sent_from']); + $mailer = Swift_Mailer::newInstance($transport); + + if (!$mailer->send($message, $failures)) { + fprintf(STDERR, "Error sending mail:" . $failures[0] . "\n"); + } else { + printf("\nLOG:\n\n" . $log . "\n"); + } + } +} +curl_close($ch); + +unlink(COOKIE_FILE); + +?> diff --git a/lib/swiftmailer b/lib/swiftmailer new file mode 160000 index 00000000..35475776 --- /dev/null +++ b/lib/swiftmailer @@ -0,0 +1 @@ +Subproject commit 3547577659c1a035093b70fce5ae393b3c94f44e