function mso_edit_comuser($data) { global $MSO; $CI =& get_instance(); $data = mso_xss_clean_data($data, array('user_login', 'password', 'comusers_email', 'comusers_new_password', 'comusers_nik', 'comusers_icq', 'comusers_url', 'comusers_msn', 'comusers_jaber', 'comusers_skype', 'comusers_avatar_url', 'comusers_description', 'comusers_date_birth_y', 'comusers_date_birth_m', 'comusers_date_birth_d', 'comusers_notify', 'comusers_language', 'comusers_activate_key', 'comusers_activate_string', 'comusers_admin_note')); if (isset($data['user_login'])) { $user_login = $data['user_login']; } else { $user_login = $MSO->data['session']['users_login']; } if (isset($data['password'])) { $password = $data['password']; } else { $password = $MSO->data['session']['users_password']; } # проверка можно ли редактировать этому пользователю с этим паролем и этим разрешением if (!mso_check_user_password($user_login, $password, 'admin_comusers')) { return array('result' => 0, 'description' => 'Login/password incorrect'); } $comusers_id = isset($data['comusers_id']) ? (int) $data['comusers_id'] : 0; if ($comusers_id <= 0) { return array('result' => 0, 'description' => 'Comuser ID incorrect'); } $comusers_email = isset($data['comusers_email']) ? $data['comusers_email'] : ''; # нет email - ошибка if (!$comusers_email or !mso_valid_email($comusers_email)) { return array('result' => 0, 'description' => 'Email incorrect'); } ### пароль $comusers_new_password = ''; if (isset($data['comusers_new_password'])) { $comusers_new_password = mso_strip($data['comusers_new_password'], false); if ($comusers_new_password and strlen($comusers_new_password) > 6) { $comusers_new_password = mso_md5($comusers_new_password); } else { return array('result' => 0, 'description' => 'Password incorrect'); } } $comusers_nik = isset($data['comusers_nik']) ? $data['comusers_nik'] : ''; $comusers_icq = isset($data['comusers_icq']) ? $data['comusers_icq'] : ''; $comusers_url = isset($data['comusers_url']) ? $data['comusers_url'] : ''; $comusers_msn = isset($data['comusers_msn']) ? $data['comusers_msn'] : ''; $comusers_jaber = isset($data['comusers_jaber']) ? $data['comusers_jaber'] : ''; $comusers_skype = isset($data['comusers_skype']) ? $data['comusers_skype'] : ''; $comusers_avatar_url = isset($data['comusers_avatar_url']) ? $data['comusers_avatar_url'] : ''; $comusers_description = isset($data['comusers_description']) ? $data['comusers_description'] : ''; $comusers_date_birth_y = isset($data['comusers_date_birth_y']) ? $data['comusers_date_birth_y'] : '1970'; $comusers_date_birth_m = isset($data['comusers_date_birth_m']) ? $data['comusers_date_birth_m'] : '1'; $comusers_date_birth_d = isset($data['comusers_date_birth_d']) ? $data['comusers_date_birth_d'] : '1'; $comusers_notify = isset($data['comusers_notify']) ? $data['comusers_notify'] : '0'; $comusers_language = isset($data['comusers_language']) ? $data['comusers_language'] : 'ru'; $comusers_activate_key = isset($data['comusers_activate_key']) ? $data['comusers_activate_key'] : ''; $comusers_activate_string = isset($data['comusers_activate_string']) ? $data['comusers_activate_string'] : ''; $comusers_admin_note = isset($data['comusers_admin_note']) ? $data['comusers_admin_note'] : ''; # дату в MySQL $comusers_date_birth = mso_date_convert_to_mysql($comusers_date_birth_y, $comusers_date_birth_m, $comusers_date_birth_d); $upd_data = array('comusers_nik' => $comusers_nik, 'comusers_admin_note' => $comusers_admin_note, 'comusers_email' => $comusers_email, 'comusers_icq' => $comusers_icq, 'comusers_url' => $comusers_url, 'comusers_msn' => $comusers_msn, 'comusers_jaber' => $comusers_jaber, 'comusers_skype' => $comusers_skype, 'comusers_avatar_url' => $comusers_avatar_url, 'comusers_description' => $comusers_description, 'comusers_date_birth' => $comusers_date_birth, 'comusers_notify' => $comusers_notify, 'comusers_language' => $comusers_language, 'comusers_activate_string' => $comusers_activate_string, 'comusers_activate_key' => $comusers_activate_key); if ($comusers_new_password) { $upd_data['comusers_password'] = $comusers_new_password; } // _pr($upd_data); $CI->db->where('comusers_id', $comusers_id); $res = $CI->db->update('comusers', $upd_data) ? '1' : '0'; mso_flush_cache(); // сбросим кэш $response = array('result' => $res, 'description' => 'Update'); return $response; }
// проверяем корректность email // если все ок, отправляем $preferences = array(); if ($post['f_files']) { $fn = getinfo('uploads_dir') . $post['f_files']; if (file_exists($fn)) { $preferences['attach'] = $fn; } } $list = explode("\n", $post['f_list']); foreach ($list as $email) { $res = true; // проверяем валидность email // если ок, то отправляем // если возврат false, всё рубим - проблема с почтой if (mso_valid_email($email)) { $res = mso_mail($email, $post['f_subject'], $post['f_message'], $post['f_from'], $preferences); if ($res) { echo '<div class="update">' . t('Отправлено: ') . $email . '</div>'; } else { echo '<div class="error">' . t('Ошибка отправки почты на сервере.') . '</div>'; break; } } else { echo '<div class="error">' . t('Неверный адрес: ') . $email . '</div>'; } } } } } ?>
$userpassword = random_string('alnum', 12); // генератор пароля $useremail = ''; $namesite = ''; $demoposts = 0; $error = false; if ($step == 3 and $_POST) { mso_checkreferer(); // проверка на чужой реферер if ($_POST['mysubmit']) { $username = isset($_POST['username']) ? mso_strip($_POST['username'], true) : false; $userpassword = isset($_POST['userpassword']) ? mso_strip($_POST['userpassword'], true) : false; $useremail = $_POST['useremail'] ? mso_strip($_POST['useremail'], true) : false; $namesite = isset($_POST['namesite']) ? mso_strip($_POST['namesite'], true) : false; $demoposts = isset($_POST['demoposts']) ? (int) mso_strip($_POST['demoposts'], true) : 0; if (!mso_valid_email($useremail)) { $useremail = false; } if (strlen($userpassword) < 6) { $userpassword = false; } if (!$useremail or !$username or !$userpassword or !$namesite) { $step = 2; $error = '<h2 class="error">' . t('Ошибочные или неполные данные!', 'install') . '</h2>'; } if ($step === 3) { require_once APPPATH . 'views/install/install-common.php'; //require_once ('install-common.php'); $res = mso_install_newsite(array('username' => $username, 'userpassword' => mso_md5($userpassword), 'userpassword_orig' => $userpassword, 'useremail' => $useremail, 'namesite' => $namesite, 'demoposts' => $demoposts, 'ip' => $_SERVER['REMOTE_ADDR'])); } } else {
if (isset($post['f_fields_guestbook'][$key])) { $ins_data['guestbook_' . $key] = $post['f_fields_guestbook'][$key]; $text_email .= $key . ': ' . $post['f_fields_guestbook'][$key] . "\n"; } } // pr($ins_data); $res = $CI->db->insert('guestbook', $ins_data) ? '1' : '0'; if ($res) { echo '<div class="mso-message-ok">' . t('Ваш отзыв добавлен!'); if ($options['moderation']) { echo ' ' . t('Он будет опубликован после одобрения модератором.'); } echo '</div>'; $text_email = t("Новая запись в гостевой книге") . ": \n" . $text_email; $text_email .= "\n" . t("Редактировать") . ": " . getinfo('siteurl') . 'admin/guestbook/editone/' . $CI->db->insert_id() . "\n"; if ($options['email'] and mso_valid_email($options['email'])) { mso_mail($options['email'], t('Новая запись в гостевой книге'), $text_email); } } else { echo '<div class="mso-message-error">' . t('Ошибка добавления в базу данных...') . '</div>'; } mso_flush_cache(); // тут бы редирект, но мы просто убиваем сессию $CI->session->sess_destroy(); } } else { // тут форма, если не было post echo '<div class="mso-guestbook"><form method="post">' . mso_form_session('f_session_id'); foreach ($options['fields_arr'] as $key => $val) { echo '<p><label><span>' . t($val) . '</span>'; if ($key != 'text') {
function _mso_login() { global $MSO; // обрабатываем POST если есть if ($_POST) { $_POST = mso_clean_post(array('flogin_submit' => 'base', 'flogin_redirect' => 'base', 'flogin_user' => 'base', 'flogin_password' => 'base', 'flogin_session_id' => 'base')); } if ($_POST and isset($_POST['flogin_submit']) and isset($_POST['flogin_redirect']) and isset($_POST['flogin_user']) and isset($_POST['flogin_password']) and isset($_POST['flogin_session_id'])) { sleep(3); // задержка - примитивная защита от подбора пароля $flogin_session_id = $_POST['flogin_session_id']; # защита сесии if ($MSO->data['session']['session_id'] != $flogin_session_id) { mso_redirect('loginform/error'); } $flogin_redirect = urldecode($_POST['flogin_redirect']); if ($flogin_redirect == 'home') { $flogin_redirect = getinfo('siteurl'); } $flogin_user = $_POST['flogin_user']; $flogin_password = $_POST['flogin_password']; # проверяем на strip - запрещенные символы if (!mso_strip($flogin_user, true) or !mso_strip($flogin_password, true)) { mso_redirect('loginform/error'); } $flogin_password = mso_md5($flogin_password); $CI =& get_instance(); // если это комюзер, то логин = email // проверяем валидность email и если он верный, то ставим куку на этого комюзера // и редиректимся на главную (куку ставить только на главную!) // если же это обычный юзер-автор, то проверяем логин и пароль по базе if (mso_valid_email($flogin_user)) { // если в логине мыло, то проверяем сначала в таблице авторов $CI->db->from('users'); # таблица users $CI->db->select('*'); # все поля $CI->db->limit(1); # одно значение $CI->db->where('users_email', $flogin_user); // where 'users_login' = $flogin_user $CI->db->where('users_password', $flogin_password); // where 'users_password' = $flogin_password $query = $CI->db->get(); if ($query->num_rows() > 0) { $userdata = $query->result_array(); # добавляем юзера к сессии $CI->session->set_userdata('userlogged', '1'); $data = array('users_id' => $userdata[0]['users_id'], 'users_nik' => $userdata[0]['users_nik'], 'users_login' => $userdata[0]['users_login'], 'users_password' => $userdata[0]['users_password'], 'users_groups_id' => $userdata[0]['users_groups_id'], 'users_last_visit' => $userdata[0]['users_last_visit'], 'users_show_smiles' => $userdata[0]['users_show_smiles'], 'users_time_zone' => $userdata[0]['users_time_zone'], 'users_language' => $userdata[0]['users_language'], 'users_avatar_url' => $userdata[0]['users_avatar_url'], 'users_email' => $userdata[0]['users_email']); $CI->session->set_userdata($data); // сразу же обновим поле последнего входа $CI->db->where('users_id', $userdata[0]['users_id']); $CI->db->update('users', array('users_last_visit' => date('Y-m-d H:i:s'))); mso_redirect($flogin_redirect, true); } else { // это не автор, значит это комюзер $CI->db->select('comusers_id, comusers_password, comusers_email, comusers_nik, comusers_url, comusers_avatar_url, comusers_last_visit'); $CI->db->where('comusers_email', $flogin_user); $CI->db->where('comusers_password', $flogin_password); $query = $CI->db->get('comusers'); if ($query->num_rows()) { $comuser_info = $query->row_array(1); // вся инфа о комюзере // сразу же обновим поле последнего входа $CI->db->where('comusers_id', $comuser_info['comusers_id']); $CI->db->update('comusers', array('comusers_last_visit' => date('Y-m-d H:i:s'))); $expire = time() + 60 * 60 * 24 * 365; // 365 дней $name_cookies = 'maxsite_comuser'; $value = serialize($comuser_info); mso_add_to_cookie($name_cookies, $value, $expire, $flogin_redirect); // в куку для всего сайта exit; } else { mso_redirect('loginform/error'); exit; } } } else { // это обычный автор $CI->db->from('users'); # таблица users $CI->db->select('*'); # все поля $CI->db->limit(1); # одно значение $CI->db->where('users_login', $flogin_user); // where 'users_login' = $flogin_user $CI->db->where('users_password', $flogin_password); // where 'users_password' = $flogin_password $query = $CI->db->get(); if ($query->num_rows() > 0) { $userdata = $query->result_array(); # добавляем юзера к сессии $CI->session->set_userdata('userlogged', '1'); $data = array('users_id' => $userdata[0]['users_id'], 'users_nik' => $userdata[0]['users_nik'], 'users_login' => $userdata[0]['users_login'], 'users_password' => $userdata[0]['users_password'], 'users_groups_id' => $userdata[0]['users_groups_id'], 'users_last_visit' => $userdata[0]['users_last_visit'], 'users_show_smiles' => $userdata[0]['users_show_smiles'], 'users_time_zone' => $userdata[0]['users_time_zone'], 'users_language' => $userdata[0]['users_language'], 'users_avatar_url' => $userdata[0]['users_avatar_url'], 'users_email' => $userdata[0]['users_email']); $CI->session->set_userdata($data); // сразу же обновим поле последнего входа $CI->db->where('users_id', $userdata[0]['users_id']); $CI->db->update('users', array('users_last_visit' => date('Y-m-d H:i:s'))); mso_redirect($flogin_redirect, true); } else { mso_redirect('loginform/error'); } } // автор } else { $MSO->data['type'] = 'loginform'; $template_file = $MSO->config['templates_dir'] . $MSO->config['template'] . '/index.php'; if (file_exists($template_file)) { require $template_file; } else { show_error('Ошибка - отсутствует файл шаблона index.php'); } } }
function forms_content_callback($matches) { $text = $matches[1]; $text = str_replace("\r", "", $text); $text = str_replace(' ', ' ', $text); $text = str_replace("\t", ' ', $text); $text = str_replace('<br />', "<br>", $text); $text = str_replace('<br>', "\n", $text); $text = str_replace("\n\n", "\n", $text); $text = str_replace(' ', ' ', $text); $text = str_replace(' ', ' ', $text); $text = str_replace(' ', ' ', $text); $text = str_replace(' ', ' ', $text); $text = str_replace("\n ", "\n", $text); $text = str_replace("\n\n", "\n", $text); $text = trim($text); $out = ''; // убиваем исходный текст формы //$r = preg_match_all('!\[email=(.*?)\]|\[redirect=(.*?)\]\[subject=(.*?)\]|\[field\](.*?)\[\/field\]|\[ushka=(.*?)\]!is', $text, $all); // на какой email отправляем $r = preg_match_all('!\\[email=(.*?)\\]!is', $text, $all); if ($r) { $email = trim(implode(' ', $all[1])); } else { $email = mso_get_option('admin_email', 'general', '*****@*****.**'); } // тема письма $r = preg_match_all('!\\[subject=(.*?)\\]!is', $text, $all); if ($r) { $subject = trim(implode(' ', $all[1])); } else { $subject = tf('Обратная связь'); } // куда редиректить после отправки $r = preg_match_all('!\\[redirect=(.*?)\\]!is', $text, $all); if ($r) { $redirect = trim(implode(' ', $all[1])); } else { $redirect = ''; } // eirf к форме $r = preg_match_all('!\\[ushka=(.*?)\\]!is', $text, $all); if ($r) { $ushka = trim(implode(' ', $all[1])); } else { $ushka = ''; } // отправить копию на ваш email $r = preg_match_all('!\\[nocopy\\]!is', $text, $all); if ($r) { $forms_subscribe = false; } else { $forms_subscribe = true; } // кнопка Сброс формы $r = preg_match_all('!\\[noreset\\]!is', $text, $all); if ($r) { $reset = false; } else { $reset = true; } // pr($all); // поля формы $r = preg_match_all('!\\[field\\](.*?)\\[\\/field\\]!is', $text, $all); $f = array(); // массив для полей if ($r) { $fields = $all[1]; /* pr($fields); pr($email); pr($redirect); pr($subject); pr($ushka); */ if ($subject) { // поле тема письма делаем в виде обязательнного поля select. // формируем массив для формы $subject_f['require'] = 1; //$subject_f['type'] = 'select'; $subject_f['type'] = mb_strpos($subject, '#') === false ? 'text' : 'select'; // если это одиночное поле, но при этом текст сабжа начинается // с _ то ставим тип hidden if ($subject_f['type'] == 'text' and mb_strpos($subject, '_') === 0) { $subject = mb_substr($subject . ' ', 1, -1, 'UTF-8'); $subject_f['type'] = 'hidden'; } $subject_f['description'] = tf('Тема письма'); //$subject_f['tip'] = t('Выберите тему письма'); $subject_f['values'] = $subject; $subject_f['value'] = $subject; $subject_f['default'] = ''; // преобразования, чтобы сделать ключ для поля $f1['subject'] = $subject_f; // у поля тема будет ключ subject foreach ($f as $key => $val) { $f1[$key] = $val; } $f = $f1; } $i = 0; foreach ($fields as $val) { $val = trim($val); if (!$val) { continue; } $val = str_replace(' = ', '=', $val); $val = str_replace('= ', '=', $val); $val = str_replace(' =', '=', $val); $val = explode("\n", $val); // разделим на строки $ar_val = array(); foreach ($val as $pole) { $pole = preg_replace('!=!', '_VAL_', $pole, 1); $ar_val = explode('_VAL_', $pole); // строки разделены = type = select if (isset($ar_val[0]) and isset($ar_val[1])) { $f[$i][$ar_val[0]] = $ar_val[1]; } } $i++; } if (!$f) { return ''; } // нет полей - выходим // теперь по-идее у нас есть вся необходимая информация по полям и по форме // смотрим есть ли POST. Если есть, то проверяем введенные поля и если они корректные, // то выполняем отправку почты, выводим сообщение и редиректимся // если POST нет, то выводим обычную форму // pr($f); if ($_POST) { $_POST = mso_clean_post(array('forms_antispam1' => 'integer', 'forms_antispam2' => 'integer', 'forms_antispam' => 'integer', 'forms_name' => 'base', 'forms_email' => 'email', 'forms_session' => 'base')); } if ($post = mso_check_post(array('forms_session', 'forms_antispam1', 'forms_antispam2', 'forms_antispam', 'forms_name', 'forms_email', 'forms_submit'))) { mso_checkreferer(); $out .= '<div class="forms-post">'; // верный email? if (!($ok = mso_valid_email($post['forms_email']))) { $out .= '<div class="message error small">' . tf('Неверный email!') . '</div>'; } // антиспам if ($ok) { $antispam1s = (int) $post['forms_antispam1']; $antispam2s = (int) $post['forms_antispam2']; $antispam3s = (int) $post['forms_antispam']; if ($antispam1s / 984 + $antispam2s / 765 != $antispam3s) { // неверный код $ok = false; $out .= '<div class="message error small">' . tf('Неверная сумма антиспама') . '</div>'; } } if ($ok) { foreach ($f as $key => $val) { if ($ok and isset($val['require']) and $val['require'] == 1) { if (!isset($post['forms_fields'][$key]) or !$post['forms_fields'][$key]) { $ok = false; $out .= '<div class="message error small">' . tf('Заполните все необходимые поля!') . '</div>'; } } if (!$ok) { break; } } } // всё ок if ($ok) { //pr($post); // pr($f); // pr($redirect); // pr($email); // pr($subject); // формируем письмо и отправляем его if (!mso_valid_email($email)) { $email = mso_get_option('admin_email', 'general', '*****@*****.**'); } // куда приходят письма $message = t('Имя: ') . $post['forms_name'] . "\n"; $message .= t('Email: ') . $post['forms_email'] . "\n"; foreach ($post['forms_fields'] as $key => $val) { //pr($key); if ($key === 'subject' and $val) { $subject = $val; //pr($subject); continue; } $message .= $f[$key]['description'] . ': ' . $val . "\n\n"; } if ($_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_REFERER'] and $_SERVER['HTTP_USER_AGENT']) { $message .= "\n" . tf('IP-адрес: ') . $_SERVER['REMOTE_ADDR'] . "\n"; $message .= tf('Отправлено со страницы: ') . $_SERVER['HTTP_REFERER'] . "\n"; $message .= tf('Браузер: ') . $_SERVER['HTTP_USER_AGENT'] . "\n"; } // pr($message); $form_hide = mso_mail($email, $subject, $message, $post['forms_email']); if ($forms_subscribe and isset($post['forms_subscribe'])) { mso_mail($post['forms_email'], tf('Вами отправлено сообщение:') . ' ' . $subject, $message); } $out .= '<div class="message ok small">' . tf('Ваше сообщение отправлено!') . '</div><p>' . str_replace("\n", '<br>', htmlspecialchars($subject . "\n" . $message)) . '</p>'; if ($redirect) { mso_redirect($redirect, true); } } else { $out .= forms_show_form($f, $ushka, $forms_subscribe, $reset, $subject); } $out .= '</div>'; $out .= mso_load_jquery('jquery.scrollto.js'); $out .= '<script>$(document).ready(function(){$.scrollTo("div.forms-post", 500);})</script>'; } else { $out .= forms_show_form($f, $ushka, $forms_subscribe, $reset, $subject); } } return $out; }
function mso_email_message_new_comment_subscribe($data) { /* Array ( [comments_page_id] => 153 - id страницы [comments_content] => sdafsadfsdaf - текст комментария [comments_approved] => - если 0, то отправки нет [page_title] => тест - заголовок страницы [id] => 607 - id комментария -- [comments_comusers_id] => 1 - номер комюзера - пока не используется -- [comments_date] => 2009-12-10 20:45:39 - дата - пока не используется -- [comments_author_ip] => 127.0.0.1 - ip - пока не используется ) */ # Опция не рассылать подписку. if (!mso_get_option('allow_comments_subscribe', 'general', 1)) { return; } // комментарий не одобрен, не отсылаем if ($data['comments_approved'] == 0) { return; } // разослать нужно всем комюзерам у которых стоит получение уведомления о новом комментарии $CI =& get_instance(); $comusers_all = mso_get_comusers_all(); // все комюзеры $from = mso_get_option('admin_email_server', 'general', ''); $subject = '[' . getinfo('name_site') . '] ' . tf('Новый комментарий к') . ' "' . $data['page_title'] . '"'; $message = tf('Новый комментарий к') . ' "' . $data['page_title'] . '"' . NR . NR; $message .= tf('Текст:') . NR . mso_xss_clean($data['comments_content']); $message .= NR . NR . tf('Перейти к комментарию на сайте:') . NR . mso_get_permalink_page($data['comments_page_id']) . '#comment-' . $data['id'] . NR; foreach ($comusers_all as $comuser) { // отправлять на все комментарии сайта $subscribe_other_comments = (isset($comuser['meta']['subscribe_other_comments']) and $comuser['meta']['subscribe_other_comments']) ? true : false; // только на свой $subscribe_my_comments = (isset($comuser['meta']['subscribe_my_comments']) and $comuser['meta']['subscribe_my_comments']) ? true : false; if ($subscribe_other_comments or $subscribe_my_comments and isset($comuser['comments_pages_id'][$data['comments_page_id']])) { // можно отправлять if (mso_valid_email($comuser['comusers_email'])) { $data = array_merge($data, array('subscription' => true)); //А здесь для smtp_mail важно знать, чтобы запретить сохранять мыло в файл. $res = mso_mail($comuser['comusers_email'], $subject, $message, $from, $data); if (!$res) { break; } // ошибка отправки почты - рубим цикл } } } }
function forms_content_post($options, $files, $fields, $format) { $result['show_error'] = array(); // каждый элемент сообщение об ошибке $result['show_form'] = false; $result['show_ok'] = false; $result['fields'] = array(); // массив полей в случае ошибок $out = ''; // принимаем post if ($post = mso_check_post(array('forms_session', 'forms_fields'))) { mso_checkreferer(); $subject_key = false; // если у поля отмечен subject, то ставим номер поля $from_key = false; // если у поля отмечен from, то ставим номер поля // добавляем в массив $field полученные значения и сразу их чистим через mso_clean_str() foreach ($fields as $key => $field) { if (isset($fields[$key]['post_value'])) { unset($fields[$key]['post_value']); } $field = array_map('trim', $field); if (isset($post['forms_fields'][$key])) { $p_v = mso_clean_str($post['forms_fields'][$key], $field['clean']); $fields[$key]['post_value'] = $p_v; // обязательное поле и не получены данные (браузер должен был это сам отсеить) if ($field['require'] and !$p_v) { $result['show_error'][] = tf('Неверно заполнено поле: ') . $field['description']; } } if ($field['subject']) { $subject_key = $key; } if ($field['from']) { $from_key = $key; } } // если есть ошибки то выходим if ($result['show_error']) { $result['show_form'] = true; $result['fields'] = $fields; return $result; } // если были ошибки, то уже вышли из функции $prefs = ''; // дополнительные опции для mso_mail // если есть вложения if ($file_attaches = forms_files_post($files)) { // формируем вложения к письму $prefs['attach'] = $file_attaches; } // формируем само письмо // куда приходят письма $email = $options['email']; if (!mso_valid_email($email)) { $email = mso_get_option('admin_email', 'general', '*****@*****.**'); } // тема письма может быть в опциях $subject = $options['subject']; if (!$subject) { // нет, значит ищем в полях $subject = $fields[$subject_key]['post_value']; } // тема письма может быть в опциях $from = $options['from']; if (!$from) { // нет, значит ищем в полях $from = $fields[$from_key]['post_value']; } // pr($fields); $message = ''; foreach ($fields as $field) { $description = $field['description']; $post_value = $field['post_value']; $m = $format['mail_field']; $m = str_replace('[description]', $description, $m); $m = str_replace('[post_value]', $post_value, $m); $m = str_replace('[NR]', NR, $m); $message .= $m; } // добавляем служебную информацию $message .= tf('IP: ') . $_SERVER['REMOTE_ADDR'] . NR; $message .= tf('Браузер: ') . $_SERVER['HTTP_USER_AGENT'] . NR; mso_hook('forms_send', $post); // pr($email); // pr($subject); // pr($from); // pr($message); // pr($prefs); // тут отправка почты mso_mail($email, $subject, $message, $from, $prefs); // удаляем временные файлы вложений if ($files) { mso_flush_cache(false, 'forms_attaches/'); } $result['show_ok'] = true; } else { $result['show_error'][] = tf('Ошибка сессии'); } return $result; }
function maxsite_auth_custom($args = array()) { if (mso_segment(1) == 'maxsite-auth-form') { // здесь формируется форма для отправки запроса // данные отправляются POST // посетитель должен указать только адрес своего сайта // в hidden указываем нужные данные $redirect_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : getinfo('siteurl'); echo '<html><head> <title>Авторизация</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head><body> <form method="post" action="' . getinfo('site_url') . 'maxsite-auth-form-post"> <input type="hidden" name="redirect_url" value="' . urlencode($redirect_url) . '"> Укажите адрес сайта (с http://): <input type="text" name="url" value="" size="80"> <button type="submit">' . tf('Перейти к сайту') . '</button> </form> </body></html>'; die; // Форма ОК } elseif (mso_segment(1) == 'maxsite-auth-form-post') { // здесь происходит приём указанного адреса сайта и редирект на него с нужными данными if ($post = mso_check_post(array('redirect_url', 'url'))) { $url = mb_strtolower($post['url']); $url = trim(str_replace('/', ' ', $url)); $url = trim(str_replace(' ', ' ', $url)); $url = trim(str_replace(' ', '/', $url)); $url = str_replace('http:/', 'http://', $url); $url = $url . '/maxsite-auth-receive/' . base64_encode(getinfo('siteurl') . '##' . urldecode($post['redirect_url']) . '##' . substr(mso_md5(getinfo('siteurl')), 1, 5)); mso_redirect($url, true); } else { mso_redirect('maxsite-auth-form'); } // ошибочная форма - возвращаемся } elseif (mso_segment(1) == 'maxsite-auth-receive') { // принимаем входящие данные от другого сайта // здесь запрос на авторизацию // нужно проверить все входящие данные // проверить is_login // и сформировать форму с отправкой на входящий_сайт/maxsite-auth-reply if (!is_login()) { echo '<html><head> <title>Авторизация</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head><body> <div class="loginform">' . tf('Для авторизации необходимо войти на сайт') . '<br>'; mso_login_form(array('login' => tf('Логин:') . ' ', 'password' => tf('Пароль:') . ' ', 'submit' => ''), getinfo('siteurl') . mso_current_url()); echo '</div></body></html>'; die; // выходим ОК } else { //проверяем разрешения группы if (!mso_check_allow('maxsite_auth_edit')) { die(tf('Доступ к авторизации запрещен')); } $options = mso_get_option('plugin_maxsite_auth', 'plugins', array()); if (!isset($options['email']) or !$options['email']) { die(tf('Не задан ответный email')); } if (!isset($options['password']) or !$options['password']) { die(tf('Не задан ответный пароль')); } // смотрятся входные get-данные (расшифровка из base64) адрес-сайт1 $data64 = mso_segment(2); if (!$data64) { die(tf('Нет данных')); } // отладка // echo (getinfo('siteurl') . '##'. 'page/about' . '##' . substr(mso_md5(getinfo('siteurl')), 1, 5)); // echo '<br>'. base64_encode((getinfo('siteurl') . '##'. 'page/about' . '##' . substr(mso_md5(getinfo('siteurl')), 1, 5))); // echo '<br>'; // распаковываем данные $data = @base64_decode($data64); if (!$data) { die(tf('Ошибочные данные')); } // адрес-сайт1##адрес текущей страницы1##открытый ключ $data = explode('##', $data); // обработаем предварительно массив $data_1 = array(); foreach ($data as $element) { if ($d = trim($element)) { $data_1[] = $d; } } // должно быть 3 элемента if (count($data_1) != 3) { die(tf('Неверное количество данных')); } // pr($data_1); $data_siteurl = $data_1[0]; $data_redirect = $data_1[1]; $data_key = $data_1[2]; // все проверки пройдены // выводим форму с кнопкой Разрешить // данные для ответа // - адрес исходный // - адрес ответ - текущий // - адрес текущей страницы1 - редирект // - открытый ключ сайта2 // - зашифрованный «email##пароль» на основе открытых ключей сайт1 и сайт2 $CI =& get_instance(); $CI->load->library('encrypt'); // подключим библиотеку для шифрования // ключ строится по этому алгоритму // он должен быть фиксированным для одного сайта $my_key = substr(mso_md5(getinfo('siteurl')), 1, 5); // шифруем на основе двух ключей $my_email_pass = $CI->encrypt->encode($options['email'] . '##' . $options['password'], $data_key . $my_key); $data = getinfo('siteurl') . '##' . $data_siteurl . '##' . $data_redirect . '##' . $my_key . '##' . $my_email_pass; // pr($data); // pr($CI->encrypt->decode($my_email_pass, $data_key . $my_key)); echo '<html><head> <title>Авторизация</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head><body> <form method="post" action="' . $data_siteurl . 'maxsite-auth-reply"> <input type="hidden" name="data" value="' . base64_encode($data) . '"> <button type="submit">' . tf('Подтвердить авторизацию') . '</button> </form> </body></html>'; die; // выход ОК } } elseif (mso_segment(1) == 'maxsite-auth-reply') { // принимаем данные для авторизации от другого сайта // должен быть email и пароль // проверяем входящие данные // проверяем существаание такого комюзера // если его нет, то выполняем авторизацию // после выполняем автологин // и редиректимся на указанную страницу // pr($_POST); if ($post = mso_check_post(array('data'))) { // проверим referer if (!isset($_SERVER['HTTP_REFERER'])) { die(t('Ошибочный referer-сайт')); } $data = @base64_decode($post['data']); if (!$data) { die(t('Ошибочные данные')); } // ошибка распаковки // pr($data); $data = explode('##', $data); // обработаем предварительно массив $data_1 = array(); foreach ($data as $element) { if ($d = trim($element)) { $data_1[] = $d; } } // должно быть 5 элементов if (count($data_1) != 5) { die(t('Неверное количество данных')); } /* $data = getinfo('siteurl') . '##' . $data_siteurl . '##' . $data_redirect . '##' . $my_key . '##' . $my_email_pass; */ // pr($data_1); $data_siteurl = $data_1[0]; // сайт где была сделана авторизация = реферер $my_siteurl = $data_1[1]; // сайт с которого был отправлен запрос на авторизацию - должен быть равен текущему $data_redirect = $data_1[2]; // конечная страница $data_key = $data_1[3]; // открытый ключ сайта-авторизатора $data_email_pass = $data_1[4]; // email и пароль if (strpos($_SERVER['HTTP_REFERER'], $data_siteurl) === false) { die(t('Ошибочный referer-сайт')); } if ($my_siteurl != getinfo('siteurl')) { die(t('Ошибочный исходный сайт')); } $CI =& get_instance(); $CI->load->library('encrypt'); // подключим библиотеку для шифрования // ключ строится по этому алгоритму // он должен быть фиксированным для одного сайта $my_key = substr(mso_md5(getinfo('siteurl')), 1, 5); // шифруем на основе двух ключей $my_email_pass = $CI->encrypt->decode($data_email_pass, $my_key . $data_key); //_pr($my_email_pass); $email_pass = explode('##', $my_email_pass); if (count($email_pass) != 2) { die(tf('Неверные данные email-пароль')); } $email = $email_pass[0]; // email $pass = $email_pass[1]; // пароль if (!mso_valid_email($email)) { die(t('Неверный email')); } if (strlen($pass) < 6) { die(tf('Короткий пароль')); } // pr($email . ' ' . $pass); require_once getinfo('common_dir') . 'comments.php'; mso_comuser_auth(array('email' => $email, 'password' => $pass)); die; // выход ОК } else { die('Ошибочные данные'); } // нет POST } else { return $args; } }
function loginza_auth_init($arg = array()) { if (mso_segment(1) == 'maxsite-loginza-auth') { // тут придет token if (!empty($_POST['token'])) { // token пришел? делаем редрект на страницу авторизации $auth_url = "http://loginza.ru/api/authinfo?token=" . $_POST['token']; $profile = loginza_auth_request($auth_url); $profile = json_decode($profile); if (!is_object($profile) || !empty($profile->error_message) || !empty($profile->error_type)) { $res_profile = (array) $profile['error_type']; die($res_profile['error_type']); } $curpage = mso_url_get(); if ($curpage == getinfo('site_url')) { $curpage = false; } $email = (isset($profile->email) and mso_valid_email($profile->email)) ? $profile->email : null; $nick = isset($profile->name->full_name) ? $profile->name->full_name : null; if (isset($profile->email) and mso_valid_email($profile->email)) { require_once getinfo('common_dir') . 'comments.php'; mso_comuser_auth(array('email' => $email, 'comusers_nik' => $nick, 'redirect' => $curpage)); mso_redirect(getinfo('site_url'), true, 301); } else { // ссылка на главную или на предыдущую // pr( $profile ); $txt = t('Не удалось авторизоваться с помощью выбранного сервиса.<br>Возможно это связано с тем, что в ответ на запрос сервис не возратил Ваш e-mail') . '<br>'; $txt .= t('Вернуться на') . ' <a href="' . getinfo('site_url') . $curpage . '">' . t('предыдущую страницу') . '</a><br>'; $txt .= t('Вернуться на') . ' <a href="' . getinfo('site_url') . '">' . t('главную страницу') . '</a><br>'; die($txt); } die; } } return $arg; }
function fbauth_init($arg = array()) { if (mso_segment(1) == 'maxsite-fbauth') { if (!function_exists('curl_init')) { die('Не найдено PHP-расширение CURL'); } if (!function_exists('json_decode')) { die('Не найдено PHP-расширение JSON'); } $options = mso_get_option('plugin_fbauth', 'plugins', array()); if (!isset($options['app_id']) or !$options['app_id']) { die(t('Не задан app_id')); } if (!isset($options['app_secret']) or !$options['app_secret']) { die(t('Не задан app_secret')); } $app_id = $options['app_id']; $app_secret = $options['app_secret']; $my_url = getinfo('site_url') . 'maxsite-fbauth'; $code = isset($_REQUEST["code"]) ? $_REQUEST["code"] : null; if (!isset($code)) { $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . '&scope=email,user_website'; mso_redirect($dialog_url, true); } $token_url = "https://graph.facebook.com/oauth/access_token?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code; $access_token = fbauth_request($token_url); $graph_url = "https://graph.facebook.com/me?" . $access_token; $user0 = fbauth_request($graph_url); if (strpos($user0, '400 Bad Request') !== false) { die(t('Ошибка авторизации (400 Bad Request)')); } else { $user = json_decode($user0); if (isset($user->email) and mso_valid_email($user->email)) { require_once getinfo('common_dir') . 'comments.php'; mso_comuser_auth(array('email' => $user->email, 'comusers_nik' => $user->name)); // echo("Hello " . $user->name); } else { // ошибочный или отстутсвующий email die(t('Не удалось авторизоваться с помощью Facebook. Возможно это связано с тем, что в ответ на запрос сервис не возвратил ваш e-mail')); } die; } } return $arg; }