/**
     * This method is called upon successful creation of a new contact
     * It sends a welcome message to the new user
     *
     * Этот метод вызывается после успешного создания нового контакта
     * В нём будет отправлено приветственное письмо новому пользователю
     *
     * @param waContact $contact
     */
    public function afterSignup(waContact $contact)
    {
        // Adding contact to system category guestbook2 (named by the app ID)
        // to be able to easily view all contacts registered in the guestbook
        // or who have left a comment, in the Contacts app
        // Добавляем контакт в системную категорию guestbook2 (по ID приложения)
        // Чтобы в приложении Контакты можно было легко посмотреть все контакты,
        // которые были зарегистрированы в гостевой книге, либо что-то написали в ней
        $contact->addToCategory($this->getAppId());
        // Getting contact's main email address
        // Получаем главный email контакта
        $email = $contact->get('email', 'default');
        // If not specified, do nothing
        // Если он не задан, ничего не делаем
        if (!$email) {
            return;
        }
        // Generating random hash
        // Генерируем случайный хэш
        $hash = md5(uniqid(time(), true));
        // Saving the hash in contact info table with the app id
        // Сохраняем этот хэш в таблице свойств контакта, указывая приложение
        $contact->setSettings($this->getAppId(), 'confirm_hash', $hash);
        // Adding contact id to the hash for easier search and verification by hash (see guestbook2FrontendConfirmAction)
        // Добавляем в хэш номер контакта, чтобы было проще искать и проверять по хэшу (см. guestbook2FrontendConfirmAction)
        $hash = substr($hash, 0, 16) . $contact->getId() . substr($hash, 16);
        // Creating confirmation link with an absolute URL
        // Формируем абсолютную ссылку подтверждения
        $confirmation_url = wa()->getRouteUrl('/frontend/confirm', true) . "?hash=" . $hash;
        // Creating a link to the app's home page with an absolute URL
        // Формируем абсолютную ссылку на главную страницу приложения
        $root_url = wa()->getRouteUrl('/frontend', true);
        // Getting account name
        // Получаем название аккаунта
        $app_settings_model = new waAppSettingsModel();
        $account_name = htmlspecialchars($app_settings_model->get('webasyst', 'name', 'Webasyst'));
        // Generating message body
        // Формируем тело письма
        $body = _w('Hi') . ' ' . htmlspecialchars($contact->getName()) . ',<br>
<br>
' . sprintf(_w('Please confirm your account at %s by clicking this link:'), $account_name) . '<br>
<a href="' . $confirmation_url . '"><strong>' . $confirmation_url . '</strong></a><br>
<br>
--<br>
' . $account_name . '<br>
<a href="' . $root_url . '">' . $root_url . '</a>';
        $subject = _w('Confirm your account');
        // Sending email message
        // Отправляем письмо
        $message = new waMailMessage($subject, $body);
        $message->setTo($email, $contact->getName());
        $message->send();
    }
Пример #2
0
 public function sendForm($form_id)
 {
     $form_model = new wformsFormModel();
     $field_model = new wformsFieldModel();
     $field_values_model = new wformsFieldValuesModel();
     $form = $form_model->getById($form_id);
     if (!$form) {
         throw new waException('Форма #' . $form_id . ' не найдена');
     }
     $fields = $field_model->getFormFields($form_id);
     foreach ($fields as $field) {
         if ($field['type'] != 'file') {
             $value = waRequest::post('field_' . $field['id']);
             if ($field['required'] && empty($value)) {
                 throw new waException('Ошибка отправки формы. Заполните обязательные поля');
             }
             if (is_array($value)) {
                 $data[$field['name']] = implode(', ', $value);
             } else {
                 $data[$field['name']] = $value;
             }
         }
     }
     if (!wa()->getCaptcha()->isValid()) {
         throw new waException('Капча введена неверно');
     }
     $view = wa()->getView();
     $view->assign('data', $data);
     $template_path = wa()->getAppPath('templates/actions/frontend/Message.html', 'wforms');
     $html = $view->fetch($template_path);
     $message = new waMailMessage($form['title'], $html);
     $message->setTo($form['to']);
     foreach ($fields as $field) {
         if ($field['type'] == 'file') {
             $file = waRequest::file('field_' . $field['id']);
             if ($file->uploaded()) {
                 $message->addAttachment($file->tmp_name, $field['name'] . '.' . $file->extension);
             }
         }
     }
     if ($form['from']) {
         $message->setFrom($form['from']);
     }
     if ($message->send()) {
         return true;
     }
     return false;
 }
Пример #3
0
 public function encodeEmail($email)
 {
     if (!self::$_idna) {
         self::$_idna = new waIdna();
     }
     return self::$_idna->encode($email);
 }
 public function run()
 {
     $app_settings_model = new waAppSettingsModel();
     $contact_settings_model = new waContactSettingsModel();
     $app_settings_model->set('blog', 'last_reminder_cron_time', time());
     // remider settings for all users
     $reminders = $contact_settings_model->select('contact_id, value')->where("app_id='blog' AND name='reminder'")->fetchAll('contact_id', true);
     if (!$reminders) {
         return;
     }
     $time = time();
     // do job no more one time in 24 hours
     $last_cron_times = $contact_settings_model->select('contact_id')->where("app_id='blog' AND name='last_reminder_cron_time' AND value <= " . ($time - 86400))->fetchAll('contact_id', true);
     $reminders_allowed = array_keys($last_cron_times);
     if (!$reminders_allowed) {
         return;
     }
     $post_model = new blogPostModel();
     $backend_url = $app_settings_model->get('blog', 'backend_url', wa()->getRootUrl(true) . wa()->getConfig()->getBackendUrl());
     $message_count = 0;
     foreach ($reminders_allowed as $contact_id) {
         $days = $reminders[$contact_id];
         // get all deadline posts for this contact
         $posts = $post_model->select("id, title, datetime")->where("status='" . blogPostModel::STATUS_DEADLINE . "' AND contact_id=" . $contact_id . " AND datetime < '" . date('Y-m-d H:i:s', $time + $days * 86400) . "'")->order('datetime')->fetchAll();
         if ($posts) {
             $contact = new waContact($contact_id);
             $email = $contact->get('email', 'default');
             $message = new waMailMessage(_w('Scheduled blog posts'), $this->getMessage($posts, $time, $backend_url));
             try {
                 $message->setTo($email);
                 if ($message->send()) {
                     $message_count++;
                 }
             } catch (Exception $e) {
             }
         }
         $contact_settings_model->set($contact_id, 'blog', 'last_reminder_cron_time', $time);
     }
     /**
      * Notify plugins about sending reminder
      * @event followup_send
      * @return void
      */
     wa()->event('reminder_send', $message_count);
 }
    /**
     * Этот метод вызывается после успешного создания нового контакта
     * В нём будет отправлено приветственное письмо новому пользователю
     * @param waContact $contact
     */
    public function afterSignup(waContact $contact)
    {
        // Добавляем контакт в системную категорию guestbook2 (по ID приложения)
        // Чтобы в приложении контакты можно было легко посмотреть все контакты,
        // которые были зарегистрированы в гостевой книге, либо что-то написали в ней
        $contact->addToCategory($this->getAppId());
        // Получаем главный email контакта
        $email = $contact->get('email', 'default');
        // Если он не задан, ничего не делаем
        if (!$email) {
            return;
        }
        // Генерируем случайный хэш
        $hash = md5(uniqid(time(), true));
        // Сохраняем этот хэш в таблице свойств контакта, указывая приложение
        $contact->setSettings($this->getAppId(), 'confirm_hash', $hash);
        // Добавляем в хэш номер контакта, чтобы было проще искать и проверять по хэшу (см. guestbook2FrontendConfirmAction)
        $hash = substr($hash, 0, 16) . $contact->getId() . substr($hash, 16);
        // Формируем абсолютную ссылку подтверждения
        $confirmation_url = wa()->getRouteUrl('/frontend/confirm', true) . "?hash=" . $hash;
        // Формируем абсолютную ссылку на главную страницу приложения
        $root_url = wa()->getRouteUrl('/frontend', true);
        // Получаем название аккаунта
        $app_settings_model = new waAppSettingsModel();
        $account_name = htmlspecialchars($app_settings_model->get('webasyst', 'name', 'Webasyst'));
        // Формируем тело письма
        $body = _w('Hi') . ' ' . htmlspecialchars($contact->getName()) . ',<br>
<br>
' . sprintf(_w('Please confirm your account at %s by clicking this link:'), $account_name) . '<br>
<a href="' . $confirmation_url . '"><strong>' . $confirmation_url . '</strong></a><br>
<br>
--<br>
' . $account_name . '<br>
<a href="' . $root_url . '">' . $root_url . '</a>';
        $subject = _w('Confirm your account');
        // Отправляем письмо
        $message = new waMailMessage($subject, $body);
        $message->setTo($email, $contact->getName());
        $message->send();
    }
 public function run($params = NULL)
 {
     $app_settings_model = new waAppSettingsModel();
     $app_settings_model->set(array('blog', 'emailsubscription'), 'last_emailsubscription_cron_time', time());
     $model = new blogEmailsubscriptionLogModel();
     $row = $model->getByField('status', 0);
     if ($row) {
         $post_id = $row['post_id'];
         $post_model = new blogPostModel();
         $post = $post_model->getById($post_id);
         $blog_model = new blogBlogModel();
         $blog = $blog_model->getById($post['blog_id']);
         $subject = $blog['name'] . ': ' . $post['title'];
         $post_title = htmlspecialchars($post['title']);
         if ($blog['status'] == blogBlogModel::STATUS_PUBLIC) {
             $post_url = blogPost::getUrl($post);
         } else {
             $app_settings_model = new waAppSettingsModel();
             $post_url = $app_settings_model->get(array('blog', 'emailsubscription'), 'backend_url', wa()->getRootUrl(true) . wa()->getConfig()->getBackendUrl());
             $post_url .= "/blog/?module=post&id=" . $post_id;
         }
         $blog_name = htmlspecialchars($blog['name']);
         $body = '<html><body>' . sprintf(_wp("New post in the blog “%s”"), $blog_name) . ': <strong><a href="' . $post_url . '">' . $post_title . '</a></strong></body></html>';
         $message = new waMailMessage();
         $message->setEncoder(Swift_Encoding::getBase64Encoding());
         $message->setSubject($subject);
         $message->setBody($body);
         $rows = $model->getByField(array('status' => 0, 'post_id' => $post_id), true);
         $message_count = 0;
         foreach ($rows as $row) {
             try {
                 $message->setTo($row['email'], $row['name']);
                 $status = $message->send() ? 1 : -1;
                 $model->setStatus($row['id'], $status);
                 if ($status) {
                     $message_count++;
                 }
             } catch (Exception $e) {
                 $model->setStatus($row['id'], -1, $e->getMessage());
             }
         }
         /**
          * Notify plugins about sending emailsubscripition
          * @event followup_send
          * @return void
          */
         wa()->event('emailsubscription_send', $message_count);
     }
 }
 /**
  * @param string $to - email
  * @param string $url - url to reset password
  * @return bool
  */
 protected function send($to, $url)
 {
     $this->view->assign('url', $url);
     $subject = _ws("Password recovery");
     $template_file = $this->getConfig()->getConfigPath('mail/RecoveringPassword.html', true, 'webasyst');
     if (file_exists($template_file)) {
         $body = $this->view->fetch($template_file);
     } else {
         $body = $this->view->fetch(wa()->getAppPath('templates/mail/RecoveringPassword.html', 'webasyst'));
     }
     $this->view->clearAllAssign();
     try {
         $m = new waMailMessage($subject, $body);
         $m->setTo($to);
         return (bool) $m->send();
     } catch (Exception $e) {
         return false;
     }
 }
Пример #8
0
 protected static function sendEmail($n, $data)
 {
     $general = wa('shop')->getConfig()->getGeneralSettings();
     if (!empty($n['from'])) {
         $from = $n['from'];
     } else {
         $from = $general['email'];
     }
     /**
      * @var waContact $customer
      */
     $customer = $data['customer'];
     if ($n['to'] == 'customer') {
         $email = $customer->get('email', 'default');
         if (!$email) {
             return;
         }
         $to = array($email);
         $log = sprintf(_w("Notification <strong>%s</strong> sent to customer."), $n['name']);
     } elseif ($n['to'] == 'admin') {
         if (!$general['email']) {
             return;
         }
         $to = array($general['email']);
         $log = sprintf(_w("Notification <strong>%s</strong> sent to store admin."), $n['name']);
     } else {
         $to = explode(',', $n['to']);
         $log = sprintf(_w("Notification <strong>%s</strong> sent to %s."), $n['name'], $n['to']);
     }
     $view = wa()->getView();
     foreach (array('shipping', 'billing') as $k) {
         $address = shopHelper::getOrderAddress($data['order']['params'], $k);
         $formatter = new waContactAddressOneLineFormatter(array('image' => false));
         $address = $formatter->format(array('data' => $address));
         $view->assign($k . '_address', $address['value']);
     }
     $order_id = $data['order']['id'];
     $data['order']['id'] = shopHelper::encodeOrderId($order_id);
     $view->assign('order_url', wa()->getRouteUrl('/frontend/myOrderByCode', array('id' => $order_id, 'code' => $data['order']['params']['auth_code']), true));
     $view->assign($data);
     $subject = $view->fetch('string:' . $n['subject']);
     $body = $view->fetch('string:' . $n['body']);
     $message = new waMailMessage($subject, $body);
     $message->setTo($to);
     if ($n['to'] == 'admin') {
         if ($customer_email = $customer->get('email', 'default')) {
             $message->addReplyTo($customer_email);
         }
     }
     if ($from) {
         $message->setFrom($from, $general['name']);
     }
     if ($message->send()) {
         $order_log_model = new shopOrderLogModel();
         $order_log_model->add(array('order_id' => $order_id, 'contact_id' => null, 'action_id' => '', 'text' => '<i class="icon16 email"></i> ' . $log, 'before_state_id' => $data['order']['state_id'], 'after_state_id' => $data['order']['state_id']));
     }
 }
Пример #9
0
 /**
  * @param string $to
  * @param array $errors
  * @return bool
  */
 public function sendEmail($to, &$errors)
 {
     if (!$to) {
         $app_settings_model = new waAppSettingsModel();
         $to = $app_settings_model->get('webasyst', 'email');
     }
     if (!$to) {
         $errors['all'] = _ws('Recipient (administrator) email is not valid');
         return false;
     }
     if (!wa($this->app_id)->getCaptcha()->isValid()) {
         $errors['captcha'] = _ws('Invalid captcha');
     }
     $email = $this->post('email');
     $email_validator = new waEmailValidator();
     $subject = trim($this->post('subject', _ws('Website request')));
     $body = trim($this->post('body'));
     if (!$body) {
         $errors['body'] = _ws('Please define your request');
     }
     if (!$email) {
         $errors['email'] = _ws('Email is required');
     } elseif (!$email_validator->isValid($email)) {
         $errors['email'] = implode(', ', $email_validator->getErrors());
     }
     if (!$errors) {
         $m = new waMailMessage($subject, nl2br($body));
         $m->setTo($to);
         $m->setFrom(array($email => $this->post('name')));
         if (!$m->send()) {
             $errors['all'] = _ws('An error occurred while attempting to send your request. Please try again in a minute.');
         } else {
             return true;
         }
     }
     return false;
 }
Пример #10
0
 public function send(waContact $contact)
 {
     $email = $contact->get('email', 'default');
     if (!$email) {
         return;
     }
     $subject = _ws("Thank you for signing up!");
     $this->view->assign('email', $email);
     $this->view->assign('name', $contact->getName());
     // send email confirmation link
     $this->sendConfirmationLink($contact);
     $template_file = $this->getConfig()->getConfigPath('mail/Signup.html', true, 'webasyst');
     if (file_exists($template_file)) {
         $body = $this->view->fetch('string:' . file_get_contents($template_file));
     } else {
         $body = $this->view->fetch(wa()->getAppPath('templates/mail/Signup.html', 'webasyst'));
     }
     try {
         $m = new waMailMessage($subject, $body);
         $m->setTo($email, $contact->getName());
         $from = $this->getFrom();
         if ($from) {
             $m->setFrom($from);
         }
         return (bool) $m->send();
     } catch (Exception $e) {
         return false;
     }
 }
Пример #11
0
 /**
  * Helper to send one message: used during real sending, as well as for test emails from follow-ups settings page.
  */
 public static function sendOne($f, $o, $customer, $contact, $to, $view = null, $general = null)
 {
     if (!$view) {
         $view = wa()->getView();
     }
     if (!$general) {
         $general = wa('shop')->getConfig()->getGeneralSettings();
     }
     $workflow = new shopWorkflow();
     $items_model = new shopOrderItemsModel();
     $o['items'] = $items_model->getItems($o['id']);
     foreach ($o['items'] as &$i) {
         if (!empty($i['file_name'])) {
             $i['download_link'] = wa()->getRouteUrl('/frontend/myOrderDownload', array('id' => $o['id'], 'code' => $o['params']['auth_code'], 'item' => $i['id']), true);
         }
     }
     unset($i);
     // Assign template vars
     $view->clearAllAssign();
     $view->assign('followup', $f);
     // row from shop_followup
     $view->assign('order', $o);
     // row from shop_order, + 'params' key
     $view->assign('customer', $contact);
     // shopCustomer
     $view->assign('order_url', wa()->getRouteUrl('/frontend/myOrderByCode', array('id' => $o['id'], 'code' => $o['params']['auth_code']), true));
     $view->assign('status', $workflow->getStateById($o['state_id'])->getName());
     // $shipping_address, $billing_address
     foreach (array('shipping', 'billing') as $k) {
         $address = shopHelper::getOrderAddress($o['params'], $k);
         $formatter = new waContactAddressOneLineFormatter(array('image' => false));
         $address = $formatter->format(array('data' => $address));
         $view->assign($k . '_address', $address['value']);
     }
     // Build email from template
     $subject = $view->fetch('string:' . $f['subject']);
     $body = $view->fetch('string:' . $f['body']);
     $from = $general['email'];
     if ($f['from']) {
         $from = $f['from'];
     }
     // Send the message
     $message = new waMailMessage($subject, $body);
     $message->setTo($to);
     $message->setFrom($from, $general['name']);
     return $message->send();
 }
 public function execute()
 {
     $modelNotifierConfig = new shopNotifierConfigModel();
     $modelNotifierLog = new shopNotifierLogModel();
     $n_date = array('w' => 'week', 'd' => 'days', 'm' => 'hour', 'h' => 'minute');
     $all_notifications = $modelNotifierConfig->getAll();
     foreach ($all_notifications as $notification) {
         $last_event_date = strtotime($modelNotifierLog->getLastDateByConfigId($notification['id']));
         $last_event = strtotime('+' . $notification['repeat_number_time'] . ' ' . $n_date[$notification['repeat_period']], $last_event_date);
         if (date('Y-m-d H:i:s', $last_event) < date('Y-m-d H:i:s')) {
             $states = (array) json_decode($notification['state_name']);
             $last_time = strtotime('-' . $notification['number_time'] . ' ' . $n_date[$notification['period']], $last_event_date);
             $orders = array();
             $orders_new = array();
             foreach ($states as $s) {
                 if ($s == 'new') {
                     $collection = new shopOrdersCollection('search/state_id=new&create_datetime<' . date('Y-m-d H:i:s', $last_time));
                     $orders_new = $collection->getOrders('*,params,items,contact');
                 } else {
                     $states_without_new[] = $s;
                 }
             }
             $state_for_collection = is_array($states_without_new) ? implode('||', $states_without_new) : $states_without_new[0];
             $collection = new shopOrdersCollection('search/state_id=' . $state_for_collection . '&update_datetime<' . date('Y-m-d H:i:s', $last_time));
             $orders = $collection->getOrders('*,params,items,contact');
             if (is_array($orders_new)) {
                 $orders = array_merge($orders, $orders_new);
             }
             $emails = array();
             $notification['data_contact'] = json_decode($notification['data_contact']);
             foreach ($notification['data_contact']->contact as $contact) {
                 $user = new waContact($contact);
                 //                    $email = array();
                 $email = $user->get('email');
                 $emails[$email[0]['value']] = $user->get('name');
             }
             if (!empty($notification['data_contact']->group)) {
                 $modelContactCategory = new waContactCategoryModel();
                 foreach ($notification['data_contact']->group as $group) {
                     $contacts = $modelContactCategory->getByField('category_id', $group);
                     //                      ->query("SELECT * FROM wa_contact_categories WHERE category_id = '".$gr."'")->fetchAll('contact_id');
                     foreach ($contacts as $key => $contact) {
                         $user = new waContact($key);
                         $email = array();
                         $email = $user->get('email');
                         $emails[$email[0]['value']] = $user->get('name');
                     }
                 }
             }
             $view = wa()->getView();
             $shop_config = $general = wa('shop')->getConfig()->getGeneralSettings();
             $from = $shop_config['email'];
             if (!$from) {
                 $from = '*****@*****.**';
             }
             if (!empty($notification['send_email']) && self::isValidEmail($notification['send_email'])) {
                 $from = $notification['send_email'];
             }
             $body = file_get_contents(shopNotifierPlugin::path($notification['template']));
             //TODO: File read error
             if ($notification['group_senders'] == 1) {
                 if ($notification['save_to_order_log'] == 1) {
                     $order_log_model = new shopOrderLogModel();
                     foreach ($orders as $order) {
                         $order_log_model->add(array('order_id' => $order['id'], 'contact_id' => wa()->getUser()->getId(), 'before_state_id' => $order['state_id'], 'after_state_id' => $order['state_id'], 'text' => 'Отправлено уведомление на адреса из оповещания ' . $notification['config_name'], 'action_id' => 'comment'));
                     }
                 }
                 $view->clearAllAssign();
                 $view->assign('orders', $orders);
                 $subject_string = 'Обратите внимание на заказы';
                 $subject = $view->fetch('string:' . $subject_string);
                 $body = $view->fetch('string:' . $body);
                 $message = new waMailMessage($subject, $body);
                 $message->setTo($emails);
                 $message->setFrom($from);
                 $message->send();
             } else {
                 foreach ($orders as $order) {
                     if ($notification['save_to_order_log'] == 1) {
                         $order_log_model = new shopOrderLogModel();
                         $order_log_model->add(array('order_id' => $order['id'], 'contact_id' => wa()->getUser()->getId(), 'before_state_id' => $order['state_id'], 'after_state_id' => $order['state_id'], 'text' => 'Отослано уведомление на емайлы из оповещания ' . $notification['config_name'], 'action_id' => 'comment'));
                     }
                     $view->clearAllAssign();
                     $view->assign('order', $order);
                     $subject_string = 'Заказ ' . shopHelper::encodeOrderId($order['id']);
                     $subject = $view->fetch('string:' . $subject_string);
                     $body = $view->fetch('string:' . $body);
                     $message = new waMailMessage($subject, $body);
                     $message->setTo($emails);
                     $message->setFrom($from);
                     $message->send();
                 }
             }
             $modelNotifierLog->add(array('config_id' => $notification['id']));
         }
     }
 }
Пример #13
0
 public function sendEmail($to, &$errors)
 {
     if (!$to) {
         $to = waMail::getDefaultFrom();
     }
     if (!$to) {
         $errors['all'] = 'Recipient (administrator) email is not valid';
         return false;
     }
     if (!$this->wa->getCaptcha()->isValid()) {
         $errors['captcha'] = _ws('Invalid captcha');
     }
     $email = $this->post('email');
     $email_validator = new waEmailValidator();
     $subject = trim($this->post('subject', 'Website request'));
     $body = trim($this->post('body'));
     if (!$body) {
         $errors['body'] = 'Please define your request';
     }
     if (!$email_validator->isValid($email)) {
         $errors['email'] = implode(', ', $email_validator->getErrors());
     }
     if (!$errors) {
         $m = new waMailMessage($subject, $body);
         $m->setTo($to);
         $m->setFrom(array($email => $this->post('name')));
         if (!$m->send()) {
             $errors['all'] = 'An error occurred while attempting to send your request. Please try again in a minute.';
         } else {
             return true;
         }
     }
     return false;
 }