public function addUser($data) { $vData = $data; $validation = Validation::factory($vData); $validation->rule('username', 'not_empty'); $validation->rule('username', 'email'); if (!$validation->check()) { $this->errors = $validation->errors('userErrors'); return FALSE; } $pass = Arr::get($data, 'pass'); $username = addslashes(Arr::get($data, 'username')); $myuser = ORM::factory('Myuser'); $auth = Auth::instance(); $pass = $auth->hash($pass); //Создаем пользователя $myuser->username = $username; $myuser->email = $username; $myuser->password = $pass; $myuser->name = addslashes(Arr::get($data, 'name')); $myuser->phone = addslashes(Arr::get($data, 'phone')); try { $myuser->save(); //Узнаем id пользователя $add_user_id = ORM::factory("user", array("username" => $username))->id; $token = substr($auth->hash($add_user_id . $username), 0, 20); //добавляем роль пользователя $model_addrole = new Model_Addrole(); $model_addrole->user_id = $add_user_id; $model_addrole->role_id = Arr::get($data, "role"); $model_addrole->save(); //добавляем запись для активации $model_addtoken = new Model_Addtoken(); $model_addtoken->user_id = $add_user_id; $model_addtoken->token = $token; $model_addtoken->save(); //отправляем пользователю сообщение для авторизации $config = Kohana::$config->load('email'); $mbase = new Model_Base(); $options = $mbase->getOptions(); Email::connect($config); $to = $username; $subject = 'Добро пожаловать на сайт ' . $options['sitename']; $from = $config['options']['username']; $message = '<b>Отправитель</b>: ' . Kohana::$base_url . '<br>'; $message .= 'Для работы с заказами на сайте Вам необходимо активировать учетную запись. <br> <br> Ваш логин: ' . $username . '<br> Ваш пароль: ' . Arr::get($data, 'pass') . '<br><br> Для активации перейдите по <a href="' . Kohana::$base_url . 'registration?token=' . $token . '&user='******'">этой ссылке</a> <hr> Спасибо за то, что пользуетесь услугами нашего сайта. По всем вопросам обращайтесь в техподдержку: ' . $config['options']['username']; $res = Email::send($to, $from, $subject, $message, $html = TRUE); return $add_user_id; } catch (ORM_Validation_Exception $e) { $this->errors = $e->errors('validation'); return false; } }
public function action_index() { $view = View::factory('forgot_password'); $this->template->content = $view->render(); if ($this->request->method() === Request::POST) { $email = $this->request->post('email'); $user = new Model_User(); $password_recovery = new Model_Password_Recovery(); $unique_email = $user->unique_email($email); if ($unique_email === true) { throw new Exception("Email is not correct!"); } $view_for_message = View::factory('forgot_password/send_email'); $user_id = $user->get_id($email); $hash = sha1(Security::token()); $view_for_message->user_id = $user_id; $view_for_message->hash = $hash; $create_attemp = $password_recovery->create_attemp($email, $user_id, $hash); if (!$create_attemp) { throw new Exception("Cannot create attemp!"); } Email::connect(); $to = array($email); $from = array('user@localhost', 'admin'); $subject = 'Password recovery'; $message = $view_for_message->render(); $send_email = Email::send($to, $from, $subject, $message, true); if (!$send_email) { throw new Exception("Cannot send email! \n {$send_email}"); } $this->redirect('/'); } }
public function action_index() { $this->template->head = 'Registration'; if (Auth::instance()->logged_in()) { $this->redirect('message'); } else { if ($post = $this->request->post()) { try { $checkusername = ORM::factory('User')->where('username', '=', $this->request->post('username'))->find()->as_array(); $checkemail = ORM::factory('User')->where('email', '=', $this->request->post('email'))->find()->as_array(); if (!empty($checkusername['username'])) { $data['errorsignin'] = 'You are entered an existing username'; } elseif (!empty($checkemail['email'])) { $data['errorsignin'] = 'You are entered an existing email!'; } elseif ($this->request->post('password') !== $this->request->post('password_confirm')) { $data['errorsignin'] = 'You are not confirm your password'; } else { $user = ORM::factory('User')->create_user($_POST, array('username', 'email', 'password')); $user->add('roles', ORM::factory('Role', array('name' => 'login'))); $config = Kohana::$config->load('email'); Email::connect($config); $to = $this->request->post('email'); $subject = 'Message from Kohana!'; $from = '*****@*****.**'; $message = "Congratulations. You have successfully registered<br>" . "Login: "******"<br>Password: "******"login"); } } catch (ORM_Validtion_Exception $e) { $errors = $e->errors('models'); } } $this->template->content = View::factory('reg', $data); } }
public function action_registration() { Request::initial()->is_ajax() || die; $emailsignup = ORM::factory('User')->checkUser('email', $this->request->post('emailsignup')); $usernamesignup = ORM::factory('User')->checkUser('username', $this->request->post('usernamesignup')); if ($emailsignup->loaded() || $usernamesignup->loaded()) { if ($emailsignup->loaded()) { $message[0]['text'] = "User with this email is already exist!"; $message[0]['item'] = "emailsignup"; $message[0]['status'] = "error"; } if ($usernamesignup->loaded()) { $message[1]['text'] = "User with username email is already exist!"; $message[1]['item'] = "usernamesignup"; $message[1]['status'] = "error"; } die(json_encode($message)); } $token = md5(time() . $this->request->post('usernamesignup') . $this->request->post('emailsignup')); $data = array('username' => $this->request->post('usernamesignup'), 'email' => $this->request->post('emailsignup'), 'password' => $this->request->post('passwordsignup'), 'password_confirm' => $this->request->post('passwordsignup_confirm'), 'token' => $token); $user = ORM::factory('User')->create_user($data, array('username', 'email', 'password', 'token')); $url = URL::site(NULL, TRUE) . 'approved?token=' . $token; $config = Kohana::$config->load('email'); $from = $config['email']; $to = $this->request->post('emailsignup'); $subject = "Registration approval"; $text = "Thank you for registration on our site! You must follow this link to activate your account: " . $url; Email::connect($config['main']); Email::send($to, $from, $subject, $text, $html = false); $message[0]['text'] = "Link to activate your account sent for your email"; $message[0]['item'] = "emailsignup"; $message[0]['status'] = "ok"; die(json_encode($message)); }
public function action_email() { if (count($this->request->post())) { $hostname = $this->request->post('email_hostname'); $port = $this->request->post('email_port'); $username = $this->request->post('email_username'); $password = $this->request->post('email_password'); $encryption = $this->request->post('email_encryption'); $email_address = $this->request->post('email_address'); try { $config = $this->_create_email_config($hostname, $port, $username, $password, $encryption); // email_address if (strlen($email_address)) { try { Email::connect($config); Email::send($email_address, $email_address, "Beans Email Verification", "You can ignore this email - it was a self-generated message " . "used to verify your email server credentials.", FALSE); } catch (Exception $e) { return $this->_view->send_error_message("An error occurred when verifying your email settings: " . $e->getMessage()); } } Session::instance('native')->set('config_email', $config); $this->request->redirect('/install/auth'); } catch (Exception $e) { $this->_view->send_error_message($e->getMessage()); } } }
public function action_restore() { $message = false; $hash = $this->request->param('id'); $query = DB::query(Database::SELECT, 'SELECT `id` FROM `users` WHERE `restore` = "' . $hash . '" AND DATEDIFF(NOW(), `restore_date`) <= 1')->execute(); $result = $query->as_array(); if ($hash and $result) { if (!empty($_POST)) { if ($_POST['password_confirm'] == $_POST['password']) { if (strlen($_POST['password']) >= 6 and strlen($_POST['password']) <= 50) { try { $user = ORM::factory('user')->where('id', '=', $result[0]['id'])->find(); $user->change_password($_POST); $message_body = sprintf(__('forgottent.restore_message'), $_POST['password']); $mailer = Email::connect(); $message = Swift_Message::newInstance()->setSubject(__('forgotten.subject'))->setFrom('*****@*****.**')->setTo($user->email)->setBody($message_body, 'text/html;'); $mailer->send($message); DB::query(Database::UPDATE, 'UPDATE `users` SET `restore` = NULL, `restore_date` = NULL WHERE `email` = "' . $user->email . '"')->execute(); $message = array('text' => __('forgotten.email_send'), 'type' => 'success'); } catch (Kohana_Exception $e) { $message = array('text' => __('forgotten.email_send_error'), 'type' => 'danger'); } } else { $message = array('text' => __('error.password_is_short'), 'type' => 'danger'); } } else { $message = array('text' => __('error.password_not_equal'), 'type' => 'danger'); } } $this->template->content = View::factory('admin/auth/restore')->set('message', $message); } else { Request::factory('err/404')->send_headers()->execute(); } }
public function action_process_user_payments() { // уведомляем пользователей, у которых осталось мало времени пользования аккаунтом $disable_event_period = DB::select('days')->from('payment_settings')->where('status', '=', 'N')->where('system_name', '=', 'disable_event_period')->limit(1)->execute()->get('days'); if (empty($disable_event_period)) { $disable_event_period = 5; } $date = new DateTime(); $date->modify($disable_event_period - 1 . " days"); $exp = ORM::factory('user')->where(DB::expr('DATE(expires)'), '=', $date->format("Y-m-d")); $exp->reset(FALSE); if (count($exp->find_all()) > 0) { Email::connect(); $exp_date = $date->format("d.m.Y"); $title = "Действие вашего аккаунта заканчивается"; $text = "Добрый день, %s.<br><br>Действие вашего аккаунта заканчивается %s.<br>Вы можете продлить аккаунт в <a href='http://www.as-avtoservice.ru/cabinet/payment'>личном кабинете</a>"; foreach ($exp->find_all() as $e) { Email::send($e->email, array('*****@*****.**', 'Ассоциация автосервисов'), $title, sprintf($text, $e->username, $exp_date), TRUE); echo "date: " . $exp_date . " email: " . $e->email . "\n"; } } // 1) ставим статус просрочен всем $payment_expires_period = DB::select('days')->from('payment_settings')->where('status', '=', 'N')->where('system_name', '=', 'payment_expires_period')->limit(1)->execute()->get('days'); if (empty($payment_expires_period)) { $payment_expires_period = 5; } $date = new DateTime(); $date->modify("-" . $payment_expires_period . " days"); DB::update("invoice")->set(array('status' => 'E'))->where('status', '=', 'N')->where('create_date', '<', $date->format("Y-m-d"))->execute(); $date = new DateTime(); // Вимикаєм користувачів з просроченими кабінетами $query = DB::update("users")->set(array('user_type' => 'disabled'))->where_open()->where('expires', '<', $date->format("Y-m-d"))->or_where('expires', '=', NULL)->where_close()->execute(); }
protected function _execute() { if (!isset($this->_data->email)) { throw new Exception("Please provide a valid email address."); } $user = ORM::Factory('user')->where('email', 'LIKE', $this->_data->email)->find(); if (!$user->loaded()) { throw new Exception("Login error: that email address was not found."); } if (isset($this->_data->resetkey) && strlen($this->_data->resetkey)) { if (!isset($this->_data->password) or !strlen($this->_data->password)) { throw new Exception("Please provide a valid password."); } if ($user->reset != $this->_data->resetkey) { throw new Exception("Invalid reset key. Please try sending the email again."); } if ($user->reset_expiration < time()) { throw new Exception("Reset key expired. Please try sending the email again."); } $user->reset = NULL; $user->reset_expiration = NULL; $user->password_change = FALSE; $user->password = $this->_beans_auth_password($user->id, $this->_data->password); // And auto-login... $expiration = $user->role->auth_expiration_length != 0 ? time() + $user->role->auth_expiration_length : rand(11111, 99999); // Generate a random for salt. $user->auth_expiration = $expiration; $user->save(); return (object) array("auth" => $this->_return_auth_element($user, $expiration)); } else { // Generate Key $user->reset = $this->_generate_reset($user->id); $user->reset_expiration = time() + 10 * 60; $user->save(); // This is the one email we send from within the app for security. $auth_print_reset = new View_Auth_Print_Reset(); $auth_print_reset->user = $user; $message = Swift_Message::newInstance(); $message->setSubject('BeansBooks Password Reset')->setFrom(array($this->_beans_setting_get('company_email') ? $this->_beans_setting_get('company_email') : '*****@*****.**'))->setTo(array($user->email)); $auth_print_reset->swift_email_message = $message; $message = $auth_print_reset->render(); try { if (!Email::connect()) { throw new Exception("Could not send email. Does your config have correct email settings?"); } if (!Email::sendMessage($message)) { throw new Exception("Could not send email. Does your config have correct email settings?"); } } catch (Exception $e) { throw new Exception("An error occurred when sending the email: have you setup email properly in config.php?"); } } return (object) array(); }
/** * Send an email message. * * @param string|array recipient email (and name), or an array of To, Cc, Bcc names * @param string|array sender email (and name) * @param string message subject * @param string message body * @param boolean send email as HTML * @param array attachments: filenames or arrays of name, content * @return integer number of emails sent */ public static function send($to, $from, $subject, $message, $html = FALSE, $attachments = NULL) { // Connect to SwiftMailer Email::$mail === NULL and Email::connect(); // Determine the message type $html = $html === TRUE ? 'text/html' : 'text/plain'; // Create the message $message = Swift_Message::newInstance($subject, $message, $html, 'utf-8'); if (is_string($to)) { // Single recipient $message->setTo($to); } elseif (is_array($to)) { if (isset($to[0]) and isset($to[1])) { // Create To: address set $to = array('to' => $to); } foreach ($to as $method => $set) { if (!in_array($method, array('to', 'cc', 'bcc'))) { // Use To: by default $method = 'to'; } // Create method name $method = 'add' . ucfirst($method); if (is_array($set)) { // Add a recipient with name $message->{$method}($set[0], $set[1]); } else { // Add a recipient without name $message->{$method}($set); } } } if (is_string($from)) { // From without a name $message->setFrom($from); } elseif (is_array($from)) { // From with a name $message->setFrom($from[0], $from[1]); } if (!empty($attachments)) { foreach ($attachments as $attach) { if (is_array($attach)) { //Create the attachment with your data $message->attach(Swift_Attachment::newInstance($attach['content'], $attach['name'], File::mime_by_ext($attach['name']))); } else { //attachments by path $message->attach(Swift_Attachment::fromPath($attach)); } } } return Email::$mail->send($message); }
public function action_restore_pass() { $model = array(); $model["error"] = ""; $model["success"] = ""; if ($_POST) { $vData = $_POST; $validation = Validation::factory($vData); $validation->rule('email', 'not_empty'); // валидация пройдена if ($validation->check()) { $email = $_POST["email"]; $user = DB::select()->from('users')->where('email', '=', $email)->execute()->current(); // Пользователь зарегистрирован if ($user) { $model_user = new Model_User(); // Создаём новый пароль $auth = Auth::instance(); $pass = $model_user->generate_pass(); $hash_pass = $auth->hash($pass); DB::update("users")->set(array("password" => $hash_pass))->where("email", "=", $email)->execute(); //отправляем пользователю сообщение для восстановления пароля $config = Kohana::$config->load('email'); $mbase = new Model_Base(); $options = $mbase->getOptions(); Email::connect($config); $to = $email; $subject = 'Восстановление пароля на ' . $options['sitename']; $from = $config['options']['username']; $message = '<h2>Мы создали вам новый пароль для входа на <a href="' . Kohana::$base_url . '">' . $options['sitename'] . '</a>!</h2><hr>'; $message .= '<h3>Ваши реквизиты для входа:<h3>'; $message .= '<p><small>Логин: <input type="text" value="' . $email . '"></small></p>'; $message .= '<p><small>Пароль: <input type="text" value="' . $pass . '"></small></p>'; $message .= '<hr>Спасибо за то, что пользуетесь услугами нашего портала. По всем вопросам обращайтесь в техподдержку: ' . $config['options']['username']; Email::send($to, $from, $subject, $message, $html = true); $model["success"] = '<div class="alert alert-success"><p>На ваш эл. ящик отправлены инструкции по восстановлению пароля.</p></div>'; // Пользователь не зарегистрирован } else { $model["error"] .= '<div class="alert alert-danger"><p>Данный адрес эл. почты не зарегистрирован.</p></div>'; } // Валидация не пройдена } else { $model["error"] .= '<div class="alert alert-danger"><p>Вы не ввели адрес эл. почты</p></div>'; } } $this->title('Забыли пароль?'); $this->page_title('Забыли пароль?'); $this->keywords('Забыли пароль?'); $this->description('Забыли пароль?'); $this->render('user/cabinet/restore_pass.php', $model, "response"); }
public function action_send() { $config = Kohana::$config->load('email'); Email::connect($config); $to = $_POST['to']; $subject = $_POST['subject']; $from = Kohana::$config->load('site.email'); $message = $_POST['content']; $saveemail = $_POST['saveemail']; $date = $_POST['date']; if ($saveemail == 1) { ORM::factory('email')->set('to', $to)->set('subject', $subject)->set('from', $from)->set('message', $message)->set('date', $date)->save(); } Email::send($to, $from, $subject, $message, $html = TRUE); }
public function reg($name, $pass, $role) { PC::debug(array($name, $pass, $role), "reg"); $myuser = new Model_Myuser(); $auth = Auth::instance(); $hash_pass = $auth->hash($pass); //Создаем пользователя $myuser->username = $name; $myuser->email = $name; $myuser->password = $hash_pass; try { $myuser->save(); //Узнаем id пользователя //$usertmp = ORM::factory('user', array('username'=>$name)); $adduserid = DB::select()->from('users')->where('username', '=', $name)->execute()->as_array()[0]["id"]; $adduser = new Model_Addrole(); $adduser->user_id = $adduserid; $adduser->role_id = $role; $adduser->save(); //добавляем запись для активации $token = substr($auth->hash($adduserid . $name), 0, 20); $addtoken = new Model_Addtoken(); $addtoken->user_id = $adduserid; $addtoken->token = $token; $addtoken->save(); //отправляем пользователю сообщение для авторизации $config = Kohana::$config->load('email'); $mbase = new Model_Base(); $options = $mbase->getOptions(); Email::connect($config); $to = $name; $subject = 'Добро пожаловать на сайт ' . $options['sitename']; $from = $config['options']['username']; $message = '<h2>Вы успешно зарегистрировались на сайте <a href="' . Kohana::$base_url . '">' . $options['sitename'] . '</a>!</h2><hr>'; $message .= '<p>Перед входом пожалуйста подтвердите свою учётную запись, для этого перейдите по <a href="' . Kohana::$base_url . 'user/activate?token=' . $token . '&user='******'">этой ссылке</a>.</p><hr>'; $message .= '<h3>Ваши реквизиты для входа:<h3>'; $message .= '<p><small>Логин: <input type="text" value="' . $name . '"></small></p>'; $message .= '<p><small>Пароль: <input type="text" value="' . $pass . '"></small></p>'; $message .= '<hr>Спасибо за то, что пользуетесь услугами нашего портала. По всем вопросам обращайтесь в техподдержку: ' . $config['options']['username']; Email::send($to, $from, $subject, $message, $html = true); return true; } catch (ORM_Validation_Exception $e) { $this->errors = $e->errors('validation'); return false; } }
public function mail_send($to, $from, $subject, $message) { $email_config = Kohana::$config->load("email"); $res = Email::connect($email_config); if (!Email::send($to, $from, $subject, $message, $html = true)) { $model_base = new Model_Base(); $options = $model_base->getOptions(); $to = $options['admin_email']; $subject = 'Ошибки на сайте ' . $options['sitename']; $from = $email_config['options']['username']; foreach ($this->errors as $error) { $message = '<h2>Ошибка</h2>'; $message .= $error; $message .= ' <em>Отправлено: ' . date("G:i:s M j Y") . '</em>'; } Email::send($to, $from, $subject, $message, $html = true); } }
public function action_index() { $email = Security::xss_clean(Arr::get($this->post, 'email', '')); $user = ORM::factory('User')->where('email', '=', $email)->find(); if ($user->loaded() && $user->network_reg == 0 && empty($user->link_activate)) { $date = date("Y-m-d H:i:s"); $code = md5($date . $user->password); Email::connect(); Email::View('reminderapi'); Email::set(array('username' => $user->username, 'id' => $code, 'url' => URL::media($this->language . '/auth/recovery/', true))); Email::send($user->email, array('*****@*****.**', 'e-history.kz'), "E-history.kz, ссылка для смены пароля.", '', true); $save_code = ORM::factory('User', $user->id); $save_code->link_recovery = $code; $save_code->save(); $this->data = true; } else { $this->data['error'] = 'Email is not registered'; } $this->response->body(json_encode($this->data)); }
public function action_step3() { $this->checkInstalled(); $data = array(); $data['values'] = array(); $values = Arr::extract($_POST, array('hostname', 'username', 'password', 'port', 'timeout', 'localDomain', 'systemEmail', 'myemail')); if ($this->isPressed('btnSubmit')) { $smtpconf = Session::instance()->get('smtpconf'); if (!empty($smtpconf)) { Request::initial()->redirect('install/done.html'); } $data['needCheck'] = TRUE; } if ($this->isPressed('btnCheck')) { $smtpconf = array('driver' => 'smtp', 'options' => array('hostname' => $values['hostname'], 'username' => $values['username'], 'password' => $values['password'], 'port' => $values['port'], 'timeout' => $values['timeout'], 'localDomain' => $values['localDomain']), 'systemEmail' => $values['systemEmail']); try { $time = date('d.m.Y H:i:s', time()); $email = Arr::get($_POST, 'myemail'); $from = array($values['systemEmail'], 'Администратор'); $subject = 'Проверка настроек SMTP сервера'; $message = "Поздравляем !\n"; $message .= "Вы получили это сообщение, отправленное в {$time}, значит настройки SMTP сервера правильные.\n"; $message .= "Перейдите на страницу установки образовательной системы и нажмите кнопку 'Продолжить'\n"; Email::connect($smtpconf); $sent = Email::send($email, $from, $subject, $message, FALSE); if ($sent == 0) { throw new Exception('Error sending email message.'); } Session::instance()->set('smtpconf', $values); $data['time'] = $time; } catch (Exception $e) { $data['SMTPerror'] = TRUE; } } $data['values'] = $values; $this->setBody('install/step3', $data); }
/** * Creates a new instance of a swift mailer factory. * See http://swiftmailer.org/docs/ * * @author Merrick Christensen */ public function __construct() { $this->mailer = Email::connect(); }
public function action_agree() { $id = (int) $this->request->param('id', 0); if (!Auth::instance()->logged_in()) { Message::success(i18n::get('You can not participate in this debate')); $this->redirect('debate', 301); } $debate = ORM::factory('Debate', $id); $nowdate = date('Y-m-d H:i:s'); $date = date('Y-m-d H:i:s', strtotime("+36 hours", strtotime($debate->date))); if ($debate->opponent_email == Auth::instance()->get_user()->email and $debate->is_closed == 0 and $debate->is_public == 0 or $date < $nowdate) { $date = date('Y-m-d H:i:s'); $debate->start_time = $date; $debate->end_time = date('Y-m-d H:i:s', strtotime("+" . $debate->lifetime . " hours", strtotime($date))); $debate->opponent_id = Auth::instance()->get_user()->id; $debate->is_public = 1; $debate->replier_id = $debate->author_id; $debate->save(); $user_id = Auth::instance()->get_user()->id; $user = ORM::factory('User', $debate->author_id); $email = $user->profile->email; $opponent = $user->username; $user = ORM::factory('User', $user_id); $author = $user->username; $debate_link = Url::site("debate/view/" . $debate->id, true); Message::success(i18n::get('You have agreed to participate in the debates. Notification to this effect was sent to your opponent')); Email::connect(); Email::View('debate_agree'); Email::set(array('opponent' => $opponent, 'author' => $author, 'link' => 'e-history.kz', 'theme' => "<a href='" . $debate_link . "'>'" . $debate->title . "'</a>")); Email::send($email, array('*****@*****.**', 'e-history.kz'), __("Ваш оппонент согласился участвовать в дебатах на портале :link", array(':link' => 'History.kz')), '', true); $this->redirect('debate/view/' . $id, 301); } else { if ($date < $nowdate) { Message::success(i18n::get('Expired 36 hours during which you could agree to take part in the debate')); } else { Message::success(i18n::get('You can not give consent to participate in this debate')); } $this->redirect('debate', 301); } }
public function loadMail($mail) { $sql = 'SELECT EMAIL.ID, ADDRESS, PASSWORD, SERVER, PORT FROM EMAIL, EMAIL_CONNECTION WHERE EMAIL.ID = IDMAIL AND IDUSER = ? AND ADDRESS = ?'; $this->pdo->prepare($sql); $this->pdo->execute(array($_SESSION['ID'], $mail)); $array = array(); while ($result = $this->pdo->fetch(\PDO::FETCH_ASSOC)) { $mail = new Email($result['ID'], $result['ADDRESS']); $mail->connect($result['SERVER'], $result['PORT'], $result['PASSWORD']); $mail->initializeMails(); foreach ($mail->getMails() as $value) { array_push($array, $value->display()); } } return json_encode($array); }
public function action_materials() { if (!Auth::instance()->logged_in()) { $this->redirect('/', 301); } $user_id = $this->user->id; $materials = ORM::factory('Material')->where('user_id', '=', $user_id); $paginate = Paginate::factory($materials)->paginate(NULL, NULL, 3)->render(); $materials = $materials->find_all(); $this->set('materials', $materials); $this->set('paginate', $paginate); $uploader = View::factory('storage/materials')->set('user_id', $user_id)->render(); $this->set('uploader', $uploader); if ($this->request->method() == Request::POST) { $journal = (int) Arr::get($_POST, 'material_type', 0); if ($journal !== 1) { $journal = 0; } try { $material = ORM::factory('Material'); $material->theme = substr(Arr::get($_POST, 'theme', ''), 0, 250); $material->message = substr(Arr::get($_POST, 'message', ''), 0, 500); $material->user_id = $user_id; $material->date = date('Y-m-d H:i:s'); $material->lang_notice = strtolower(Kohana_I18n::lang()); if ($journal) { $material->is_journal = 1; $material->is_moderator = 0; } $material->save(); $files = Arr::get($_POST, 'files', ''); if ($files) { foreach ($files as $key => $file) { if ($key > 7) { break; } if ($file) { $storage = ORM::factory('Storage', (int) $file); try { $upload = ORM::factory('Material_File'); $upload->user_id = $user_id; $upload->material_id = $material->id; $upload->date = date('Y-m-d H:i:s'); $upload->storage_id = (int) $file; $upload->filesize = filesize($storage->file_path); $upload->save(); } catch (ORM_Validation_Exception $e) { } } } } Message::success(i18n::get('The material sent to the moderator. Thank you!')); $user = ORM::factory('User', $user_id); $user_email = $user->email; Email::connect(); Email::View('review_now_' . i18N::lang()); Email::set(array('message' => I18n::get('Оставленный вами материал находится на рассмотрении редакционной коллегии портала'))); Email::send($user_email, array('*****@*****.**', 'e-history.kz'), I18n::get('Рассмотрение материала на портале "История Казахстана" e-history.kz'), '', true); if ($journal != 1) { $material_type = 'Интересные материалы'; $url = URL::media('/manage/materials', TRUE); } else { $material_type = 'Журнал e-history'; $url = URL::media('/manage/materials/ehistory', TRUE); } $user_profile = ORM::factory('User_Profile', $user_id); if ($user_profile->first_name != '') { $user_name = $user_profile->first_name . ' ' . $user_profile->last_name; } else { $user_name = $user->username; } $email = '*****@*****.**'; Email::connect(); Email::View('new_material'); Email::set(array('url' => $url, 'material_type' => $material_type, 'username' => $user_name)); Email::send($email, array('*****@*****.**', 'e-history.kz'), "Новый материал на e-history.kz", '', true); $this->redirect('profile/materials', 301); } catch (ORM_Validation_Exception $e) { $errors = $e->errors($e->alias()); $files = Arr::get($_POST, 'files', ''); $this->set('errors', $errors)->set('material', $_POST)->set('files', $files); } } $this->add_cumb('User profile', 'profile'); $this->add_cumb('Downloaded Content', '/'); }
public function action_purchasesend() { $purchase_id = $this->request->post('purchase_id'); $send_email = $this->request->post('send-email') ? TRUE : FALSE; $email = $this->request->post('email'); $send_mail = $this->request->post('send-mail') ? TRUE : FALSE; $send_done = $this->request->post('send-done') ? TRUE : FALSE; if (!$purchase_id) { return $this->_return_error("ERROR: No purchase ID provided."); } if (!$send_email and !$send_mail and !$send_done) { return $this->_return_error("ERROR: Please select at least one option."); } $vendor_purchase_lookup = new Beans_Vendor_Purchase_Lookup($this->_beans_data_auth((object) array('id' => $purchase_id))); $vendor_purchase_lookup_result = $vendor_purchase_lookup->execute(); if (!$vendor_purchase_lookup_result->success) { return $this->_return_error("An error occurred retrieving that purchase:<br>" . $this->_beans_result_get_error($vendor_purchase_lookup_result)); } if ($send_email) { if (!$email or !filter_var($email, FILTER_VALIDATE_EMAIL)) { return $this->_return_error("Please provide a valid email address."); } $company_settings = new Beans_Setup_Company_List($this->_beans_data_auth()); $company_settings_result = $company_settings->execute(); if (!$company_settings_result->success) { return $this->_return_error($this->_beans_result_get_error($company_settings_result)); } // Shorten for sanity's sake... $settings = $company_settings_result->data->settings; if (!isset($settings->company_email) or !strlen($settings->company_email)) { return $this->_return_error("Email cannot be sent until you set an email address for your company within 'Setup'."); } $message = Swift_Message::newInstance(); $message->setSubject($settings->company_name . ' - Purchase ' . $vendor_purchase_lookup_result->data->purchase->purchase_number)->setFrom(array($settings->company_email))->setTo(array($email)); $vendors_print_purchase = new View_Vendors_Print_Purchase(); $vendors_print_purchase->setup_company_list_result = $company_settings_result; $vendors_print_purchase->purchase = $vendor_purchase_lookup_result->data->purchase; $vendors_print_purchase->swift_email_message = $message; $message = $vendors_print_purchase->render(); try { if (!Email::connect()) { return $this->_return_error("Could not send email. Does your config have correct email settings?"); } if (!Email::sendMessage($message)) { return $this->_return_error("Could not send email. Does your config have correct email settings?"); } } catch (Exception $e) { return $this->_return_error("An error occurred when sending the email: " . $e->getMessage() . "<br><br>Have you setup email properly in config.php?"); } } $vendor_purchase_update_sent_data = new stdClass(); $vendor_purchase_update_sent_data->id = $purchase_id; if ($send_done or $send_email and $send_mail or $send_email and $vendor_purchase_lookup_result->data->purchase->sent == "print" or $send_mail and $vendor_purchase_lookup_result->data->purchase->sent == "email") { $vendor_purchase_update_sent_data->sent = 'both'; } else { if ($send_email) { $vendor_purchase_update_sent_data->sent = 'email'; } else { if ($send_mail) { $vendor_purchase_update_sent_data->sent = 'print'; } } } $vendor_purchase_update_sent = new Beans_Vendor_Purchase_Update_Sent($this->_beans_data_auth($vendor_purchase_update_sent_data)); $vendor_purchase_update_sent_result = $vendor_purchase_update_sent->execute(); if (!$vendor_purchase_update_sent_result->success) { return $this->_return_error("An error occurred when updating that purchase:<br>" . $this->_beans_result_get_error($vendor_purchase_update_sent_result)); } $html = new View_Partials_Vendors_Purchases_Purchase(); $html->purchase = $vendor_purchase_update_sent_result->data->purchase; $this->_return_object->data->purchase = $vendor_purchase_update_sent_result->data->purchase; $this->_return_object->data->purchase->html = $html->render(); }
public function emailSend($to, $subject, $message) { $config_email = Kohana::$config->load('email'); Email::connect($config_email); $from = $config_email->get('admin_email'); $send = Email::send($to, $from, $subject, $message, $html = true); return $send; }
public function send($data) { $material = new Model_Material('groups'); $fields = $material->getFields2($data['template'], TRUE); //отправляем письмо $config = Kohana::$config->load('email'); Email::connect($config); $subject = Arr::get($fields, 'title'); $from = $config['options']['username']; $message = Arr::get($fields, 'text'); $message = str_replace('@#object#@', Arr::get($data, 'object_name'), $message); $message = str_replace('@#url#@', Arr::get($data, 'object_url'), $message); //генерируем уникальный разделитель $bound = "--" . md5(uniqid(time())); foreach ($data['check_name'] as $subscriberId) { $subscriber = $this->getSubscriber($subscriberId); if ($subscriber['active'] == 1) { $message = str_replace('@#subscriber#@', $subscriber['name'], $message); $subject = str_replace('@#subscriber#@', $subscriber['name'], $subject); $message = str_replace('@#site#@', Kohana::$base_url, $message); $mymessage = str_replace('@#email#@', $subscriber['email'], $message); // $mail_header = "MIME-Version: 1.0;\r\n"; // $mail_header.= "Content-Type: multipart/mixed; boundary=\"$bound\"\r\n"; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=UTF-8\r\n"; $headers .= "From: Morrismedia <" . $from . ">\r\n"; //прикрепляем файл //путь к файлу $file_path = DOCROOT . '/img/user/novost-1_859f1ca6ad9b29c3475.png'; //если файл найден, прикрепляем его к сообщению if (file_exists($file_path)) { $file_name = basename($file_path); $fa = fopen($file_path, "rb"); if ($fa) { $multipart_message = "\r\n--{$bound}\r\n"; $multipart_message .= "Content-type: text/html; charset=UTF-8\r\n"; $multipart_message .= "Content-Transfer-Encoding: base64\r\n"; $multipart_message .= "\r\n"; $multipart_message .= chunk_split(base64_encode($message)); $multipart_message .= "\r\n\r\n--{$bound}\r\n"; $multipart_message .= "Content-Type: application/octet-stream; name=\"{$file_name}\"\r\n"; $multipart_message .= "Content-Transfer-Encoding: base64\r\n"; $multipart_message .= "Content-Disposition: attachment; filename=\"{$file_name}\"\r\n"; $multipart_message .= "\r\n"; $multipart_message .= chunk_split(base64_encode(fread($fa, filesize($file_path)))); fclose($fa); //передаем текст сообщения и прикрепленный файл в переменную $message = $multipart_message; } else { $message = $message; } } else { //если файл не существует передаем текстовое сообщение $message = $message; } // var_dump($mail_header); $result = mail($subscriber['email'], $subject, $mymessage, $headers); if ($result) { $this->messages[] = 'Успешная отправка на ' . $subscriber['email']; $this->updateSend($subscriber['email']); } else { $this->errors[] = 'Ошибка отправки на ' . $subscriber['email']; } // try // { // if(mail($subscriber['email'], $subject, $message, $mail_header, '*****@*****.**')) //// if(Email::send($subscriber['email'], $from, $subject, $message, $html = TRUE)) // { // $this->messages[] = 'Успешная отправка на '.$subscriber['email']; // $this->updateSend($subscriber['email']); // } // else // $this->errors[] = 'Ошибка отправки на '.$subscriber['email']; // } // catch (Exception $e) // { // $this->errors[] = 'Ошибка отправки на '.$subscriber['email']; // } } } return array('messages' => $this->messages, 'errors' => $this->errors); }
protected function _execute(array $params) { $report_list = array(); $start = microtime(true); //получаем список юзеров имеющих подписки $user_list = ORM::factory('Subscription')->group_by('user_id')->find_all(); foreach ($user_list as $oneuser) { set_time_limit(30); $user_id = $oneuser->user_id; $lang = ORM::factory('Subscription_Setting')->where('user_id', '=', $user_id)->find()->lang; $lang_arr = array('ru', 'en', 'kz', 'RU', 'EN', 'KZ'); if (!in_array($lang, $lang_arr)) { $lang = 'ru'; } $period = ORM::factory('Subscription_Setting')->where('user_id', '=', $user_id)->find()->period; $user = ORM::factory('User', $user_id); $user_profile = ORM::factory('User_Profile', $user_id); $update_time = false; $period_arr = array('1', '2', '3'); if (!in_array($period, $period_arr)) { $update_time = true; } if ($period == '1') { $update_time = true; } if ($period == '2') { if (date('N') == 1) { $update_time = true; } } if ($period == '3') { if (date('j') == 1) { $update_time = true; } } //Как обращаться к пользователю if ($user_profile->first_name != '') { $user_name = $user_profile->first_name . ' ' . $user_profile->last_name; } else { $user_name = $user->username; } //На какое мыло слать $user_email = $user->email; //выставляем язык для рассылки I18n::lang($lang); //получаем список подписок текущего пользователя $sub_list = ORM::factory('Subscription')->where('user_id', '=', $user_id)->find_all(); $links = array(); //ищем самую старую дату из всех подписок $lastdate = '3000-01-01 00:00:00'; foreach ($sub_list as $sub) { if ($lastdate > $sub->date) { $lastdate = $sub->date; } } //если пришло время обновляться if ($update_time == true) { //перебираем список подписок текущего юзера foreach ($sub_list as $sub) { //Получаем запись из Pages, на которую подписан юзер $page = ORM::factory('Page', $sub->category_id); //Смотрим ключ записи, если ключ пустой то ищем имя ключа родителя $key = $page->key; if ($page->key == '' and $page->lvl == '3') { $page_lvl = ORM::factory('Page', $page->parent_id)->as_array(null, 'key'); $key = $page_lvl['key']; } //перебираем все варианты ключей //История казахстана и подразделы if ($key == 'history') { set_time_limit(30); if ($page->lvl == 2) { $allsubhistory = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all()->as_array(null, 'id'); $allsubhistory = ORM::factory('Page')->where('parent_id', 'in', $allsubhistory)->find_all()->as_array(null, 'id'); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { if (count(Subtool::findincontents($inlog, $allsubhistory)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } if ($page->lvl == 3) { $allsubhistory = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all()->as_array(null, 'id'); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { if (count(Subtool::findincontents($inlog, $allsubhistory)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } } //Первый президент и подразделы if ($key == 'president') { set_time_limit(30); if ($page->lvl == 3) { if ($page->key == '') { $find_child = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all()->as_array(null, 'id'); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($find_child) > 0) { if (count($inlog) > 0) { if (count(Subtool::findincontents($inlog, $find_child)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } else { if (count($inlog) > 0) { $find_child[] = $sub->category_id; if (count(Subtool::findincontents($inlog, $find_child)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } } } if ($page->lvl == 2) { $president = false; $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all(); foreach ($find_child_lvl3 as $child_lvl3) { if ($president == false) { if ($child_lvl3->key == '') { $find_child = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all()->as_array(null, 'id'); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($find_child) > 0) { if (count($inlog) > 0) { if (count(Subtool::findincontents($inlog, $find_child)) > 0) { $president = true; } } } else { if (count($inlog) > 0) { $find_child[] = $sub->category_id; if (count(Subtool::findincontents($inlog, $find_child)) > 0) { $president = true; } } } } $e = explode('_', $page->key); if ($e[0] == 'books' and isset($e[2])) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Book'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); $cats[] = $e[2]; if (count($inlog) > 0) { if (count(Subtool::findinbooks($inlog, $cats)) > 0) { $president = true; } } } } } if ($president == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } //Экспертный взгляд и подразделы if ($key == 'expert' and $page->key == 'expert' and $page->lvl == 3) { set_time_limit(30); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Expert_Opinion'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'expert' and $page->key == '' and $page->lvl == 3) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsub[] = $sub->category_id; if (count(Subtool::findincontents($inlog, $allsub)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } if ($key == 'expert' and $page->lvl == 2) { set_time_limit(30); $expert = false; $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all(); foreach ($find_child_lvl3 as $child_lvl3) { if ($expert == false) { if ($child_lvl3->key == 'expert') { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Expert_Opinion'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $expert = true; } } if ($child_lvl3->key == '') { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsub[] = $child_lvl3->id; if (count(Subtool::findincontents($inlog, $allsub)) > 0) { $expert = true; } } } } } if ($expert == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } //Электронный архив и подразделы if ($key == 'archive' and $page->lvl == 3) { set_time_limit(30); $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all(); if (count($find_child_lvl3) > 0) { $archive_lvl3 = false; foreach ($find_child_lvl3 as $child_lvl3) { if ($archive_lvl3 == false) { $allsub = array(); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsub[] = $child_lvl3->id; if (count(Subtool::findincontents($inlog, $allsub)) > 0) { $archive_lvl3 = true; } } } } if ($archive_lvl3 == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsub[] = $sub->category_id; if (count(Subtool::findincontents($inlog, $allsub)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } } if ($key == 'archive' and $page->lvl == 2) { $find_all_child = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all(); $archive_lvl3 = false; foreach ($find_all_child as $finded_child) { if ($archive_lvl3 == false) { set_time_limit(30); $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $finded_child->id)->find_all(); $archive_lvl3 = false; if (count($find_child_lvl3) > 0) { foreach ($find_child_lvl3 as $child_lvl3) { $allsub = array(); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsub[] = $child_lvl3->id; if (count(Subtool::findincontents($inlog, $allsub)) > 0) { $archive_lvl3 = true; } } } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsub[] = $finded_child->id; if (count(Subtool::findincontents($inlog, $allsub)) > 0) { $archive_lvl3 = true; } } } } } if ($archive_lvl3 == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } //Персоналии if ($key == 'biography' and $page->lvl == 3) { $all_biography_lvl4 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); foreach ($all_biography_lvl4 as $biography_lvl4) { set_time_limit(30); $newbiography = false; $e = explode('_', $biography_lvl4->key); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Biography'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $biography = ORM::factory('Biography')->where('id', 'in', $inlog)->and_where('category_id', '=', $e[1])->find_all()->as_array(null, 'id'); if (count($biography) > 0) { $newbiography = true; } } } if ($newbiography == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'personal' and $page->lvl == 2) { $all_biography_lvl3 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all()->as_array(null, 'id'); $all_biography_lvl4 = ORM::factory('Page')->where('parent_id', 'in', $all_biography_lvl3)->find_all(); $newbiography = false; foreach ($all_biography_lvl4 as $biography_lvl4) { set_time_limit(30); if ($newbiography == false) { $e = explode('_', $biography_lvl4->key); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Biography'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $biography = ORM::factory('Biography')->where('id', 'in', $inlog)->and_where('category_id', '=', $e[1])->find_all()->as_array(null, 'id'); if (count($biography) > 0) { $newbiography = true; } } } } if ($newbiography == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } //Книги любые $e = explode('_', $page->key); if ($e[0] == 'books' and isset($e[2])) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Book'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); $cats[] = $e[2]; if (count($inlog) > 0) { if (count(Subtool::findinbooks($inlog, $cats)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } // Историческое образование if ($key == 'education' and $page->lvl == 3) { $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all(); if (count($find_child_lvl3) > 0) { $education_lvl3 = false; foreach ($find_child_lvl3 as $child_lvl3) { if ($education_lvl3 == false) { $allsub = array(); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Book'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $e = explode('_', $child_lvl3->key); $allsub[] = $e[1]; if (count(Subtool::findinbooks($inlog, $allsub)) > 0) { $education_lvl3 = true; } } } } if ($education_lvl3 == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } if ($key == 'education' and $page->lvl == 2) { $find_child_lvl2 = ORM::factory('Page')->where('parent_id', '=', $sub->category_id)->find_all()->as_array(null, 'id'); $neweducation = false; foreach ($find_child_lvl2 as $child_lvl2) { set_time_limit(30); if ($neweducation == false) { $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $child_lvl2)->find_all(); if (count($find_child_lvl3) > 0) { foreach ($find_child_lvl3 as $child_lvl3) { $allsub = array(); $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Book'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $e = explode('_', $child_lvl3->key); $allsub[] = $e[1]; if (count(Subtool::findinbooks($inlog, $allsub)) > 0) { $neweducation = true; } } } } else { $booksfore = ORM::factory('Page', $child_lvl2); //опасный момент $e = explode('_', $booksfore->key); if ($e[0] == 'books' and isset($e[2])) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Book'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); $cats[] = $e[2]; if (count($inlog) > 0) { if (count(Subtool::findinbooks($inlog, $cats)) > 0) { $neweducation = true; } } } } } } if ($neweducation == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } //Организации образования и науки if ($key == 'institute' and $page->lvl == 3) { set_time_limit(30); $find_child_lvl4 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); if (count($find_child_lvl4->as_array(null, 'id')) > 0) { foreach ($find_child_lvl4 as $child_lvl4) { $find_child_lvl5 = ORM::factory('Page')->where('parent_id', '=', $child_lvl4->id)->find_all()->as_array(null, 'id'); if (count($find_child_lvl5) > 0) { $child_lvl5[] = $find_child_lvl5[0]; } } if (count($child_lvl5) > 0) { $find_organization = ORM::factory('Organization')->where('page_id', 'in', $child_lvl5)->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($find_organization) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } else { $child_lvl4_ids = $find_child_lvl4->as_array(null, 'id'); $find_organization = ORM::factory('Organization')->where('page_id', 'in', $child_lvl4_ids)->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($find_organization) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs[] = $page->id; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } } if ($key == 'institute' and $page->lvl == 2) { $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); $newinstitute = false; foreach ($find_child_lvl3 as $child_lvl3) { set_time_limit(30); if ($newinstitute == false) { $find_child_lvl4 = ORM::factory('Page')->where('parent_id', '=', $child_lvl3->id)->find_all(); if (count($find_child_lvl4->as_array(null, 'id')) > 0) { foreach ($find_child_lvl4 as $child_lvl4) { set_time_limit(30); $find_child_lvl5 = ORM::factory('Page')->where('parent_id', '=', $child_lvl4->id)->find_all()->as_array(null, 'id'); if (count($find_child_lvl5) > 0) { $child_lvl5[] = $find_child_lvl5[0]; } } if (count($child_lvl5) > 0) { $find_organization = ORM::factory('Organization')->where('page_id', 'in', $child_lvl5)->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($find_organization) > 0) { $newinstitute = true; } } else { $child_lvl4_ids = $find_child_lvl4->as_array(null, 'id'); $find_organization = ORM::factory('Organization')->where('page_id', 'in', $child_lvl4_ids)->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($find_organization) > 0) { $newinstitute = true; } } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs[] = $page->id; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $newinstitute = true; } } } } } if ($newinstitute == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'people' and $page->lvl == 3) { $find_child_lvl4 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all()->as_array(null, 'id'); if (count($find_child_lvl4) > 0) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs = $find_child_lvl4; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs[] = $page->id; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } } if ($key == 'people' and $page->lvl == 2) { $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); $newpeople = false; foreach ($find_child_lvl3 as $child_lvl3) { set_time_limit(30); if ($newpeople == false) { $find_child_lvl4 = ORM::factory('Page')->where('parent_id', '=', $child_lvl3->id)->find_all()->as_array(null, 'id'); if (count($find_child_lvl4) > 0) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs = $find_child_lvl4; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $newpeople = true; } } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs[] = $child_lvl3->id; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $newpeople = true; } } } } } if ($newpeople == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } //публикации if ($key == 'publications' and $page->lvl == 2) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Publication'))->and_where('language', '=', $lang)->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($inlog) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } //Электронный журнал "e-history.kz" if ($key == 'metodology' or $key == 'crossstudy' or $key == 'metodicheskie') { $find_childs_lvl4 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); $finded_lvl3 = false; foreach ($find_childs_lvl4 as $childs_lvl4) { set_time_limit(30); if ($finded_lvl3 == false) { set_time_limit(30); $find_childs_lvl5 = ORM::factory('Page')->where('parent_id', '=', $childs_lvl4->id)->find_all()->as_array(null, 'id'); if (count($find_childs_lvl5) > 0) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs = $find_childs_lvl5; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $finded_lvl3 = true; } } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs[] = $childs_lvl4->id; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $finded_lvl3 = true; } } } } } if ($finded_lvl3 == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'journal_ehistory') { $find_childs_lvl3 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); $newehistory = false; foreach ($find_childs_lvl3 as $childs_lvl3) { set_time_limit(30); if ($newehistory == false) { $find_childs_lvl4 = ORM::factory('Page')->where('parent_id', '=', $childs_lvl3->id)->find_all(); $finded_lvl3 = false; foreach ($find_childs_lvl4 as $childs_lvl4) { if ($finded_lvl3 == false) { set_time_limit(30); $find_childs_lvl5 = ORM::factory('Page')->where('parent_id', '=', $childs_lvl4->id)->find_all()->as_array(null, 'id'); if (count($find_childs_lvl5) > 0) { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs = $find_childs_lvl5; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $finded_lvl3 = true; $newehistory = true; } } } else { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Pages_Content'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $allsubs[] = $childs_lvl4->id; if (count(Subtool::findincontents($inlog, $allsubs)) > 0) { $finded_lvl3 = true; $newehistory = true; } } } } } } } if ($newehistory == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } //блок интерактив if ($key == 'debate') { $debates = ORM::factory('Debate')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($debates) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'briefings') { $briefings = ORM::factory('Briefing')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($briefings) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'scorm') { $educations = ORM::factory('Education')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($educations) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'ent') { $ent = ORM::factory('Ent')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($ent) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'interactive') { $interactives = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); $newinteractive = false; foreach ($interactives as $child) { set_time_limit(30); if ($newinteractive == false) { $child_key = $child->key; if ($child_key == 'debate') { $debates = ORM::factory('Debate')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($debates) > 0) { $newinteractive = true; } } if ($child_key == 'briefings') { $briefings = ORM::factory('Briefing')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($briefings) > 0) { $newinteractive = true; } } if ($child_key == 'scorm') { $educations = ORM::factory('Education')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($educations) > 0) { $newinteractive = true; } } if ($child_key == 'ent') { $ent = ORM::factory('Ent')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($ent) > 0) { $newinteractive = true; } } } } if ($newinteractive == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'photosets') { $photosets = ORM::factory('Photoset')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($photosets) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'video') { $videos = ORM::factory('Video')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($videos) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'audio') { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Audio'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $audios = ORM::factory('Audio')->where('id', 'in', $inlog)->find_all()->as_array(null, 'id'); if (count($audios) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } if ($key == 'infographs') { $infographs = ORM::factory('Infograph')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($infographs) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } if ($key == 'library') { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Book'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $books = ORM::factory('Book')->where('id', 'in', $inlog)->find_all()->as_array(null, 'id'); if (count($books) > 0) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } } if ($key == 'multimedia') { $find_child_lvl3 = ORM::factory('Page')->where('parent_id', '=', $page->id)->find_all(); $newmultimedia = false; foreach ($find_child_lvl3 as $child_lvl3) { set_time_limit(30); if ($newmultimedia == false) { $child_key = $child_lvl3->key; if ($child_key == 'photosets') { $photosets = ORM::factory('Photoset')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($photosets) > 0) { $newmultimedia = true; } } if ($child_key == 'video') { $videos = ORM::factory('Video')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($videos) > 0) { $newmultimedia = true; } } if ($child_key == 'audio') { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Audio'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $audios = ORM::factory('Audio')->where('id', 'in', $inlog)->find_all()->as_array(null, 'id'); if (count($audios) > 0) { $newmultimedia = true; } } } if ($child_key == 'infographs') { $infographs = ORM::factory('Infograph')->where('date', '>', $lastdate)->find_all()->as_array(null, 'id'); if (count($infographs) > 0) { $newmultimedia = true; } } if ($child_key == 'library') { $inlog = ORM::factory('Log')->where(DB::expr('lower(model)'), 'LIKE', strtolower('Model_Book'))->and_where('date', '>', $lastdate)->find_all()->as_array(null, 'content_id'); if (count($inlog) > 0) { $books = ORM::factory('Book')->where('id', 'in', $inlog)->find_all()->as_array(null, 'id'); if (count($books) > 0) { $newmultimedia = true; } } } } } if ($newmultimedia == true) { $links[] = array('link' => URL::media($lang . '/contents/list/' . $sub->category_id), 'title' => $page->name); } } $subupdate = ORM::factory('Subscription', $sub->id); $subupdate->date = date("Y-m-d H:i:s"); $subupdate->save(); } $time = microtime(true) - $start; if (count($links) != 0) { $report_list[] = array('time' => $time, 'user_id' => $user_id); Email::connect(); if ($lang == 'ru' or $lang == 'RU') { Email::View('distribution_ru'); } if ($lang == 'kz' or $lang == 'KZ') { Email::View('distribution_kz'); } if ($lang == 'en' or $lang == 'EN') { Email::View('distribution_en'); } Email::set(array('user' => $user_name, 'period1' => $lastdate, 'period2' => date("Y-m-d H:i:s"), 'unsublink' => Subtool::media('/' . $lang . '/profile/subscription'), 'links' => $links)); set_time_limit(60); Email::send($user_email, array('*****@*****.**', 'e-history.kz'), I18n::get('Обновления на портале Истории Казахстана e-history.kz'), '', true); } } } set_time_limit(60); if (count($report_list) != 0) { Email::connect(); Email::View('successsub'); Email::set(array('message' => 'Все рассылки успешно разослались', 'list' => $report_list)); Email::send('*****@*****.**', array('*****@*****.**', 'e-history.kz'), "Рассылки на истории", '', true); } else { Email::connect(); Email::View('default'); Email::set(array('message' => 'Сегодня никому ничего не отправлено')); Email::send('*****@*****.**', array('*****@*****.**', 'e-history.kz'), "Рассылки на истории", '', true); } }
public function action_index() { //смотрим шаблон для виджета $id = $this->request->param('id'); $widget = new Model_Widget(); $template = $widget->getTempalte('callback', $id); if ($template) { $this->template = View::factory('widgets/' . $template); } if (isset($_POST['callback-order'])) { if (Captcha::valid(Arr::get($_POST, 'comm-captcha'))) { $base = new Model_Base(); $options = $base->getOptions(); $vData = $_POST; $validation = Validation::factory($vData); $validation->rule('cb-name', 'not_empty'); $validation->rule('cb-name', 'min_length', array(':value', '2')); $validation->rule('cb-name', 'max_length', array(':value', '250')); $validation->rule('cb-phone', 'not_empty'); $validation->rule('cb-phone', 'phone'); $validation->rule('cb-phone', 'min_length', array(':value', '6')); $validation->rule('cb-phone', 'max_length', array(':value', '15')); if (!$validation->check()) { $this->errors = $validation->errors('callbackErrors'); } else { $name = Arr::get($_POST, 'cb-name', ''); $phone = Arr::get($_POST, 'cb-phone', ''); //отправляем письмо $config = Kohana::$config->load('email'); Email::connect($config); $to = $config['options']['callback_email']; //$to = '*****@*****.**'; $subject = 'Поступила заявка с сайта ' . $options['sitename'] . ' от ' . $name . ''; $from = $config['options']['username']; $message = '<h2>Новая заявка</h2>'; $message .= 'Отправитель: <b>' . $name . ', </b><br>'; $message .= 'Тел: <b>' . $phone . ', </b><br>'; $message .= '<em>Отправлено: ' . date("G:i:s M j Y") . '</em>'; Email::send($to, $from, $subject, $message, $html = TRUE); if (count($this->errors) > 0) { $base = new Model_Base(); $options = $base->getOptions(); $to = $options['admin_email']; $subject = 'Ошибки на сайте ' . $options['sitename']; $from = $config['options']['username']; foreach ($this->errors as $error) { $message = '<h2>Ошибка</h2>'; $message .= $error; $message .= ' <em>Отправлено: ' . date("G:i:s M j Y") . '</em>'; } Email::send($to, $from, $subject, $message, $html = TRUE); } else { $this->messages[] = 'Спасибо! Ваш вопрос успешно отправлен.'; } } } else { $this->errors['captcha'] = "Код введен неверно"; } } $captcha_image = Captcha::instance()->render(); $this->template->captcha = $captcha_image; $this->template->errors = $this->errors; $this->template->messages = $this->messages; }
public function action_saleinvoice() { $sale_id = $this->request->post('sale_id'); $send_none = $this->request->post('send-none') ? TRUE : FALSE; $send_email = $this->request->post('send-email') ? TRUE : FALSE; $email = $this->request->post('email'); $send_mail = $this->request->post('send-mail') ? TRUE : FALSE; $send_done = $this->request->post('send-done') ? TRUE : FALSE; if (!$sale_id) { return $this->_return_error("ERROR: No sale ID provided."); } if (!$send_none and !$send_email and !$send_mail and !$send_done) { return $this->_return_error("ERROR: Please select at least one option."); } // Invoice $customer_sale_invoice = new Beans_Customer_Sale_Invoice($this->_beans_data_auth((object) array('id' => $sale_id))); $customer_sale_invoice_result = $customer_sale_invoice->execute(); if (!$customer_sale_invoice_result->success) { return $this->_return_error("An error occurred when converting that sale to an invoice:<br>" . $this->_beans_result_get_error($customer_sale_invoice_result)); } if ($send_none) { $html = new View_Partials_Customers_Sales_Sale(); $html->sale = $customer_sale_invoice_result->data->sale; $html->invoice_view = $this->request->post('invoice_view'); $this->_return_object->data->sale = $customer_sale_invoice_result->data->sale; $this->_return_object->data->sale->html = $html->render(); return; } if ($send_done) { $customer_sale_update_sent = new Beans_Customer_Sale_Update_Sent($this->_beans_data_auth((object) array('id' => $customer_sale_invoice_result->data->sale->id, 'sent' => 'both'))); $customer_sale_update_sent_result = $customer_sale_update_sent->execute(); $html = new View_Partials_Customers_Sales_Sale(); $html->sale = $customer_sale_update_sent_result->data->sale; $html->invoice_view = $this->request->post('invoice_view'); $this->_return_object->data->sale = $customer_sale_update_sent_result->data->sale; $this->_return_object->data->sale->html = $html->render(); return; } if ($send_email) { if (!$email or !filter_var($email, FILTER_VALIDATE_EMAIL)) { return $this->_return_error("Please provide a valid email address."); } $company_settings = new Beans_Setup_Company_List($this->_beans_data_auth()); $company_settings_result = $company_settings->execute(); if (!$company_settings_result->success) { return $this->_return_error($this->_beans_result_get_error($company_settings_result)); } // Shorten for sanity's sake... $settings = $company_settings_result->data->settings; if (!isset($settings->company_email) or !strlen($settings->company_email)) { return $this->_return_error("Email cannot be sent until you set an email address for your company within 'Setup'."); } $message = Swift_Message::newInstance(); $message->setSubject($settings->company_name . ' - ' . $customer_sale_invoice_result->data->sale->title)->setFrom(array($settings->company_email))->setTo(array($email)); $customers_print_sale = new View_Customers_Print_Sale(); $customers_print_sale->setup_company_list_result = $company_settings_result; $customers_print_sale->sale = $customer_sale_invoice_result->data->sale; $customers_print_sale->swift_email_message = $message; $message = $customers_print_sale->render(); try { if (!Email::connect()) { return $this->_return_error("Could not send email. Does your config have correct email settings?"); } if (!Email::sendMessage($message)) { return $this->_return_error("Could not send email. Does your config have correct email settings?"); } } catch (Exception $e) { return $this->_return_error("An error occurred when sending the email: " . $e->getMessage() . "<br><br>Have you setup email properly in config.php?"); } } // Update sale attributes only. $customer_sale_update_sent_data = new stdClass(); $customer_sale_update_sent_data->id = $sale_id; if ($send_done or $send_email and $send_mail or $send_email and $customer_sale_invoice_result->data->sale->sent == "print" or $send_mail and $customer_sale_invoice_result->data->sale->sent == "email") { $customer_sale_update_sent_data->sent = 'both'; } else { if ($send_email) { $customer_sale_update_sent_data->sent = 'email'; } else { if ($send_mail) { $customer_sale_update_sent_data->sent = 'print'; } } } $customer_sale_update_sent = new Beans_Customer_Sale_Update_Sent($this->_beans_data_auth($customer_sale_update_sent_data)); $customer_sale_update_sent_result = $customer_sale_update_sent->execute(); if (!$customer_sale_update_sent_result->success) { return $this->_return_error("An error occurred when updating that sale:<br>" . $this->_beans_result_get_error($customer_sale_update_sent_result)); } $html = new View_Partials_Customers_Sales_Sale(); $html->sale = $customer_sale_update_sent_result->data->sale; $html->invoice_view = $this->request->post('invoice_view'); $this->_return_object->data->sale = $customer_sale_update_sent_result->data->sale; $this->_return_object->data->sale->html = $html->render(); }
public function save_email() { $obj = new Email(); $obj->receiveMail('*****@*****.**', '1234567a', '*****@*****.**', 'pop3.baicheng.com', 'pop3', '110', false); // 链接邮箱服务器 $obj->connect(); // 获取邮件总数 $tot = $obj->getTotalMails(); if ($tot > 0) { // 循环获取每一封邮件 for ($i = $tot; $i > 0; $i--) { // 获取邮件头 $head = $obj->getHeaders($i); /****** 根据模板生成正式租车订单xls [S] ******/ // 租车订单附件 - 模板路径 $templet_path = CARRENTAL_ORDER_PATH . 'Templet/Templet.xls'; // 租车订单附件 - 正式路径 $order_path = CARRENTAL_ORDER_PATH . date('Y-m-d', time()) . '/'; // 如正式路径不存在则创建 if (!file_exists($order_path)) { if (!DirectoryFile::dirCreate($order_path)) { exit('创建目录失败!'); } } // 如模板文件存在则复制到正式路径下 if (file_exists($templet_path)) { // 生成附件名称 $attachment_name = 'order_' . time() . '.xls'; // 复制租车订单模板至正式目录下 $status = @copy($templet_path, $order_path . $attachment_name); if (!$status) { exit('模板文件移动失败!'); } } else { exit('订单模板文件不存在!'); } // 引入PHPExcel扩展 Yii::createComponent('application.extensions.excel.PHPExcel'); // 实例化Excel读取类 $PHPReader = new PHPExcel_Reader_Excel5(); // 读取Excel工作表 $PHPExcel = $PHPReader->load($order_path . $attachment_name); $currentSheet = $PHPExcel->getSheet(0); // 获取订单邮件内容 $email_content = $obj->getBody($i); // 拆分订单邮件 $order_id = $this->email_explode('<font style="color: #444444; font-family: Arial, Helvetica, sans-serif; font-size: 16px; text-transform: uppercase; font-weight: bold;">', $email_content); // 拆分出订单号 $car_detail = $this->email_explode('<font style="color: #666666; font-family: Arial, Helvetica, sans-serif; font-size: 12px;">', $email_content); // 拆分出车辆信息 $other_detail = $this->email_explode('<font style="color: #666666; font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: 18px;">', $email_content); // 拆分出其它信息 [费用明细 、车行、您的细节、取车、还车、涵盖范围 等...] $email_detail = array_merge($order_id, $car_detail, $other_detail); // 合并成完整的订单信息 /*print_r($email_detail); exit();*/ // 写入单元格内容 $currentSheet->setCellValue('B3', $email_detail[0]); // 预定号[reservation number] $currentSheet->setCellValue('D3', $email_detail[13]); // 确认号码[confirmation number] $currentSheet->setCellValue('B5', $email_detail[15]); // 租车人姓名[Name] $currentSheet->setCellValue('D5', $email_detail[16]); // 航班号码[Flight number] $currentSheet->setCellValue('B19', $email_detail[11]); // 车辆代码[Car Code] $currentSheet->setCellValue('D19', $email_detail[2]); // 车门数[Doors] $currentSheet->setCellValue('D22', $email_detail[3]); // 空调[Air Con] $currentSheet->setCellValue('D20', $email_detail[1]); // 座位数[Car Seats] $currentSheet->setCellValue('B9', trim(explode('在', $email_detail[17])[0])); // 取车日期 $currentSheet->setCellValue('B10', trim(explode('在', $email_detail[17])[1])); // 取车时间 $currentSheet->setCellValue('B11', $email_detail[18]); // 取车门店[Location] $currentSheet->setCellValue('B12', $email_detail[19]); // 取车地址[Address] $currentSheet->setCellValue('B13', $email_detail[21]); // 取车地电话[Tel] $currentSheet->setCellValue('D9', trim(explode('在', $email_detail[23])[0])); // 还车日期 $currentSheet->setCellValue('D10', trim(explode('在', $email_detail[23])[1])); // 还车时间 $currentSheet->setCellValue('D11', $email_detail[24]); // 还车门店[Location] $currentSheet->setCellValue('D12', $email_detail[25]); // 还车地址[Address] $currentSheet->setCellValue('D13', $email_detail[27]); // 还车地电话[Tel] $currentSheet->setCellValue('B23', $email_detail[13]); // 确认号码[confirmation number] // 实例化Excel写入类 $PHPWriter = new PHPExcel_Writer_Excel5($PHPExcel); // 生成订单附件 $PHPWriter->save(iconv('utf-8', 'gbk', $order_path . $attachment_name)); echo '<script language="javascript" type="text/javascript">window.top.window.stopUpload(1);</script>'; /****** 根据模板生成正式租车订单xls [E] ******/ // 填充模型 $carrentalemail = new CarrentalEmail(); $carrentalemail->title = $head; $carrentalemail->content = $email_content; $carrentalemail->status = 1; $carrentalemail->attachment_path = $order_path . $attachment_name; $carrentalemail->create_time = date('Y-m-d H:i:s', time()); // 开启事务 $transaction = Yii::app()->db->beginTransaction(); try { // 保存成功则生成租车订单附件并发送 if ($carrentalemail->save()) { // 发送邮件 $status = Email::sendEmail('*****@*****.**', '租车订单', $carrentalemail->content, 'smtp.baicheng.com', '*****@*****.**', '1234567a', array($order_path . $attachment_name, $attachment_name)); // 发送成功后删除邮件 if ($status) { // $obj->deleteMails($i); } else { throw new Exception('发送邮件失败!'); } } else { throw new Exception('邮件数据保存失败!'); } $transaction->commit(); // 提交事务 } catch (Exception $e) { $transaction->rollBack(); //回滚事务 echo $e->getMessage(); } } } // 关闭链接 $obj->close_mailbox(); }
public static function send($to, $subject, $message, $html = FALSE) { $config = array('driver' => 'smtp', 'options' => array('hostname' => Kohana::$config->load('mailer.hostname'), 'username' => Kohana::$config->load('mailer.username'), 'password' => Kohana::$config->load('mailer.password'), 'port' => Kohana::$config->load('mailer.port'), 'encryption' => Kohana::$config->load('mailer.encryption'))); Email::connect($config); Email::send($to, Kohana::$config->load('mailer.from'), $subject, $message, $html); }
public function action_recovery_password() { if (Request::initial()->is_ajax()) { $email = Arr::get($_POST, 'email', ''); $login = Arr::get($_POST, 'login', ''); $model = ORM::factory('User', array('username' => $login)); if ($model->email == $email) { $config = Kohana::$config->load('email'); Email::connect($config); $subject = 'Востановление пароля'; $from = '*****@*****.**'; $to = $email; $password = $this->generate_password(); $message = 'Ваш новый пароль:' . $password; Email::send($to, $from, $subject, $message, $html = false); $model->values(array('password' => $password)); $model->save(); echo 'OK!'; } else { echo 'Проверьте логин или email'; } } }
/** * A basic implementation of the "Forgot password" functionality */ public function action_forgot() { // Password reset must be enabled in config/useradmin.php if (!Kohana::$config->load('useradmin')->email) { Message::add('error', 'Password reset via email is not enabled. Please contact the site administrator to reset your password.'); $this->redirect('user/register'); } // set the template title (see Controller_App for implementation) $this->template->title = __('Forgot password'); if (isset($_POST['reset_email'])) { $user = ORM::factory('User')->where('email', '=', $_POST['reset_email'])->find(); // admin passwords cannot be reset by email if (is_numeric($user->id) && $user->username != 'admin') { // send an email with the account reset token $user->reset_token = $user->generate_password(32); $user->save(); $message = "You have requested a password reset. You can reset password to your account by visiting the page at:\n\n" . ":reset_token_link\n\n" . "If the above link is not clickable, please visit the following page:\n" . ":reset_link\n\n" . "and copy/paste the following Reset Token: :reset_token\nYour user account name is: :username\n"; $mailer = Email::connect(); // Create complex Swift_Message object stored in $message // MUST PASS ALL PARAMS AS REFS $subject = __('Account password reset'); $to = $_POST['reset_email']; $from = Kohana::$config->load('useradmin')->email_address; $body = __($message, array(':reset_token_link' => URL::site('user/reset?reset_token=' . $user->reset_token . '&reset_email=' . $_POST['reset_email'], TRUE), ':reset_link' => URL::site('user/reset', TRUE), ':reset_token' => $user->reset_token, ':username' => $user->username)); // FIXME: Test if Swift_Message has been found. $message_swift = Swift_Message::newInstance($subject, $body)->setFrom($from)->setTo($to); if ($mailer->send($message_swift)) { Message::add('success', __('Password reset email sent.')); $this->redirect('user/login'); } else { Message::add('failure', __('Could not send email.')); } } else { if ($user->username == 'admin') { Message::add('error', __('Admin account password cannot be reset via email.')); } else { Message::add('error', __('User account could not be found.')); } } } $this->template->content = View::factory('user/reset/forgot'); }
public function action_index() { $data = array(); $id = $this->request->param('id'); $emails = new Model_Email(); $material = new Model_Material('group'); if (isset($_POST['send'])) { $fields = $material->getFields2($_POST['template'], TRUE); //отправляем письмо $config = Kohana::$config->load('email'); Email::connect($config); $subject = Arr::get($fields, 'title'); $from = $config['options']['username']; $message = Arr::get($fields, 'text'); //генерируем уникальный разделитель $bound = "--" . md5(uniqid(time())); foreach ($_POST['check_name'] as $subscriberId) { $subscriber = $emails->getSubscriber($subscriberId); $message = str_replace('@#subscriber#@', $subscriber['name'], $message); $subject = str_replace('@#subscriber#@', $subscriber['name'], $subject); $message = str_replace('@#site#@', Kohana::$base_url, $message); $mail_header = "MIME-Version: 1.0;\r\n"; $mail_header .= "Content-Type: multipart/mixed; boundary=\"{$bound}\"\r\n"; $mail_header .= "Отправитель: <" . $from . ">\r\n"; $mail_header .= "Для ответа <" . $from . ">\r\n"; $mail_header .= "Subject: {$subject} \n"; //прикрепляем файл //путь к файлу $file_path = DOCROOT . '/img/user/novost-1_859f1ca6ad9b29c3475.png'; //если файл найден, прикрепляем его к сообщению if (file_exists($file_path)) { $file_name = basename($file_path); $fa = fopen($file_path, "rb"); if ($fa) { $multipart_message = "\r\n--{$bound}\r\n"; $multipart_message .= "Content-Type: text/html; charset=UTF-8\r\n"; $multipart_message .= "Content-Transfer-Encoding: base64\r\n"; $multipart_message .= "\r\n"; $multipart_message .= chunk_split(base64_encode($message)); $multipart_message .= "\r\n\r\n--{$bound}\r\n"; $multipart_message .= "Content-Type: application/octet-stream; name=\"{$file_name}\"\r\n"; $multipart_message .= "Content-Transfer-Encoding: base64\r\n"; $multipart_message .= "Content-Disposition: attachment; filename=\"{$file_name}\"\r\n"; $multipart_message .= "\r\n"; $multipart_message .= chunk_split(base64_encode(fread($fa, filesize($file_path)))); fclose($fa); //передаем текст сообщения и прикрепленный файл в переменную $message = $multipart_message; } else { $message = $message; } } else { //если файл не существует передаем текстовое сообщение $message = $message; } // var_dump($message); try { if (mail($subscriber['email'], $subject, $message, $mail_header)) { // if(Email::send($subscriber['email'], $from, $subject, $message, $html = TRUE)) $this->messages[] = 'Успешная отправка на ' . $subscriber['email']; } else { $this->errors[] = 'Ошибка отправки на ' . $subscriber['email']; } } catch (Exception $e) { $this->errors[] = 'Ошибка отправки на ' . $subscriber['email']; } } } if ($id == NULL) { $this->templates = $material->getMaterials(59, 100, 0, '', array(), array('text')); $data['emails'] = $emails->getEmails(); } $this->template->content = View::factory('admin/admEmails', array('data' => $data, 'user' => $this->user, 'templates' => $this->templates, 'errors' => $this->errors, 'messages' => $this->messages)); }