Files
thetool/application/MailtemplateDispatch/MailtemplateDispatch.php
2025-01-14 22:41:14 +01:00

487 lines
16 KiB
PHP

<?php
class MailtemplateDispatch extends mfBaseModel {
private $mailtemplate;
private $filter_datasource_array;
private $recipient_filter_array;
private $creator;
private $editor;
public function sendToRecipients($test_to_email = false) {
$emails = [];
if(!$test_to_email) {
$emails = $this->getRecipients();
if(!$emails) {
$this->log->debug(__METHOD__.": No recipient emails (".$this->id.")");
return true;
}
if(!$this->tosend_date || $this->tosend_date > date('U')) {
$this->log->debug(__METHOD__.": No tosend date or in future (".$this->id.")");
return true;
}
}
if($test_to_email) {
$emails = [$test_to_email];
}
if(!$this->subject) return false;
if(!$this->sender_email) return false;
if(!$this->sender_name) return false;
$template = $this->getProperty("mailtemplate");
if(!$template) return false;
if($template->body_html) {
$body = "<html><head></head><body>";
$body .= $template->renderBody();
$body .= "</body></html>\n"; // explicitly add new line, or some mail clients wont show attachment
} else {
$body = $template->renderBody();
}
$subject = $this->subject;
$from_email = $this->sender_email;
$from_name = $this->sender_name;
$attachments = [];
foreach($template->files as $file) {
$att = [];
$att["path"] = MFUPLOAD_FILE_SAVE_PATH."/".$file->file->subfolder."/".$file->file->store_filename;
$att["filename"] = $file->filename;
$att["mimetype"] = $file->file->mimetype;
$attachments[] = $att;
}
foreach($emails as $email) {
$to = $email;
// check for NotificationLog
$mtdlog = MailtemplateDispatchLog::getFirst(["mailtemplatedispatch_id" => $this->id, "email" => $to]);
if($mtdlog) {
// was sent already
continue;
}
$email = new Emailnotification();
$email->setSubject($subject);
if($template->body_html) {
$email->setHtmlBody($body);
} else {
$email->setBody($body);
}
$email->setFrom($from_email, $from_name);
$email->setTo($to);
$email->setHeader("X-".ucfirst(MFAPPNAME)."-mtdid", $this->id);
if(count($attachments)) {
foreach($attachments as $file) {
$email->addAttachment($file["path"], null, $file["filename"], $file['mimetype']);
}
}
$email->send();
$this->log->info(__METHOD__.": Sending MaintenanceNotification to $to");
if($test_to_email) {
return true;
}
$mtdlog = MailtemplateDispatchLog::create([
"mailtemplatedispatch_id" => $this->id,
"email" => $to,
"sent" => date("U"),
]);
$mtdlog->save();
sleep(1); // wait a second
}
}
public function getRecipients($list_recipients = false, $return_recipients = false) {
$datasources = $this->getProperty("filter_datasource_array");
$filter = $this->getProperty("recipient_filter_array");
$zips = [];
$zip_source = "owner";
$to_billcontact = false;
$to_techcontact = false;
$fibu_account = false;
if(array_key_exists("zip", $filter) && count($filter["zip"])) {
$zips = $filter["zip"];
}
// only owner is implemented yet
if(array_key_exists("zip_source", $filter) && $filter["zip_source"] == "termination") {
$zip_source = "term";
}
if(array_key_exists("billingaddress", $filter) && $filter["billingaddress"]) {
$to_billcontact = true;
}
if(array_key_exists("techcontact", $filter) && $filter["techcontact"]) {
$to_techcontact = true;
}
if(array_key_exists("fibu_account", $filter) && $filter["fibu_account"]) {
$fibu_account = true;
}
if(!is_array($datasources) || !count($datasources)) {
$this->log->warn(__METHOD__.": Mailtemplate ".$this->id.": no datasource");
return false;
}
$owner_ids = [];
$emails = [];
if(in_array("contract", $datasources)) {
foreach(ContractModel::searchActive([]) as $contract) {
if($fibu_account && !$contract->owner->fibu_account_number) continue;
if(($zips && in_array($contract->owner->zip, $zips)) || !$zips ) {
if(!in_array($contract->owner_id, $owner_ids)) {
$owner_ids[] = $contract->owner_id;
}
if($contract->owner->email) {
$emails[] = trim($contract->owner->email);
}
if($to_billcontact && $contract->billingaddress_id && $contract->billingaddress->email) {
if(($zips && in_array($contract->billingaddress->zip, $zips)) || !$zips ) {
$emails[] = trim($contract->billingaddress->email);
}
}
if($to_techcontact && array_key_exists("techcontact", $contract->owner->links) && is_array($contract->owner->links["techcontact"])) {
foreach($contract->owner->links["techcontact"] as $techlink) {
if($techlink->address->email) {
$emails[] = trim($techlink->address->email);
}
}
}
}
}
}
if(in_array("order", $datasources)) {
$order_search = [];
$order_search["finish_date"] = true;
if(array_key_exists("order_open", $filter) && $filter["order_open"]) {
$order_search["finish_date"] = false;
}
foreach(OrderModel::search($order_search) as $order) {
if($fibu_account && !$order->owner->fibu_account_number) continue;
if(array_key_exists("order_int_products", $filter) && $filter["order_int_products"]) {
$include_order = true;
foreach($order->products as $op) {
if($op->product->external) {
//fwrite(STDERR, "found external product (".$op->product->name.")\n");
$include_order = false;
break;
}
}
if(!$include_order) continue;
}
if(($zips && in_array($order->owner->zip, $zips)) || !$zips ) {
if(!in_array($order->owner_id, $owner_ids)) {
$owner_ids[] = $order->owner_id;
}
if($order->owner->email) {
$emails[] = trim($order->owner->email);
}
if($to_billcontact && $order->billingaddress_id && $order->billingaddress->email) {
$emails[] = trim($order->billingaddress->email);
}
if($to_techcontact && $order->techcontact_id && $order->techcontact->email) {
$emails[] = trim($order->techcontact->email);
}
}
}
}
if($list_recipients || $return_recipients) {
$csv = "Kundennummer;Firma;Vorname;Nachname;Straße;PLZ;Ort;Email\n";
foreach ($owner_ids as $id) {
$address = new Address($id);
if (!$address->id) {
echo "Adresse mit id $id nicht gefunden\n";
}
$csv .= $address->customer_number . ";";
$csv .= '"' . str_replace(["\r\n", "\n", "\r"]," ", $address->company) . '";';
$csv .= '"' . $address->firstname . '";';
$csv .= '"' . $address->lastname . '";';
$csv .= '"' . $address->street . '";';
$csv .= '"' . $address->zip . '";';
$csv .= '"' . $address->city . '";';
$csv .= '"' . $address->email . '";' . "\n";
}
if($return_recipients) {
return $csv;
} else {
echo $csv;
exit;
}
}
$emails = array_unique($emails);
return $emails;
}
public function getProperty($name) {
if($this->$name == null) {
if($name == "filter_datasource_array") {
$json = $this->filter_datasource;
if(!$json) {
return [];
}
$ds = json_decode($json, true);
if(!is_array($ds)) {
return [];
}
$this->filter_datasource_array = $ds;
return $this->filter_datasource_array;
}
if($name == "recipient_filter_array") {
$json = $this->recipient_filter;
if(!$json) {
return [];
}
$rf = json_decode($json, true);
if(!is_array($rf)) {
return [];
}
$this->recipient_filter_array = $rf;
return $this->recipient_filter_array;
}
if($name == "file") {
if(!$this->id) return null;
$file = MailtemplateDispatchFile::getFirst(["MailtemplateDispatch_id" => $this->id]);
if($file) {
$this->file = $file;
}
return $this->file;
}
if($name == "creator") {
$this->creator = mfValuecache::singleton()->get("Worker-id-".$this->create_by);
if($this->creator === null) {
$this->creator = new User($this->create_by);
if($this->creator->id) {
mfValuecache::singleton()->set("Worker-id-".$this->create_by, $this->creator);
}
}
return $this->creator;
}
if($name == "editor") {
$this->editor = mfValuecache::singleton()->get("Worker-id-".$this->edit_by);
if($this->editor === null) {
$this->editor = new User($this->edit_by);
if($this->editor->id) {
mfValuecache::singleton()->set("Worker-id-".$this->edit_by, $this->editor);
}
}
return $this->editor;
}
$classname = ucfirst($name);
$idfield = $name."_id";
$this->$name = mfValuecache::singleton()->get("mfObjectmodel-$name-".$this->$idfield);
if(!$this->$name) {
$this->$name = new $classname($this->$idfield);
}
if($this->$name->id) {
mfValuecache::singleton()->set("mfObjectmodel-$name-".$this->$name->id, $this->$name);
return $this->$name;
} else {
return null;
}
}
return $this->$name;
}
/********************************
* Begin static Model functions
*/
public static function create(Array $data) {
$model = new MailtemplateDispatch();
$table_fields = [
"mailtemplate_id", "sender_email","sender_name", "sender_replyto", "tosend_date", "send_start", "send_finish", "send_lock", "recipient_count",
"subject", "body_text", "body_html", "filter_datasource", "recipient_filter",
"note", "create_by","edit_by","create","edit"
];
foreach($data as $field => $value) {
if(in_array($field, $table_fields)) {
$model->$field = $value;
}
}
$me = new User();
$me->loadMe();
if($model->create_by === null) {
$model->create_by = $me->id;
}
if($model->edit_by === null) {
$model->edit_by = $me->id;
}
return $model;
}
public static function getAll() {
$items = [];
$db = FronkDB::singleton();
$res = $db->select("MailtemplateDispatch", "*", "1 = 1 ORDER BY `create`");
if($db->num_rows($res)) {
while($data = $db->fetch_object($res)) {
$items[] = new MailtemplateDispatch($data);
}
}
return $items;
}
public static function getFirst($filter) {
$db = FronkDB::singleton();
$where = self::getSqlFilter($filter);
$sql = "SELECT * FROM MailtemplateDispatch
WHERE $where
ORDER BY `create` LIMIT 1";
//var_dump($sql);exit;
$res = $db->query($sql);
if($db->num_rows($res)) {
$data = $db->fetch_object($res);
$item = new MailtemplateDispatch($data);
if($item->id) {
return $item;
} else {
return null;
}
}
return null;
}
public static function count($filter) {
$db = FronkDB::singleton();
$where = self::getSqlFilter($filter);
$sql = "SELECT COUNT(*) as cnt FROM MailtemplateDispatch
WHERE $where";
//mfLoghandler::singleton()->debug($sql);
$res = $db->query($sql);
if($db->num_rows($res)) {
$data = $db->fetch_object($res);
return $data->cnt;
}
return 0;
}
public static function search($filter, $limit = false, $order = false) {
//var_dump($filter);exit;
$items = [];
if(!$order) {
$order = "`create` ASC";
}
$db = FronkDB::singleton();
$where = self::getSqlFilter($filter);
$sql = "SELECT * FROM MailtemplateDispatch
WHERE $where
ORDER BY $order";
if(is_array($limit) && count($limit)) {
if(is_numeric($limit['start']) && is_numeric($limit['count'])) {
$sql .= " LIMIT ".$limit['start'].", ".$limit['count'];
} elseif(is_numeric($limit['count'])) {
$sql .= " LIMIT ".$limit['count'];
}
}
mfLoghandler::singleton()->debug($sql);
$res = $db->query($sql);
if($db->num_rows($res)) {
while($data = $db->fetch_object($res)) {
$items[$data->id] = new MailtemplateDispatch($data);
}
}
return $items;
}
private static function getSqlFilter($filter) {
$where = "1=1 ";
if(array_key_exists("mailtemplate_id", $filter)) {
$mailtemplate_id = $filter['mailtemplate_id'];
if(is_numeric($mailtemplate_id)) {
$where .= " AND MailtemplateDispatch.mailtemplate_id=$mailtemplate_id";
}
}
if(array_key_exists("subject", $filter)) {
$subject = FronkDB::singleton()->escape($filter["subject"]);
if($subject) {
$where .= " AND subject='$subject'";
}
}
if(array_key_exists("send_finish", $filter)) {
$send_finish = $filter['send_finish'];
if($send_finish === null) {
$where .= " AND send_finish IS NULL";
}
}
if(array_key_exists("send_lock", $filter)) {
$send_lock = $filter['send_lock'];
if($send_lock === null) {
$where .= " AND send_lock IS NULL";
}
}
if(array_key_exists("add-where", $filter)) {
$where .= " ".$filter['add-where'];
}
//var_dump($filter, $where);exit;
return $where;
}
}