Example #1
0
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;
}
Example #2
0
function forms_content_callback($matches)
{
    $text = $matches[1];
    $text = str_replace("\r", "", $text);
    $text = str_replace('&nbsp;', ' ', $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);
    // число антиспама привязано и к сессии
    $ses = getinfo('session');
    $ses = preg_replace("/\\D/", '', $ses['session_id']);
    $ses = substr($ses, 0, 4);
    $antispam_num = date('jw') + date('t') * date('G') + $ses;
    // служебная секция [options]
    $def = array('email' => mso_get_option('admin_email', 'general', '*****@*****.**'), 'subject' => '', 'from' => '', 'redirect' => '', 'redirect_pause' => '2', 'ushka' => '', 'reset' => 1, 'require_title' => '*', 'antispam' => tf('Наберите число'), 'antispam_ok' => $antispam_num);
    $options = mso_section_to_array($text, 'options', $def, true);
    // если секции [options] нет, то ставим дефолт
    if (!$options) {
        $options[0] = $def;
    }
    if ($options) {
        $options = $options[0];
    }
    // служебная секция [files]
    $def = array('file_count' => 0, 'file_type' => 'jpg|jpeg|png|svg', 'file_max_size' => 200, 'file_description' => 'Скриншоты', 'file_tip' => tf('Выберите для загрузки файлы (jpg, jpeg, png, svg) размером до 200 Кб'));
    $files = mso_section_to_array($text, 'files', $def, true);
    if ($files) {
        $files = $files[0];
        // только одна секция
        // если полей меньше 1, то обнуляем массив
        if ((int) $files['file_count'] < 1) {
            $files = array();
        }
    }
    // поля формы [field]
    $def = array('require' => 0, 'type' => 'text', 'description' => '', 'placeholder' => '', 'tip' => '', 'value' => '', 'attr' => '', 'clean' => 'base', 'values' => '', 'default' => '', 'subject' => 0, 'from' => 0);
    $fields = mso_section_to_array($text, 'field', $def, true);
    $options = array_map('trim', $options);
    // pr($options);
    // pr($files);
    // pr($fields);
    // pr($text);
    // html-формат вывода
    $format['container_class'] = 'mso-forms';
    // css-класс для div-контейнера формы
    $format['textarea'] = '<p><label><span>[description][require_title]</span><textarea [field_param]>[value]</textarea></label>[tip]</p>';
    $format['checkbox'] = '<p><label><span></span><input [field_param] value="1" type="checkbox"> [description]</label>[tip]</p>';
    $format['select'] = '<p><label><span>[description][require_title]</span><select [field_param]>[option]</select></label>[tip]</p>';
    $format['input'] = '<p><label><span>[description][require_title]</span><input [field_param]></label>[tip]</p>';
    $format['tip'] = '<span class="mso-forms-tip">[tip]</span>';
    $format['file_description'] = '<p><label><span>[file_description]</span></label></p>';
    $format['file_field'] = '<p>[file_field]</p>';
    $format['file_tip'] = '<p><span class="mso-forms-tip">[file_tip]</span></p>';
    $format['message_ok'] = '<p class="mso-forms-ok">' . tf('Ваше сообщение отправлено') . '</p>';
    $format['message_error'] = '<p class="mso-forms-error">[error]</p>';
    $format['antispam'] = '<p><label><span>[antispam] [antispam_ok][require_title]</span>[input]</label></p>';
    $format['buttons'] = '<p class="mso-forms-buttons">[submit] [reset]</p>';
    $format['mail_field'] = '[description]: [post_value] [NR]';
    // подключаем файл формата из текущего шаблона
    if ($fn = mso_fe('custom/plugins/forms/format.php')) {
        require $fn;
    }
    $out = '';
    // затираем исходный текст формы
    if ($_POST) {
        // если это отправка
        $result_post = forms_content_post($options, $files, $fields, $format);
        // в $result_post результат отправки
        if ($result_post['show_ok']) {
            $out .= $format['message_ok'];
            if ($options['redirect']) {
                // редирект через N секунд
                header('Refresh: ' . $options['redirect_pause'] . '; url=' . $options['redirect']);
            }
        } elseif ($result_post['show_error']) {
            // вывод сообщений об ошибках
            foreach ($result_post['show_error'] as $error) {
                $out .= str_replace('[message_error]', tf($error), $format['message_error']);
            }
            if ($result_post['show_form']) {
                $out .= forms_show_form($options, $files, $result_post['fields'], $format);
            }
        }
    } else {
        // выводим форму
        $out .= forms_show_form($options, $files, $fields, $format);
    }
    return $out;
}