public static function enqueue_message_to_email($message_id, $authors_ids, $notification_type = EmailNotification::TO_AUTHOR_ON_ASSIGN) { if (empty($message_id) || !is_numeric($message_id)) { return false; } assert(in_array($notification_type, EmailNotification::$NOTIFICATION_TYPES)); // Если не надо уведомлять - выходим типа все ок if (!EmailNotificationType::isSendable($notification_type)) { return array(); } $result = array(); if (!is_array($authors_ids) && is_numeric($authors_ids)) { $authors_ids = array($authors_ids); } foreach ($authors_ids as $id) { if (is_numeric($id)) { try { $author = Employee::find($id); } catch (Exception $e) { $result['error'][] = $id; continue; } $notification_id = EmailNotification::create(array('message_id' => $message_id, 'receiver_email' => $author['email'], 'type' => $notification_type)); if ($notification_id) { $result['success'][] = $id; } } else { $ids = explode(', ', $id); $temp_result = self::enqueue_message_to_email($message_id, $ids, $notification_type); if (count($temp_result['success'])) { array_push($result['success'], $temp_result['success']); } if (count($temp_result['error'])) { array_push($result['error'], $temp_result['error']); } } } return $result; }
/** * @param int $message_id Message id in TABLE_MESSAGES * @param string $receiver_email receiver's Email address * @param int $message_type тип сообщения, из набора EmailNotificationType::$NOTIFICATION_TYPES * @see EmailNotificationType * @return mixed */ function enqueue_message_to_email($message_id, $receiver_email, $notification_type) { assert(in_array($notification_type, EmailNotificationType::$NOTIFICATION_TYPES)); if (empty($receiver_email)) { return false; } if (!EmailNotificationType::isPersistable($notification_type)) { return false; } return EmailNotification::create(array('message_id' => $message_id, 'receiver_email' => $receiver_email, 'type' => $notification_type)); }
function cron_sendEmailNotifications() { $execution_time = ini_get('max_execution_time'); if (empty($execution_time)) { $execution_time = DEF_EXEC_TIME; } else { if ($execution_time > MAX_EXEC_TIME * 2) { $execution_time = MAX_EXEC_TIME * 2; } } $execution_time_start = time(); $execution_time_end = $execution_time_start + $execution_time / 2; $notifications = \Components\Entity\EmailNotification::findBy(array(), array('attempts_to_send' => 'ASC'), EMAIL_NOTIFICATION_LIMIT, 0); $notification_index = 0; $good_cnt = 0; $notification_count = count($notifications); while (time() <= $execution_time_end && $notification_index < $notification_count) { $notification = $notifications[$notification_index]; $message = \Components\Entity\Message::find($notification['message_id']); if (!empty($message)) { //Прочитано, или не шлем - надо его сразу убить, чтобы потом когда включим не повалил шквал старых писем if ($message['readed'] || !\Components\Entity\EmailNotificationType::isSendable($notification['type'])) { \Components\Entity\EmailNotification::delete($notification['id']); } else { $attachments = array(); // надо только для писем типа \Components\Entity\EmailNotification::TO_SUBSCRIBED_AUTHORS_ON_DISTRIBUTION $all_added_size = 0; $fna = 0; if ($notification['type'] == \Components\Entity\EmailNotification::TO_SUBSCRIBED_AUTHORS_ON_DISTRIBUTION && !empty($message['order_id'])) { $files = get_order_files($message['order_id']); foreach ($files as $file) { $all_added_size += $file['size']; if ($all_added_size > 16000000) { // write to body, but not add file $fna++; } else { $attachments[] = array('path' => get_file_path($message['order_id'], $file), 'name' => $file['name']); } } } $subtext = ""; if ($fna) { $subtext = "<br><br>-----------------------------------<br>" . "Еще " . $fna . " файла(ов) не были добавлены к письму из-за ограничения размеров"; } // Это условие проверено выше //if ( \Components\Entity\EmailNotificationType::isSendable($notification['type']) ) //{ $email = new \Components\Classes\Email(); $email->IsHTML(true); $email->setData(array('email' => $notification['receiver_email'], 'name' => ''), $message['subject'], $message['text'] . $subtext, $attachments, true, Message::getReceiverEmailAndName($message['creator_id']), Message::getReceiverEmailAndName($message['creator_id'])); try { $send_result = $email->send(); if ($send_result) { \Components\Entity\EmailNotification::delete($notification['id']); $good_cnt++; } else { \Components\Entity\EmailNotification::update($notification['id'], array('attempts_to_send' => $notification['attempts_to_send'] + 1, 'last_attempt' => time(), 'last_error' => $email->ErrorInfo)); } } catch (\Components\Exceptions\Exception $e) { \Components\Entity\EmailNotification::update($notification['id'], array('attempts_to_send' => $notification['attempts_to_send'] + 1, 'last_attempt' => time())); } unset($email); //} } } $notification_index++; } db::query("update ofc_sys_log set p_value=" . $execution_time_start . " where p_name='email_notify_last_tm_start'"); db::query("update ofc_sys_log set p_value=" . (time() - $execution_time_start) . " where p_name='email_notify_last_tm_work'"); db::query("update ofc_sys_log set p_value=" . $notification_index . " where p_name='email_notify_last_all_cnt'"); db::query("update ofc_sys_log set p_value=" . $good_cnt . " where p_name='email_notify_last_good_cnt'"); }
if (!empty($_GET['t'])) { $type = $_GET['t']; } switch ($type) { case NOTIFICATION_TYPE_NORMAL: default: if (!\Components\Entity\EmailNotificationType::isPersistable(\Components\Entity\EmailNotification::TO_AUTHOR_ON_REMIND_NORMAL)) { $GUI->ERR("Напоминание отключено!"); page_ReloadSec(); return; } $failed_emails = Author::saveMessageAndEnqueueEmail($order_id, array($order_info['author_id']), 'u' . $_SESSION['user']['data']['id'], 'Напоминание по заказу №' . $order_id . ' ' . $order_info['subject'], 'Уважаемый автор, напоминаем Вам о том, что данный заказ должен быть прислан Вами на почту или прикреплен на сайте в личном кабинете сегодня. Сообщите о состоянии заказа. С уважением, ' . sotr_getFullName($_SESSION['user']['data']['id']), \Components\Entity\EmailNotification::TO_AUTHOR_ON_REMIND_NORMAL); break; case NOTIFICATION_TYPE_URGENT: if (!\Components\Entity\EmailNotificationType::isPersistable(\Components\Entity\EmailNotification::TO_AUTHOR_ON_REMIND_URGENT)) { $GUI->ERR("Напоминание отключено!"); page_ReloadSec(); return; } $failed_emails = Author::saveMessageAndEnqueueEmail($order_id, array($order_info['author_id']), 'u' . $_SESSION['user']['data']['id'], 'СРОЧНО ответьте по заказу №' . $order_id . ' ' . $order_info['subject'], 'Срочно ответьте о состоянии данного заказа, по которому дата сдачи Вами сорвана. Предупреждаем что срыв срока заказа позволит нам не выплатить Вам гонорар и/или наложить штраф. Мы всегда выполняем свои обязательства по оплате перед Вами и ждем с Вашей стороны того же, а именно соблюдение сроков и требований. Спасибо за понимание. С уважением, ' . sotr_getFullName($_SESSION['user']['data']['id']), \Components\Entity\EmailNotification::TO_AUTHOR_ON_REMIND_URGENT); break; } if (!empty($failed_emails)) { $GUI->ERR("Не удалось отправить заказ на " . $failed_emails[0]['email']); page_ReloadSec(); } AuthorNotification::create(array('author_id' => $order_info['author_id'], 'order_id' => $order_id, 'date' => date('Y-m-d H:i:s'), 'type' => $type)); $GUI->OK("Напоминание отправлено"); page_ReloadSec(); break;
function assign_order_to_manager($Frm, $Err) { if (!$Err) { $order_id = $Frm->GetNmValueI("order_id"); $manager_id = $Frm->GetNmValueI("manager_id"); Order::update($order_id, array('manager_id' => $manager_id)); $do_msg = \Components\Entity\EmailNotificationType::isPersistable(\Components\Entity\EmailNotification::TO_MANAGERS_ON_MANAGER_CHANGE); if ($do_msg) { $message_id = mls_Send("u" . $manager_id, "u" . $_SESSION["user"]["data"]["id"], "На вас назначен заказ №" . $order_id, "На вас назначен заказ №" . $order_id, 1, 0); Author::enqueue_message_to_email($message_id, array($manager_id), \Components\Entity\EmailNotification::TO_MANAGERS_ON_MANAGER_CHANGE); } $old_manager_id = $Frm->GetNmValueI("old_manager_id"); if ($do_msg && $old_manager_id != 0) { $message_id = mls_Send("u" . $old_manager_id, "u" . $_SESSION["user"]["data"]["id"], "Вы сняты с заказа №" . $order_id, "Вас сняли с заказа №" . $order_id . "<br>Причина: " . $Frm->GetNmValueH("reason"), 1, 0); Author::enqueue_message_to_email($message_id, array($old_manager_id), \Components\Entity\EmailNotification::TO_MANAGERS_ON_MANAGER_CHANGE); } $txt = "Заказ закреплен"; if ($do_msg) { $txt .= ", уведомления отправлены"; } $Frm->_gui->OK($txt); page_reloadAll(); } }
public static function isPersistable($type_id) { if (EmailNotificationType::isValidType($type_id)) { if (in_array($type_id, EmailNotificationType::getPersistableIds())) { return true; } } return false; }