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'");
}
Ejemplo n.º 2
0
 public static function create_order($order_parameters)
 {
     $result = array('status' => false, 'msg' => '');
     $message = array();
     if (empty($order_parameters['client_id'])) {
         $result['msg'] = "Id клиента не указан";
         return $result;
     }
     if ($order_parameters['work'] == 0 && !strlen($order_parameters['work_usr'])) {
         $order_parameters['work_usr'] = "******";
         //            $message[] = "Не указан вид работы";
     }
     if ($order_parameters['disc'] == 0 && !strlen($order_parameters['disc_usr'])) {
         $order_parameters['disc_usr'] = "******";
         //          $message[] = "Не указана дисциплина";
     }
     if ($order_parameters['pgmax'] && $order_parameters['pgmax'] < $order_parameters['pgmin']) {
         $message[] = "Неверно указано макс. число страниц";
     }
     if ($order_parameters['srcmax'] && $order_parameters['srcmax'] < $order_parameters['srcmin']) {
         $message[] = "Неверно указано макс. число источников";
     }
     if (count($message)) {
         $result['msg'] = join("\n", $message);
         return $result;
     }
     $date = mktime();
     $filial_id = db::get_single_value("SELECT filial_id FROM " . TBL_PREF . "clients WHERE id = " . db::input($order_parameters['client_id']) . "");
     if (!$filial_id) {
         $filial_id = $order_parameters['filial_id'];
     }
     if (!$filial_id) {
         $query = "SELECT ftc.filial_id FROM " . TBL_PREF . "clients c  JOIN " . TBL_PREF . "data_city dc ON dc.name = c.city JOIN " . TBL_PREF . "filial_to_city ftc ON ftc.city_id = dc.id" . " WHERE c.id = " . db::input($order_parameters['client_id']) . "";
         $filial_id = db::get_single_value($query);
     }
     $order_id = Order::create(array("filial_id" => $filial_id, "klient_id" => $order_parameters['client_id'], "vuz_id" => $order_parameters['vuz'], "vuz_user" => $order_parameters['vuz_usr'], "type_id" => $order_parameters['work'], "type_user" => $order_parameters['work_usr'], "napr_id" => $order_parameters['napr'], "disc_id" => $order_parameters['disc'], "disc_user" => $order_parameters['disc_usr'], "time_kln" => $order_parameters['time_kln'], "payment_id" => $order_parameters['opl'], "subject" => $order_parameters['subj'], "about_kln" => $order_parameters['treb'], "kurs" => $order_parameters['kurs'], "prakt_pc" => $order_parameters['prakt'], "pages_min" => $order_parameters['pgmin'], "pages_max" => $order_parameters['pgmax'], "src_min" => $order_parameters['srcmin'], "src_max" => $order_parameters['srcmax'], "from_id" => 4));
     //        foreach ($_FILES as $file) {
     //            if (is_uploaded_file($file["tmp_name"])) {
     //                $extension = pathinfo($file['name']);
     //                $extension = strtolower($extension['extension']);
     //
     //                $file_id = \Components\Entity\OrderFile::create() ::attachFile($order_id, 0, $file["name"], $file["size"]);
     //
     //                if (!$file_id) {
     //                    $result['msg'] = "Ошибка при загрузке файла";
     //                    return $result;
     //                } else {
     //                    $dir = DIR_FS_ORDER_FILES . $order_id . '/';
     //                    if (!is_dir(DIR_FS_ORDER_FILES)) {
     //                        create_path('order_files', DIR_FS_DOCUMENT_ROOT);
     //                    }
     //                    if (!is_dir($dir)) {
     //                        create_path($order_id, DIR_FS_ORDER_FILES);
     //                    }
     //
     //                    $file_name = $file_id . '.' . $extension;
     //
     //                    if (!move_uploaded_file($file['tmp_name'], $dir . $file_name)) {
     //                        Order::deleteAttachedFile($file_id);
     //                        $result['msg'] = "Ошибка при сохранении файла";
     //                        return $result;
     //                    }
     //                }
     //            }
     //        }
     if ($order_id) {
         ////////////////////////
         // Текст клиенту
         $client = Client::find($order_parameters['client_id']);
         $filial = \Components\Entity\Filial::find($filial_id);
         $txt = "<p>Здравствуйте" . (empty($client["fio"]) ? "" : ", " . $client["fio"]) . "!</p>";
         // Если первый раз
         if (@$_SESSION["new_klient_added"]) {
             $txt .= "<p>Мы очень рады, что Вы решили воспользоваться нашими услугами и высоко ценим Ваше доверие!</p>";
         } else {
             $txt .= "<p>Спасибо, что Вы с нами! Для постоянных клиентов у нас всегда есть интересные и выгодные предложения!</p>";
         }
         $zak = "<p>Номер заказа: " . $order_id . "<br>" . "Дата: " . date("d.m.Y") . "<br>";
         $zak .= "Вид работы: ";
         if (!empty($order_parameters['work_usr'])) {
             $zak .= $order_parameters['work_usr'] . "<br>";
         } else {
             $worktype = \Components\Entity\Worktypes::find($order_parameters['work']);
             $zak .= $worktype['name'] . "<br>";
         }
         $zak .= "Дисциплина: ";
         if ($order_parameters['disc_usr']) {
             $zak .= $order_parameters['disc_usr'] . "<br>";
         } else {
             $discipline = \Components\Entity\Discipline::find($order_parameters['disc']);
             $zak .= $discipline['name'] . "<br>";
             //                $zak .= $_SESSION["zf_work_predm"] . "<br>";
         }
         if ($order_parameters['subj']) {
             $zak .= "Тема работы: " . $order_parameters['subj'] . "<br>";
         }
         if ($order_parameters['treb']) {
             $zak .= "Требования: " . $order_parameters['treb'] . "<br>";
         }
         if ($order_parameters['time_kln']) {
             $zak .= "Дата сдачи: " . $order_parameters['time_kln'] . "<br>";
         }
         if ($order_parameters['pgmin'] && $order_parameters['pgmax']) {
             $zak .= "Число страниц: " . $order_parameters['pgmin'] . "-" . $order_parameters['pgmax'] . "<br>";
         }
         $txt .= "<p>Ваш заказ принят, и в ближайшее время наш менеджер свяжется с Вами.</p>" . "<p>Содержание заказа: <br>" . $zak . "</p>";
         $txt .= "<p><i>С уважением, компания по написанию студенческих работ.</i></p>";
         $email = new \Components\Classes\Email();
         $email->setData(array('email' => $client['email'], 'name' => $client['fio']), "Ваш заказ принят!", $txt, array(), true, array(), array('email' => $filial['email'], 'name' => $filial['name']));
         //$m->SMTPDebug = true;
         $mailErrors = array();
         if (!$email->send()) {
             $mailErrors[] = "Ошибки при отправке письма клиенту: " . $email->ErrorInfo;
         }
         ////////////////////////
         // Текст в приемную заказов
         $zak .= "<p>Заказчик:<br>";
         if (@$_SESSION["new_klient_added"]) {
             $zak .= "Новая регистрация<br>";
         }
         $zak .= "id: " . $client["id"] . "<br>" . "Имя: " . $client["fio"] . "<br>" . "Почта: " . $client["email"] . "<br>" . "Телефон: " . $client["telnum"] . "<br>" . "Город: " . $client["city"] . "<br>" . "Другие контакты: " . $client["contacts"] . "<br>";
         if (!empty($mailErrors)) {
             $zak .= join('<br>', $mailErrors);
         }
         $message_id = \Components\Entity\Message::create(array('parent_id' => 0, 'order_id' => $order_id, 'klient_id' => $client["id"], 'visit_id' => 0, 'tender_id' => 0, 'created' => time(), 'creator_id' => 'k' . $client["id"], 'addr' => 'u' . $filial['user_id'], 'subject' => "Поступил новый заказ #" . $order_id, 'text' => $zak, 'prior' => 1, 'uvedom' => 1, 'readed' => 0, 'needansv' => 0, 'basket' => 0));
         if (!empty($message_id)) {
             \Components\Classes\Author::enqueue_message_to_email($message_id, $filial['user_id'], \Components\Entity\EmailNotification::TO_MANAGER_ON_CLIENT_CREATED_ORDER);
         }
         // Прикалываем файлы
         $files = $_FILES;
         // move file
         if (count($files)) {
             $path = DIR_FS_ORDER_FILES . $order_id;
             if (!file_exists($path)) {
                 mkdir($path);
             }
             foreach ($files as $f) {
                 $fid = \Components\Entity\OrderFile::create(array('order_id' => $order_id, 'creator_id' => 0, 'created' => time(), 'name' => $f["name"], 'size' => $f["size"]));
                 if ($fid > 0) {
                     $ext = substr($f["name"], strrpos($f["name"], ".") + 1);
                     $f_s = fopen($f["tmp_name"], "r");
                     $f_d = fopen($path . "/" . $fid . "." . $ext, "w");
                     fwrite($f_d, fread($f_s, $f["size"]));
                     fclose($f_s);
                     fclose($f_d);
                 }
                 //                    unlink($f["path"]);
             }
         }
     }
     return self::generate_response(true, "OK", array('id' => $order_id, 'date' => $date));
 }