commit 5bbe30bea5fde0e41609f9b0fe34ef7a41da1bb5 Author: root Date: Sun Sep 11 17:14:11 2016 +0500 инициализация модуля diff --git a/contactsnew/class.contactsnew.php b/contactsnew/class.contactsnew.php new file mode 100644 index 0000000..eb4f8b8 --- /dev/null +++ b/contactsnew/class.contactsnew.php @@ -0,0 +1,1421 @@ + array( + 'new' => true, + 'title' => 'email', + 'type' => 'input', + 'main' => 1, + 'setting' => 'FILTER_VALIDATE_EMAIL', + 'required' => 1 + ), + 'subject' => array( + 'new' => true, + 'title' => 'subject', + 'type' => 'input', + 'main' => 1 + ), + 'receivers' => array( + 'new' => true, + 'title' => 'receivers', + 'type' => 'select', + 'main' => 1, + 'setting' => array() + ), + 'copy' => array( + 'new' => true, + 'title' => 'copy', + 'type' => 'checkbox', + 'main' => 1 + ), + 'captcha' => array( + 'new' => true, + 'title' => 'captcha', + 'type' => 'input', + 'main' => 1, + 'required' => 1 + ) + ); + // переменная для хранения формы + var $form = array(); + +/** + * Внутренние методы класса + */ + + /** + * Конструктор + */ + function __construct ($email) + { + $this->fields_main = array_keys($this->fields_main_data); + $this->fields_main_in_string = "'" . implode("','",$this->fields_main) . "'"; + } + + /** + * Метод забирает форму из бд по алиасу/id + */ + function _form ($alias_id,$_fields=true) + { + global $AVE_DB, $AVE_Template; + + // иначе забираем из бд форму + $form = array(); + // основные параметры + $form = $AVE_DB->Query(" + SELECT * FROM " . PREFIX . "_module_contactsnew_forms + WHERE + " . (is_numeric($alias_id) ? 'id' : 'alias') . " = '" . $alias_id . "' + ")->FetchAssocArray(); + // если форма не обнаружена, выходим + if (empty($form)) return array(); + $form['alias_id'] = $alias_id; + // получатели + $form['mail_set'] = unserialize($form['mail_set']); + + if ($_fields === true) + { + // поля + $sql = $AVE_DB->Query(" + SELECT * FROM " . PREFIX . "_module_contactsnew_fields + WHERE form_id = '" . $form['id'] . "' + ORDER BY id ASC + "); + $form['fields'] = array(); + while ($field = $sql->FetchAssocArray()) + { + // раскрываем массив настроек для селектов + if (in_array($field['type'],array('select','multiselect','doc','multidoc'))) + { + // @fix для v1.0 beta <= 2: поддержка одной рубрики, не массива + if (in_array($field['type'],array('doc','multidoc')) && !empty($field['setting']) && is_numeric($field['setting'])) + $field['setting'] = array(0 => $field['setting']); + else + $field['setting'] = unserialize($field['setting']) !== false ? unserialize($field['setting']) : array(); + } + // если тип поля поменялся, ставим пустую строку + elseif (unserialize($field['setting']) !== false) $field['setting'] = ''; + + // раскрываем массив опций по умолчанию для мультиселекта + if ($field['type'] == 'multiselect') + { + $field['defaultval'] = unserialize($field['defaultval']) !== false ? unserialize($field['defaultval']) : array(); + } + // если тип поля поменялся, ставим пустую строку + elseif (unserialize($field['defaultval']) !== false) $field['defaultval'] = ''; + + // главные поля + if (in_array($field['title'],$this->fields_main) && $field['main']) + { + $form['fields_main'][$field['title']] = $field['id']; + $field['title_lang'] = $AVE_Template->get_config_vars('mfld_' . $field['title']); + } + + $form['fields'][$field['id']] = $field; + } + } + // убираем слеши + $form = $this->_stripslashes($form); + + // сохраняем форму в переменную класса + $this->form = $form; + + return $form; + } + + /** + * Метод убирает слэши во всей переменной + */ + function _stripslashes($var) + { + if (!is_array($var)) return stripslashes($var); + else return array_map(array($this,'_stripslashes'),$var); + } + + /** + * Метод тримует всю переменную + */ + function _trim($var) + { + if (!is_array($var)) return trim($var); + else return array_map(array($this,'_trim'),$var); + } + + /** + * Метод чистит переменную от пустых значений и массивов + */ + function _cleanvar($var) + { + if (!is_array($var)) return trim($var) > '' ? trim($var) : null; + $narr = array(); + while(list($key, $val) = each($var)) + { + if (is_array($val)) + { + $val = _cleanvar($val); + if (count($val) > 0) $narr[$key] = $val; + } + else + { + if (trim($val) > '') $narr[$key] = $val; + } + } + unset ($var); + return $narr; + } + + /** + * Валидация Email-а + */ + function _email_validate ($email='') + { + return (filter_var($email, FILTER_VALIDATE_EMAIL) === false ? false : true); + } + + /** + * Проверка алиаса тега на валидность и уникальность + */ + function _alias_validate ($alias='',$fid=0) + { + global $AVE_DB; + // соответствие требованиям + if ( + empty ($alias) || + preg_match('/^[A-Za-z0-9-_]{1,20}$/i', $alias) !== 1 || + is_numeric($alias) + ) return 'syn'; + // уникальность + return !(bool)$AVE_DB->Query(" + SELECT 1 FROM " . PREFIX . "_module_contactsnew_forms + WHERE + alias = '" . $alias . "' AND + id != '" . $fid . "' + ")->GetCell(); + } + + /** + * Получение списка рубрик + */ + function _rubrics () + { + global $AVE_DB; + $rubs = array(); + $sql = $AVE_DB->Query(" + SELECT Id, rubric_title FROM " . PREFIX . "_rubrics + "); + while ($rub = $sql->FetchAssocArray()) $rubs[$rub['Id']] = $rub['rubric_title']; + return $rubs; + } + + /** + * Получение списка документов + */ + function _docs ($rubs_id = array()) + { + global $AVE_DB; + if (empty($rubs_id)) return array(); + // @fix для v1.0 beta <= 2: поддержка одной рубрики, не массива + if (!is_array($rubs_id)) $rubs_id = array(0 => $rubs_id); + $docs = array(); + $sql = $AVE_DB->Query(" + SELECT Id, document_title FROM " . PREFIX . "_documents + WHERE rubric_id IN (" . implode(',',$rubs_id) . ") + "); + while ($doc = $sql->FetchAssocArray()) $docs[$doc['Id']] = $doc['document_title']; + return $docs; + } + + /** + * Парсинг главных тегов + */ + function _parse_tags ($str) + { + global $AVE_Core, $AVE_DB; + if (empty($_SESSION['user_login'])) $_SESSION['user_login'] = (UGROUP != 2) ? $AVE_DB->Query("SELECT user_name FROM " . PREFIX . "_users WHERE Id = '" . UID . "'")->GetCell() : ''; + + $str = preg_replace_callback('/\[tag:(css|js):([^ :\/]+):?(\S+)*\]/', array($AVE_Core, '_parse_combine'), $str); + $str = parse_hide($str); + return str_replace(array( + '[tag:docid]', + '[tag:formtitle]', + // @fix для v1.0 beta <= 2: поддержка тега formaction + '[tag:formaction]', + '[tag:document]', + '[tag:formalias]', + '[tag:path]', + '[tag:mediapath]', + '[tag:captcha]', + '[tag:uname]', + '[tag:ufname]', + '[tag:ulname]', + '[tag:ulogin]', + '[tag:uemail]', + '[tag:sitename]', + '[tag:sitehost]', + ),array( + $AVE_Core->curentdoc->Id, + $this->form['title'], + $_SERVER['REQUEST_URI'], + $_SERVER['REQUEST_URI'], + $this->form['alias'] ? $this->form['alias'] : $this->form['id'], + ABS_PATH, + ABS_PATH . 'templates/' . THEME_FOLDER . '/', + 'inc/captcha.php', + $_SESSION['user_name'], + get_user_rec_by_id(UID)->firstname, + get_user_rec_by_id(UID)->lastname, + $_SESSION['user_login'], + $_SESSION['user_email'], + htmlspecialchars(get_settings('site_name'), ENT_QUOTES), + $_SERVER['HTTP_HOST'], + ),$str); + } + + /** + * Внутренний PHP-парсер + */ + function _eval2var($code) + { + global $AVE_DB, $AVE_Core, $AVE_Template; + ob_start(); + eval($code); + return ob_get_clean(); + } + + /** + * Приведение тегов главных полей к стандартной форме + */ + function _parse_tag_fld_main ($tpl='', $save_is=false) + { + foreach ($this->fields_main as $field_title) + { + $count = 0; + $tpl = str_replace(array( + '[tag:fld:' . $field_title . ']', + '[tag:if_fld:' . $field_title, + '[tag:elseif_fld:' . $field_title, + ), array( + '[tag:fld:' . $this->form['fields_main'][$field_title] . ']', + '[tag:if_fld:' . $this->form['fields_main'][$field_title], + '[tag:elseif_fld:' . $this->form['fields_main'][$field_title], + ),$tpl,$count); + if ($save_is) $this->form['is_' . $field_title] = $count > 0 ? true : false; + } + return $tpl; + } + + /** + * Замена тега условия + */ + function _parse_tag_if (&$tpl,$tag='',$open = true) + { + if ($open) + $tpl = str_replace(array('[tag:' . $tag . ']','[/tag:' . $tag . ']'),'',$tpl); + else + $tpl = preg_replace('/\[tag:' . $tag . '](.*?)\[\/tag:' . $tag . ']/si','',$tpl); + } + + /** + * Замена тега названия поля + */ + function _parse_tag_title ($matches) + { + $field_id = $matches[1]; + return !$this->form['fields'][$field_id]['main'] ? $this->form['fields'][$field_id]['title'] : $this->form['fields'][$field_id]['title_lang']; + } + + /** + * Замена тега поля на значение $_POST + */ + function _parse_tag_fld_post ($matches) + { + return $_POST['form-' . $this->form['alias_id']][$matches[1]]; + } + + /** + * Замена тега поля при выводе формы + */ + function _parse_tag_fld_form ($matches) + { + $field_id = (int)$matches[1]; + // забираем массив поля + $field = $this->form['fields'][$field_id]; + // если поля нет, возвращаем тег обратно + if (empty($field)) return $matches[0]; + // если поле выключено, возвращаем пустую строку + if (empty($field['active'])) return ''; + $alias_id = $this->form['alias_id']; + $fld_val = $this->form['is_submited'] ? $this->_stripslashes($_POST['form-' . $alias_id][$field_id]) : + (in_array($field['type'],array('input','textarea')) ? $this->_eval2var('?>' . $field['defaultval'] . 'form['fields'][$field_id]['is_used'] = true; + $input = ''; + $return = ''; + + switch ($field['type']) + { + case 'input': + $input = ''; + break; + + case 'textarea': + $input = ''; + break; + + case 'select': + $input = ''; + break; + + case 'multiselect': + $input = ''; + break; + + case 'checkbox': + $input = ' + + '; + break; + + case 'file': + $input = ''; + break; + + case 'doc': + $input = ''; + break; + + case 'multidoc': + $input = ''; + break; + } + // вставляем поле в шаблон поля + $return = trim($field['tpl']) > '' ? str_replace('[tag:fld]',$input,$field['tpl']) : $input; + // парсим теги названия и id + $return = str_replace(array( + '[tag:id]', + '[tag:title]', + ),array( + $field['id'], + '[tag:title:' . $field_id . ']', + ),$return); + // если попытка отправить форму, обрабатываем валидацию и пустоту + if ($this->form['is_submited']) + { + // валидация (только для капчи, input, textarea и file) + if ( + ($field['title'] == 'captcha' && $field['main'] && $this->form['is_captcha'] === true) || + (in_array($field['type'],array('input','textarea','file')) && !empty($field['setting'])) + ) + { + $valid = false; + // если капча + if ($field['title'] == 'captcha') $valid = (empty($_SESSION['captcha_keystring']) || empty($fld_val) || $_SESSION['captcha_keystring'] != $fld_val) ? false : true; + // если файл + elseif ($field['type'] == 'file') $valid = ($_FILES['form-' . $alias_id]['size'][$field_id] / 1024 / 1024) <= $field['setting']; + // если передали регулярку + elseif ($field['setting']{0} == '/') $valid = preg_match($field['setting'],$fld_val) === 1 ? true : false; + // если константу + elseif (defined($field['setting'])) $valid = filter_var($fld_val,constant($field['setting'])) !== false ? true : false; + // иначе, ничего не делаем + else return 'Неверные параметры валидации!'; + // парсим теги валидности + $this->_parse_tag_if($return,'if_valid',$valid); + $this->_parse_tag_if($return,'if_invalid',!$valid); + // записываем результаты + $this->form['ajax']['fields'][$field_id]['validate'] = true; + $this->form['ajax']['fields'][$field_id]['pattern'] = $field['setting']; + $this->form['ajax']['fields'][$field_id]['is_valid'] = $valid; + if (!$valid) + { + $this->form['is_valid'] = false; + $this->form['ajax']['form']['is_valid'] = false; + } + } + else + { + $this->form['ajax']['fields'][$field_id]['validate'] = false; + $this->form['ajax']['fields'][$field_id]['is_valid'] = null; + } + // пустота (для любых обязательных полей) + if (!empty($field['required']) && $field['required']) + { + if ($field['type'] == 'file') + $empty = ( + empty($_FILES['form-' . $alias_id]['tmp_name'][$field_id]) || + !empty($_FILES['form-' . $alias_id]['error'][$field_id]) + ); + else + { + $clean_fld_val = $this->_cleanvar($fld_val); + $empty = empty($clean_fld_val); + } + // парсим теги + $this->_parse_tag_if($return,'if_empty',$empty); + $this->_parse_tag_if($return,'if_notempty',!$empty); + // записываем результаты + $this->form['ajax']['fields'][$field_id]['required'] = true; + $this->form['ajax']['fields'][$field_id]['is_empty'] = $empty; + if ($empty) + { + $this->form['is_valid'] = false; + $this->form['ajax']['form']['is_valid'] = false; + } + } + else + { + $this->form['ajax']['fields'][$field_id]['required'] = false; + $this->form['ajax']['fields'][$field_id]['is_empty'] = null; + } + } + // удаляем оставшиеся теги + $this->_parse_tag_if($return,'if_valid',false); + $this->_parse_tag_if($return,'if_invalid',false); + $this->_parse_tag_if($return,'if_empty',false); + $this->_parse_tag_if($return,'if_notempty',false); + + return $return; + } + + /** + * Замена тега поля в шаблоне письма + */ + function _parse_tag_fld_mail ($matches) + { + global $AVE_DB, $AVE_Template; + + $field_id = (int)$matches[1]; + // забираем массив поля + $field = $this->form['fields'][$field_id]; + // если поля нет, возвращаем тег обратно + if (empty($field)) return $matches[0]; + // если поля не было в шаблоне формы, убираем тег + if ($field['is_used'] !== true || empty($field['active'])) return ''; + // иначе, продолжаем + $alias_id = $this->form['alias_id']; + $val = $_POST['form-' . $alias_id][$field_id]; + $newval = ''; + $tag_mail_empty = ($this->form['mail_set']['format'] === 'text' ? '<' : '<') . $AVE_Template->get_config_vars('tag_mail_empty') . ($this->form['mail_set']['format'] === 'text' ? '>' : '>'); + + // делаем поправки для типов + switch ($field['type']) + { + case 'select': + $newval = $field['setting'][$val]; + if ($field['title'] == 'receivers') $newval = $newval['name']; + break; + + case 'multiselect': + foreach ($val as $val1) $newval .= $field['setting'][$val1] . ','; + $newval = rtrim($newval,','); + break; + + case 'checkbox': + $newval = ($val ? $AVE_Template->get_config_vars('yes') : $AVE_Template->get_config_vars('no')); + break; + + case 'doc': + if (!empty($val)) $newval = $AVE_DB->Query("SELECT document_title FROM " . PREFIX . "_documents WHERE Id='" . $val . "'")->GetCell(); + break; + + case 'multidoc': + if (!empty($val)) + { + $sql = $AVE_DB->Query("SELECT document_title FROM " . PREFIX . "_documents WHERE Id IN (" . implode(',',$val) . ")"); + while ($titl = $sql->GetCell()) $titls[] = $titl; + $newval = implode(', ',$titls); + } + break; + + case 'file': + $newval = implode(', ',$_FILES['form-' . $alias_id]['name']); + break; + + default: + $newval = $val; + } + return (empty($newval) ? $tag_mail_empty : $newval); + } + +/** + * Внешние методы класса + */ + + /** + * Вывод списка форм + */ + function forms_list () + { + global $AVE_DB, $AVE_Template; + $assign = array(); + + $limit = 20; + $start = get_current_page() * $limit - $limit; + $sql = $AVE_DB->Query(" + SELECT SQL_CALC_FOUND_ROWS + f.*, + SUM(IF(h.status='new',1,0)) AS history_new, + SUM(IF(h.status='viewed',1,0)) AS history_viewed, + SUM(IF(h.status='replied',1,0)) AS history_replied + FROM " . PREFIX . "_module_contactsnew_forms AS f + LEFT OUTER JOIN " . PREFIX . "_module_contactsnew_history AS h ON f.id = h.form_id + GROUP BY f.id + ORDER BY f.id ASC + LIMIT " . $start . "," . $limit . " + "); + $num = (int)$AVE_DB->Query("SELECT FOUND_ROWS()")->GetCell(); + $pages = @ceil($num / $limit); + if ($num > $limit) + { + $page_nav = '{t}'; + $page_nav = get_pagination($pages, 'page', $page_nav); + $AVE_Template->assign('page_nav', $page_nav); + } + + while ($row = $sql->FetchAssocArray()) + { + $assign['forms'][] = $row; + } + + $AVE_Template->assign($assign); + $AVE_Template->assign('content', $AVE_Template->fetch($this->tpl_dir . 'forms.tpl')); + } + + /** + * Создание/редактирование формы + */ + function form_edit () + { + global $AVE_DB, $AVE_Template; + $form = array(); + $assign = array(); + $fid = $assign['fid'] = !empty($_REQUEST['fid']) ? (int)$_REQUEST['fid'] : 0; + + if ($fid) + { + $form = $this->_form($fid); + + // для правильного вывода селектов + if (empty($form['mail_set']['receivers'])) $form['mail_set']['receivers'] = array(0 => array()); + foreach ($form['fields'] as &$field) + { + if (($field['type'] == 'select' || $field['type'] == 'multiselect') && empty($field['setting'])) + { + $field['setting'] = array(0 => ''); + $field['setting_empty'] = true; + } + } + } + + // алерт при открытии правки + if (!empty($_SESSION['module_contactsnew_admin'][$fid]['edit_alert'])) + { + $assign['alert']['text'] = $AVE_Template->get_config_vars($_SESSION['module_contactsnew_admin'][$fid]['edit_alert']['text']); + $assign['alert']['theme'] = $_SESSION['module_contactsnew_admin'][$fid]['edit_alert']['theme']; + unset($_SESSION['module_contactsnew_admin'][$fid]['edit_alert']); + } + $assign['form'] = $form; + $assign['form_fields_tpl'] = $this->tpl_dir . 'form_fields.tpl'; + $assign['rubrics'] = $this->_rubrics(); + + // назначаем массив CodeMirror + $assign['codemirror'] = array( + 'rubheader' => 200, + 'from_name' => 60, + 'from_email' => 60, + 'subject_tpl' => 60, + 'form_tpl' => 460, + 'mail_tpl' => 460, + 'finish_tpl' => 320, + 'code_onsubmit' => 200, + 'code_onvalidate' => 200, + 'code_onsend' => 200 + ); + + $AVE_Template->assign($assign); + $AVE_Template->assign('content', $AVE_Template->fetch($this->tpl_dir . 'form_edit.tpl')); + } + + /** + * Получение полей через аякс + */ + function form_fields_fetch () + { + global $AVE_DB, $AVE_Template; + $fid = $assign['fid'] = !empty($_REQUEST['fid']) ? (int)$_REQUEST['fid'] : 0; + if (!$fid) return; + $form = $this->_form($fid); + // для правильного вывода селектов + if (empty($form['mail_set']['receivers'])) $form['mail_set']['receivers'] = array(0 => array()); + foreach ($form['fields'] as &$field) + { + if (($field['type'] == 'select' || $field['type'] == 'multiselect') && empty($field['setting'])) + { + $field['setting'] = array(0 => ''); + $field['setting_empty'] = true; + } + } + $AVE_Template->assign('fields',$form['fields']); + $AVE_Template->assign('rubrics',$this->_rubrics()); + $AVE_Template->assign('field_tpl_open',$_REQUEST['field_tpl_open']); + + return $AVE_Template->fetch($this->tpl_dir . 'form_fields.tpl'); + } + + /** + * Сохранение формы + */ + function form_save ($fid) + { + global $AVE_DB; + + // проверяем Email-ы получателей + $receivers = array(); + foreach ($_REQUEST['mail_set']['receivers'] as $receiver) + { + if ($this->_email_validate($receiver['email'])) $receivers[] = $receiver; + } + $_REQUEST['mail_set']['receivers'] = $receivers; + // параметры отправителя + if (!trim($_REQUEST['mail_set']['from_email']) > '') $_REQUEST['mail_set']['from_email'] = get_settings('mail_from'); + if (!trim($_REQUEST['mail_set']['from_name']) > '') $_REQUEST['mail_set']['from_name'] = get_settings('mail_from_name'); + + if ($fid) + { + $AVE_DB->Query(" + UPDATE " . PREFIX . "_module_contactsnew_forms + SET + title = '" . addslashes($_REQUEST['title']) . "', + protection = '" . (int)$_REQUEST['protection'] . "', + " . (($_REQUEST['alias'] === '' || $this->_alias_validate($_REQUEST['alias'],$fid) === true) ? " alias = '" . $_REQUEST['alias'] . "'," : '') . " + mail_set = '" . addslashes(serialize($_REQUEST['mail_set'])) . "', + rubheader = '" . addslashes($_REQUEST['rubheader']) . "', + form_tpl = '" . addslashes($_REQUEST['form_tpl']) . "', + mail_tpl = '" . addslashes($_REQUEST['mail_tpl']) . "', + finish_tpl = '" . addslashes($_REQUEST['finish_tpl']) . "', + code_onsubmit = '" . addslashes($_REQUEST['code_onsubmit']) . "', + code_onvalidate = '" . addslashes($_REQUEST['code_onvalidate']) . "', + code_onsend = '" . addslashes($_REQUEST['code_onsend']) . "' + WHERE + id = '" . $fid . "' + "); + } + else + { + $mail_set = array( + 'from_name' => get_settings('mail_from_name'), + 'from_email' => get_settings('mail_from'), + 'receivers' => array(0 => array( + 'name' => get_settings('mail_from_name'), + 'email' => get_settings('mail_from') + ), + ), + 'subject_tpl' => '[tag:formtitle]', + 'format' => 'text' + ); + $AVE_DB->Query(" + INSERT INTO " . PREFIX . "_module_contactsnew_forms + SET + title = '" . addslashes($_REQUEST['title']) . "', + " . (($this->_alias_validate($_REQUEST['alias'],$fid) === true || $_REQUEST['alias'] === '') ? " alias = '" . $_REQUEST['alias'] . "'," : '') . " + mail_set = '" . addslashes(serialize($mail_set)) . "' + "); + $fid = (int)$AVE_DB->InsertId(); + $_REQUEST['fields'] = $this->fields_main_data; + // прописываем алерт об успешном создании + if ($fid > 0) $_SESSION['module_contactsnew_admin'][$fid]['edit_alert'] = array('text' => 'created', 'theme' => 'accept'); + + // если устанавливаем пример + if (!empty($_REQUEST['demo'])) + { + $demo = array(); + include(BASE_DIR . '/modules/contactsnew/demo.php'); + $_REQUEST = array_merge($_REQUEST,$demo); + // обновляем форму с данными примера + $this->form_save($fid); + // подставляем в шаблон новые id полей + $demo['form_tpl'] = preg_replace_callback('/\[tag:fld:(\d+)]/', create_function('$matches','return "[tag:fld:" . $_REQUEST["demo_change"][(int)$matches[1]] . "]";'),$demo['form_tpl']); + $AVE_DB->Query(" + UPDATE " . PREFIX . "_module_contactsnew_forms + SET + form_tpl = '" . addslashes($demo['form_tpl']) . "' + WHERE id = '" . $fid . "' + "); + return $fid; + } + } + + // сохраняем поля + foreach ($_REQUEST['fields'] as $field_id => $field) + { + if (!trim($field['title'])) continue; + if (is_array($field['setting'])) + { + $settings = array(); + foreach ($field['setting'] as $setting) + { + // если получатели + if ($field['title'] == 'receivers' && is_array($setting) && trim($setting['name']) > '' && trim($setting['email']) > '' && $this->_email_validate($setting['email'])) + $settings[] = $setting; + // другое + elseif (!is_array($setting) && trim($setting) > '') + $settings[] = $setting; + } + $field['setting'] = serialize($settings); + } + elseif ($field['type'] == 'file') $field['setting'] = (int)$field['setting']; + + if (is_array($field['defaultval'])) $field['defaultval'] = serialize($field['defaultval']); + + $sql = " + title = '" . addslashes($field['title']) . "', + active = '" . (int)$field['active'] . "', + type = '" . $field['type'] . "', + setting = '" . addslashes($field['setting']) . "', + required = '" . (int)$field['required'] . "', + defaultval = '" . addslashes($field['defaultval']) . "', + attributes = '" . addslashes(trim($field['attributes'])) . "', + tpl = '" . addslashes($field['tpl']) . "' + "; + if ($field['new']) + { + $AVE_DB->Query(" + INSERT INTO " . PREFIX . "_module_contactsnew_fields + SET + form_id = '" . (int)$fid . "', + main = '" . (int)$field['main'] . "', + " . $sql . " + "); + if ($_REQUEST['demo']) $_REQUEST['demo_change'][$field_id] = (int)$AVE_DB->InsertId(); + } + else + { + $AVE_DB->Query(" + UPDATE " . PREFIX . "_module_contactsnew_fields + SET + " . $sql . " + WHERE + id = '" . (int)$field_id . "' AND + form_id = '" . $fid . "' + "); + } + } + foreach ($_REQUEST['field_del'] as $field_id => $delete) + { + if (empty($delete)) continue; + $AVE_DB->Query(" + DELETE FROM " . PREFIX . "_module_contactsnew_fields + WHERE + id = '" . (int)$field_id . "' AND + main != '1' + "); + } + + return $fid; + } + + /** + * Удаление формы + */ + function form_del ($fid) + { + global $AVE_DB; + + $AVE_DB->Query(" + DELETE FROM " . PREFIX . "_module_contactsnew_forms + WHERE id = '" . $fid . "' + "); + $AVE_DB->Query(" + DELETE FROM " . PREFIX . "_module_contactsnew_fields + WHERE form_id = '" . $fid . "' + "); + } + + /** + * Сохранение формы + */ + function form_copy ($fid) + { + global $AVE_DB; + + // форма + $form = $AVE_DB->Query(" + SELECT * FROM " . PREFIX . "_module_contactsnew_forms + WHERE id = '" . $fid . "' + ")->FetchAssocArray(); + if (empty($form)) return; + $query = "INSERT INTO " . PREFIX . "_module_contactsnew_forms SET "; + foreach ($form as $key => $val) + { + if ($key == 'id' || $key == 'alias') continue; + $query .= $key . " = '" . addslashes($val) . "', "; + } + $query = rtrim($query,', '); + $AVE_DB->Query($query); + $fid_new = (int)$AVE_DB->InsertId(); + + // поля + $sql = $AVE_DB->Query(" + SELECT * FROM " . PREFIX . "_module_contactsnew_fields + WHERE form_id = '" . $fid . "' + "); + while ($row = $sql->FetchAssocArray()) + { + if (empty($row['id'])) continue; + $query = "INSERT INTO " . PREFIX . "_module_contactsnew_fields SET "; + foreach ($row as $key => $val) + { + if ($key == 'id') continue; + elseif ($key == 'form_id') $val = $fid_new; + $query .= $key . " = '" . addslashes($val) . "', "; + } + $query = rtrim($query,', '); + $AVE_DB->Query($query); + } + + return $fid_new; + } + + /** + * Вывод формы + */ + function form_display ($alias_id) + { + global $AVE_Template; + $form = $this->_form($alias_id); + if (empty($form)) return "[mod_contactsnew:$alias_id] - " . $AVE_Template->get_config_vars('form_notfound'); + // по дефолту форма валидна, но не отправлена - потом перезаписываем, если что + $this->form['is_valid'] = true; + $this->form['ajax']['form']['is_valid'] = true; + $this->form['ajax']['form']['is_sent'] = false; + $this->form['ajax']['form']['finish_tpl'] = null; + // rubheader + $GLOBALS['user_header']['module_contactsnew_' . $alias_id] = $this->_parse_tags($this->form['rubheader']); + + // вывод финишной страницы, если включена проверка от повторной отправки + if (!empty($_GET['mcnfinish']) && $form['protection']) + { + if ($_SESSION['mcnfinish'][$form['id'] . $_GET['mcnfinish']] === true) + { + unset($_SESSION['mcnfinish'][$form['id'] . $_GET['mcnfinish']]); + // формируем финишную страницу + $tpl = $this->_parse_tags($form['finish_tpl']); + $tpl = $this->_eval2var('?>' . $tpl . 'form['is_submited'] = false; + if (!empty($_POST['form-' . $alias_id])) + { + $this->form['is_submited'] = true; + // выполняем код после отправки формы + eval('?>' . $this->form['code_onsubmit'] . 'form['form_tpl']; + // меняем теги основных полей на стандартные + $tpl = $this->_parse_tag_fld_main($tpl,true); + // парсим теги полей и названий + $tpl = preg_replace_callback('/\[tag:fld:(\d+)]/', array($this,'_parse_tag_fld_form'), $tpl); + $tpl = preg_replace_callback('/\[tag:title:([A-Za-z0-9-_]+)]/', array($this,'_parse_tag_title'),$tpl); + unset($_SESSION['captcha_keystring']); + // выполняем код после валидации + eval('?>' . $this->form['code_onvalidate'] . 'form['is_submited'] === true && $this->form['is_valid'] === true) + return $this->form_submit($alias_id); + // иначе - заканчиваем вывод + else + { + // парсим основные теги + $tpl = $this->_parse_tags($tpl); + // теги общей валидности + if ($this->form['is_submited']) + { + $this->_parse_tag_if($tpl,'if_form_valid',$this->form['is_valid']); + $this->_parse_tag_if($tpl,'if_form_invalid',!$this->form['is_valid']); + } + else + { + $this->_parse_tag_if($tpl,'if_form_valid',false); + $this->_parse_tag_if($tpl,'if_form_invalid',false); + } + // заменяем теги условий + $tpl = preg_replace('/\[tag:(if|elseif)_fld:(\d*)(.*?)]/si','',$tpl); + $tpl = str_replace(array('[tag:else_fld]','[/tag:if_fld]'),array('',''),$tpl); + // выполняем код + return $this->_eval2var('?>' . $tpl . 'form; + $fields = $form['fields']; + $fid = $form['id']; + + // формируем список получателей + $recs = array(); + + // пользователь (отправка копии) + if ( + ($form['is_copy'] === true && $_POST['form-' . $alias_id][$form['fields_main']['copy']] == 1) || + $fields[$form['fields_main']['copy']]['defaultval'] == 1 + ) + { + $email = ''; + if ($form['is_email'] === true) $email = $_POST['form-' . $alias_id][$form['fields_main']['email']]; + if (empty($email)) $email = $_SESSION['user_email']; + if (!empty($email)) + { + $recs[] = array( + 'email' => $email, + 'name' => $_SESSION['user_name'], + 'agent' => 'user', + ); + } + $history['email'] = $email; + } + + // главные получатели + $recs = array_merge($recs,$form['mail_set']['receivers']); + + // выбранные в форме получатели + if ($this->form['is_receivers'] === true) + { + $recs_field_id = $form['fields_main']['receivers']; + $recs[] = $fields[$recs_field_id]['setting'][$_POST['form-' . $alias_id][$recs_field_id]]; + } + + // если ни один получатель не назначен, отправляем админскому + if (empty($recs)) $recs[] = array( + 'name' => get_settings('mail_from_name'), + 'email' => get_settings('mail_from') + ); + + // перезаписываем список уникальных получателей в переменную письма + $this->form['receivers'] = array(); + foreach ($recs as $rec) + { + if (!isset($this->form['receivers'][$rec['email']]) && trim($rec['email']) > '') $this->form['receivers'][trim($rec['email'])] = $rec; + } + $recs = $this->form['receivers']; + $recs[] = array('agent' => 'history'); + + // обрабатываем тему по умолчанию + if (!$form['fields'][$form['fields_main']['subject']]['active'] || !$form['fields'][$form['fields_main']['subject']]['is_used']) + { + $_POST['form-' . $alias_id][$form['fields_main']['subject']] = $form['fields'][$form['fields_main']['subject']]['defaultval']; + } + + // обрабатываем шаблон письма + $tpl = $form['mail_tpl']; + // меняем теги основных полей на стандартные + $tpl = $this->_parse_tag_fld_main($tpl); + // парсим [tag:easymail] + if (strpos($tpl,'[tag:easymail]') !== false) + { + $easy = ''; + foreach ($fields as $field_id => $field) + { + if ($field['is_used'] !== true || $field['title'] == 'captcha' || empty($field['active'])) continue; + $easy .= "[tag:title:$field_id]" . ": [tag:fld:$field_id];" . ($form['mail_set']['format'] === 'text' ? "\r\n" : '
'); + } + // убираем последний перевод строки + $easy = ($form['mail_set']['format'] === 'text') ? rtrim($easy) : substr($easy,0,-4); + $tpl = str_replace('[tag:easymail]',$easy,$tpl); + } + // парсим теги полей и названий + $tpl = preg_replace_callback('/\[tag:fld:(\d+)]/', array($this,'_parse_tag_fld_mail'),$tpl); + $tpl = preg_replace_callback('/\[tag:title:([A-Za-z0-9-_]+)]/', array($this,'_parse_tag_title'),$tpl); + // парсим основные теги + $tpl = $this->_parse_tags($tpl); + // заменяем теги условий + $tpl = preg_replace('/\[tag:(if|elseif)_fld:(\d*)(.*?)]/si','',$tpl); + $tpl = str_replace(array('[tag:else_fld]','[/tag:if_fld]'),array('',''),$tpl); + + // файлы-вложения + $attach = array(); + if (!empty($_FILES['form-' . $alias_id]['tmp_name'])) + { + foreach ($_FILES['form-' . $alias_id]['name'] as $field_id => $fname) + { + $ext = (end(explode('.', $fname))); + if ( + !empty($_FILES['form-' . $alias_id]['tmp_name'][$field_id]) && + !empty($form['fields'][$field_id]) && + empty($_FILES['form-' . $alias_id]['error'][$field_id]) && + !in_array($ext,array('php', 'phtml', 'php3', 'php4', 'php5', 'js', 'pl')) + ) + { + $fname = BASE_DIR . '/' . ATTACH_DIR . '/' . str_replace(' ', '_', mb_strtolower(trim($fname))); + if (file_exists($fname)) $fname = rtrim($fname,'.' . $ext) . '_' . mt_rand(0,10000) . '.' . $ext; + @move_uploaded_file($_FILES['form-' . $alias_id]['tmp_name'][$field_id], $fname); + $attach[] = $fname; + } + } + } + + // Имя отправителя + $from_name_tpl = $form['mail_set']['from_name']; + $from_name_tpl = $this->_parse_tags($from_name_tpl); + $from_name_tpl = $this->_parse_tag_fld_main($from_name_tpl); + $from_name_tpl = preg_replace_callback('/\[tag:fld:(\d+)]/', array($this,'_parse_tag_fld_post'),$from_name_tpl); + // Email отправителя + $from_email_tpl = $form['mail_set']['from_email']; + $from_email_tpl = $this->_parse_tags($from_email_tpl); + $from_email_tpl = $this->_parse_tag_fld_main($from_email_tpl); + $from_email_tpl = preg_replace_callback('/\[tag:fld:(\d+)]/', array($this,'_parse_tag_fld_post'),$from_email_tpl); + // Тема + $subject_tpl = $form['mail_set']['subject_tpl']; + $subject_tpl = $this->_parse_tags($subject_tpl); + $subject_tpl = $this->_parse_tag_fld_main($subject_tpl); + $subject_tpl = preg_replace_callback('/\[tag:fld:(\d+)]/', array($this,'_parse_tag_fld_post'),$subject_tpl); + + // отправляем письма + foreach ($recs as $rec) + { + $mail = $tpl; + $from_name = $from_name_tpl; + $from_email = $from_email_tpl; + $subject = $subject_tpl; + + $if_user_open = ($rec['agent'] === 'user'); + $if_admin_open = !$if_user_open; + + $this->_parse_tag_if($mail,'if_user',$if_user_open); + $this->_parse_tag_if($mail,'if_admin',$if_admin_open); + $this->_parse_tag_if($subject,'if_user',$if_user_open); + $this->_parse_tag_if($subject,'if_admin',$if_admin_open); + + // @fix для v1.0 beta <= 2: поддержка тега if_notuser + $this->_parse_tag_if($mail,'if_notuser',$if_admin_open); + $this->_parse_tag_if($subject,'if_notuser',$if_admin_open); + + $mail = trim($this->_eval2var('?>' . $mail . '_eval2var('?>' . $subject . 'Query(" + INSERT INTO " . PREFIX . "_module_contactsnew_history + SET + form_id = '" . $fid . "', + email = '" . $history['email'] . "', + subject = '" . addslashes($subject) . "', + date = '" . time() . "', + dialog = '" . addslashes(serialize($history['dialog'])) . "', + postdata = '" . addslashes(serialize($_POST)) . "' + "); + unset($history); + } + // иначе, отправляем письмо + else + { + $this->_parse_tag_if($from_name,'if_user',$if_user_open); + $this->_parse_tag_if($from_name,'if_admin',$if_admin_open); + $this->_parse_tag_if($from_email,'if_user',$if_user_open); + $this->_parse_tag_if($from_email,'if_admin',$if_admin_open); + $from_name = $this->_eval2var('?>' . $from_name . '_eval2var('?>' . $from_email . '' . $this->form['code_onsend'] . '_parse_tags($form['finish_tpl']); + $tpl = $this->_eval2var('?>' . $tpl . 'form['ajax']['form']['is_sent'] = true; + $this->form['ajax']['form']['finish_tpl'] = $tpl; + return $tpl; + } + } + + /** + * Вывод истории + */ + function history_list ($fid) + { + global $AVE_DB, $AVE_Template; + $assign = array(); + $assign['fid'] = $fid; + $assign['form'] = $this->_form($fid,false); + + $limit = 50; + $start = get_current_page() * $limit - $limit; + $sql = $AVE_DB->Query(" + SELECT SQL_CALC_FOUND_ROWS * + FROM " . PREFIX . "_module_contactsnew_history + WHERE form_id = '" . $fid . "' + ORDER BY date DESC + LIMIT " . $start . "," . $limit . " + "); + $num = (int)$AVE_DB->Query("SELECT FOUND_ROWS()")->GetCell(); + $pages = @ceil($num / $limit); + if ($num > $limit) + { + $page_nav = '{t}'; + $page_nav = get_pagination($pages, 'page', $page_nav); + $AVE_Template->assign('page_nav', $page_nav); + } + + while ($row = $sql->FetchAssocArray()) + { + unset($row['dialog']); + $assign['dialogs'][] = $row; + } + + $assign = $this->_stripslashes($assign); + $AVE_Template->assign($assign); + $AVE_Template->assign('content', $AVE_Template->fetch($this->tpl_dir . 'history.tpl')); + } + + /** + * Сохранение статуса диалога + */ + function dialog_status ($hid) + { + global $AVE_DB; + + if ($_REQUEST['status'] !== 'new') + { + $AVE_DB->Query(" + UPDATE " . PREFIX . "_module_contactsnew_history + SET + status = '" . $_REQUEST['status'] . "' + WHERE id = '" . $hid . "' + "); + } + + if (empty($_REQUEST['ajax'])) + { + header('Location: index.php?do=modules&action=modedit&mod=contactsnew&moduleaction=history_list&fid=' . $_REQUEST['fid'] . '&cp=' . SESS); + exit; + } + } + + /** + * Вывод диалога + */ + function history_dialog ($hid) + { + global $AVE_DB, $AVE_Template; + $assign = array(); + + $assign['hid'] = $hid; + $history = $AVE_DB->Query(" + SELECT * + FROM " . PREFIX . "_module_contactsnew_history + WHERE id = '" . $hid . "' + ")->FetchAssocArray(); + $history['dialog'] = unserialize($history['dialog']); + $history = $this->_stripslashes($history); + $assign['fid'] = $history['form_id']; + $assign['form'] = $this->_form($history['form_id'],false); + + // меняем статус на прочитанное + if ($history['status'] === 'new') + { + $AVE_DB->Query(" + UPDATE " . PREFIX . "_module_contactsnew_history + SET + status = 'viewed' + WHERE id = '" . $hid . "' + "); + } + + // обращение + $request_author = $AVE_DB->Query(" + SELECT Id AS user_id, user_name, firstname, lastname + FROM " . PREFIX . "_users + WHERE email = '" . $history['email'] . "' + ")->FetchAssocArray(); + if (!empty($request_author)) $history['dialog']['request'] = array_merge($history['dialog']['request'], $request_author); + + // ответы + foreach ($history['dialog']['response'] as &$response) + { + $response_author = $AVE_DB->Query(" + SELECT user_name, firstname, lastname + FROM " . PREFIX . "_users + WHERE Id = '" . $response['user_id'] . "' + ")->FetchAssocArray(); + if (!empty($response_author)) $response = array_merge($response, $response_author); + } + + // форма ответа + if (empty($history['dialog']['response_draft'])) + { + $history['dialog']['response_draft'] = array( + 'from_email' => get_settings('mail_from'), + 'from_name' => get_settings('mail_from_name'), + 'body' => "\r\n\r\n\r\n--\r\n" . get_settings('mail_signature'), + ); + } + + // алерт при открытии + if (!empty($_SESSION['module_contactsnew_admin'][$fid]['dialog_alert'])) + { + $assign['alert']['text'] = $AVE_Template->get_config_vars($_SESSION['module_contactsnew_admin'][$fid]['dialog_alert']['text']); + $assign['alert']['theme'] = $_SESSION['module_contactsnew_admin'][$fid]['dialog_alert']['theme']; + unset($_SESSION['module_contactsnew_admin'][$fid]['dialog_alert']); + } + + $AVE_Template->assign($assign); + $AVE_Template->assign($history); + $AVE_Template->assign('content', $AVE_Template->fetch($this->tpl_dir . 'dialog.tpl')); + } + + /** + * Сохранение и отправка ответа + */ + function history_dialog_submit ($hid) + { + global $AVE_DB; + + $history = $AVE_DB->Query(" + SELECT * + FROM " . PREFIX . "_module_contactsnew_history + WHERE id = '" . $hid . "' + ")->FetchAssocArray(); + $history['dialog'] = unserialize($history['dialog']); + + if ($_REQUEST['send']) + { + $response = $_POST; + $response['user_id'] = UID; + $response['date'] = time(); + $history['dialog']['response'][] = $response; + $history['status'] = 'replied'; + unset($history['dialog']['response_draft']); + send_mail( + $history['email'], + $_POST['body'], + $_POST['subject'], + $_POST['from_email'], + $_POST['from_name'], + $_POST['format'], + array(), + false,false + ); + } + else + { + $history['dialog']['response_draft'] = $_POST; + } + + $AVE_DB->Query(" + UPDATE " . PREFIX . "_module_contactsnew_history + SET + dialog = '" . addslashes(serialize($history['dialog'])) . "', + status = '" . $history['status'] . "' + WHERE id = '" . $hid . "' + "); + + if ($_REQUEST['send']) + { + // прописываем алерт об успешной отправке письма + $_SESSION['module_contactsnew_admin'][$fid]['dialog_alert'] = array('text' => 'respose_sent', 'theme' => 'accept'); + + header('Location: index.php?do=modules&action=modedit&mod=contactsnew&moduleaction=history_dialog&hid=' . $hid . '&cp=' . SESS); + exit; + } + } +} +?> diff --git a/contactsnew/demo.php b/contactsnew/demo.php new file mode 100644 index 0000000..4f925e6 --- /dev/null +++ b/contactsnew/demo.php @@ -0,0 +1,454 @@ + +'[tag:hide:2:У вас нет прав для заполнения данной формы!] +
+
+ [tag:if_form_invalid] +
+ При заполнении формы возникли ошибки! + +
+ [/tag:if_form_invalid] + [tag:fld:email] + [tag:fld:subject] + [tag:fld:receivers] + [tag:fld:6] + [tag:fld:7] + [tag:fld:8] + [tag:fld:9] + [tag:fld:10] + [tag:fld:11] + [tag:fld:copy] + [tag:fld:captcha] +
+
+ +
+
+
+ [tag:if_form_invalid] + + [/tag:if_form_invalid] +
+[/tag:hide]', +'ajax' => '[tag:hide:2:У вас нет прав для заполнения данной формы!] +
+
+
+ Если форма не работает, убедитесь, что скрипт jquery.form.min.js подключен к странице + +
+ [tag:if_form_invalid] +
+ При заполнении формы возникли ошибки! + +
+ [/tag:if_form_invalid] + [tag:fld:email] + [tag:fld:subject] + [tag:fld:receivers] + [tag:fld:6] + [tag:fld:7] + [tag:fld:8] + [tag:fld:9] + [tag:fld:10] + [tag:fld:11] + [tag:fld:copy] + [tag:fld:captcha] +
+
+ +
+
+
+ +
+[/tag:hide]', +'ajax_o' => +'[tag:hide:2:У вас нет прав для заполнения данной формы!] +
+
+
+ Если форма не работает, убедитесь, что скрипт jquery.form.min.js подключен к странице + +
+ [tag:if_form_invalid] +
+ При заполнении формы возникли ошибки! + +
+ [/tag:if_form_invalid] + [tag:fld:email] + [tag:fld:subject] + [tag:fld:receivers] + [tag:fld:6] + [tag:fld:7] + [tag:fld:8] + [tag:fld:9] + [tag:fld:10] + [tag:fld:11] + [tag:fld:copy] +
+
+ +
+
+
+ +
+[/tag:hide]' +); + +$demo = array( + 'mail_set' => array( + 'from_name' => '[tag:if_user]Администратор сайта [tag:sitename][/tag:if_user] +[tag:if_admin][tag:uname] ([tag:ulogin])[/tag:if_admin]', + 'from_email' => '[tag:if_user]admin@form.ru[/tag:if_user] +[tag:if_admin][tag:fld:email][/tag:if_admin]', + 'subject_tpl' => '[tag:if_user]Вы заполнили форму "[tag:fld:subject]" на сайте [tag:sitename][/tag:if_user] +[tag:if_admin]Заполнена форма: [tag:formtitle] ([tag:formalias])[/tag:if_admin]', + 'receivers' => array( + array( + 'email' => 'form@form.ru', + 'name' => 'form' + ) + ), + 'format' => 'text', + ), + 'rubheader' => '', + 'form_tpl' => $form_tpl[$_REQUEST['demo']], + 'mail_tpl' => '[tag:if_user] +Здравствуйте, [tag:uname]! + +Вы заполнили форму на нашем сайте и ввели следующие данные: + +[tag:easymail] + +В ближайшее время администрация рассмотрит вашу заявку +-- +С уважением, Администрация +[/tag:if_user] + +[tag:if_admin] +Здравствуйте! + +Пользователь [tag:uname] ([tag:ulogin]) заполнил форму \\\'[tag:formtitle]\\\' ([tag:formalias]) и ожидает ответа. + +Введённые данные: +[tag:easymail] +[/tag:if_admin]', + 'finish_tpl' => '
+ Форма успешно отправлена! +
', + 'code_onsubmit' => '', + 'code_onvalidate' => '', + 'code_onsend' => '', + 'fields' => array( + 1 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'email', + 'active' => 1, + 'type' => 'input', + 'main' => 1, + 'setting' => 'FILTER_VALIDATE_EMAIL', + 'required' => 1, + 'defaultval' => '[tag:uemail]', + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_invalid]invalid[/tag:if_invalid]" placeholder="[tag:title]" data-placement="right" data-content="Неверный email!" data-container="body" data-trigger="manual"', + 'tpl' => '
+ +
+ [tag:fld] + [tag:if_valid][/tag:if_valid] + [tag:if_invalid][/tag:if_invalid] +
+
' + ), + 2 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'subject', + 'active' => 1, + 'type' => 'input', + 'main' => 1, + 'setting' => '', + 'required' => 1, + 'defaultval' => 'Тема по умолчанию', + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_empty]invalid[/tag:if_empty]" placeholder="[tag:title]" data-placement="right" data-content="Укажите тему!" data-container="body" data-trigger="manual"', + 'tpl' => '
+ +
+ [tag:fld] + [tag:if_notempty][/tag:if_notempty] + [tag:if_empty][/tag:if_empty] +
+
' + ), + 3 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'receivers', + 'active' => 1, + 'type' => 'select', + 'main' => 1, + 'setting' => array( + 0 => array( + 'email' => 'sales@form.ru', + 'name' => 'Отдел продаж' + ), + 1 => array( + 'email' => 'support@form.ru', + 'name' => 'Служба поддержки' + ) + ), + 'required' => 0, + 'defaultval' => 0, + 'attributes' => 'id="fld[[tag:id]]" class="form-control" placeholder="[tag:title]"', + 'tpl' => '
+ +
+ [tag:fld] +
+
' + ), + 4 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'copy', + 'active' => 1, + 'type' => 'checkbox', + 'main' => 1, + 'setting' => '', + 'required' => 0, + 'defaultval' => 1, + 'attributes' => '', + 'tpl' => '
+
+
+ +
+
+
' + ), + 5 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'captcha', + 'active' => 1, + 'type' => 'input', + 'main' => 1, + 'setting' => '', + 'required' => 1, + 'defaultval' => '', + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_invalid]invalid[/tag:if_invalid]" placeholder="[tag:title]" data-placement="right" data-content="Неверный код!" data-container="body" autocomplete="off" data-trigger="manual"', + 'tpl' => '
+ +
+ [tag:fld] + [tag:if_invalid][/tag:if_invalid] +
+
' + ), + 6 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'Выбор', + 'active' => 1, + 'type' => 'select', + 'main' => 0, + 'setting' => array('выберите','а','б','в'), + 'required' => 1, + 'defaultval' => 0, + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_empty]invalid[/tag:if_empty]" placeholder="[tag:title]" data-placement="right" data-content="Выберите что-нибудь!" data-container="body" data-trigger="manual"', + 'tpl' => '
+ +
+ [tag:fld] +
+
' + ), + 7 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'Текстовое поле', + 'active' => 1, + 'type' => 'textarea', + 'main' => 0, + 'setting' => '', + 'required' => 0, + 'defaultval' => '', + 'attributes' => 'id="fld[[tag:id]]" class="form-control" placeholder="[tag:title]"', + 'tpl' => '
+ +
+ [tag:fld] + [tag:if_notempty][/tag:if_notempty] + [tag:if_empty][/tag:if_empty] +
+
' + ), + 8 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'Мульти', + 'active' => 1, + 'type' => 'multiselect', + 'main' => 0, + 'setting' => array(1,2,3,4,5), + 'required' => 1, + 'defaultval' => array(0,3), + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_empty]invalid[/tag:if_empty]" placeholder="[tag:title]" data-placement="right" data-content="Выберите что-нибудь!" data-container="body" data-trigger="manual"', + 'tpl' => '
+ +
+ [tag:fld] +
+
' + ), + 9 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'Файл (до 1мб)', + 'active' => 1, + 'type' => 'file', + 'main' => 0, + 'setting' => 1, + 'required' => 0, + 'defaultval' => '', + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_invalid]invalid[/tag:if_invalid] [tag:if_empty]invalid[/tag:if_empty]" placeholder="[tag:title]" data-placement="right" data-content="[tag:if_invalid]Слишком большой файл![/tag:if_invalid][tag:if_empty]Отсутствует файл![/tag:if_empty]" data-container="body" data-trigger="manual"', + 'tpl' => '
+ +
+ [tag:fld] + [tag:if_notempty][tag:if_valid][/tag:if_valid][/tag:if_notempty] + [tag:if_invalid][/tag:if_invalid] + [tag:if_empty][/tag:if_empty] +
+
' + ), + 10 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'Документ', + 'active' => 1, + 'type' => 'doc', + 'main' => 0, + 'setting' => array(1), + 'required' => 0, + 'defaultval' => '', + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_empty]invalid[/tag:if_empty]" placeholder="[tag:title]"', + 'tpl' => '
+ +
+ [tag:fld] +
+
' + ), + 11 => array( + 'new' => true, + 'form_id' => $fid, + 'title' => 'Мультидокумент', + 'active' => 1, + 'type' => 'multidoc', + 'main' => 0, + 'setting' => array(1,2), + 'required' => 0, + 'defaultval' => '', + 'attributes' => 'id="fld[[tag:id]]" class="form-control [tag:if_empty]invalid[/tag:if_empty]" placeholder="[tag:title]"', + 'tpl' => '
+ +
+ [tag:fld] +
+
' + ) + ) +); diff --git a/contactsnew/index.php b/contactsnew/index.php new file mode 100644 index 0000000..9c20174 --- /dev/null +++ b/contactsnew/index.php @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/contactsnew/js/jquery.form.min.js b/contactsnew/js/jquery.form.min.js new file mode 100644 index 0000000..7321a3b --- /dev/null +++ b/contactsnew/js/jquery.form.min.js @@ -0,0 +1,11 @@ +/*! + * jQuery Form Plugin + * version: 3.51.0-2014.06.20 + * Requires jQuery v1.5 or later + * Copyright (c) 2014 M. Alsup + * Examples and documentation at: http://malsup.com/jquery/form/ + * Project repository: https://github.com/malsup/form + * Dual licensed under the MIT and GPL licenses. + * https://github.com/malsup/form#copyright-and-license + */ +!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):e("undefined"!=typeof jQuery?jQuery:window.Zepto)}(function(e){"use strict";function t(t){var r=t.data;t.isDefaultPrevented()||(t.preventDefault(),e(t.target).ajaxSubmit(r))}function r(t){var r=t.target,a=e(r);if(!a.is("[type=submit],[type=image]")){var n=a.closest("[type=submit]");if(0===n.length)return;r=n[0]}var i=this;if(i.clk=r,"image"==r.type)if(void 0!==t.offsetX)i.clk_x=t.offsetX,i.clk_y=t.offsetY;else if("function"==typeof e.fn.offset){var o=a.offset();i.clk_x=t.pageX-o.left,i.clk_y=t.pageY-o.top}else i.clk_x=t.pageX-r.offsetLeft,i.clk_y=t.pageY-r.offsetTop;setTimeout(function(){i.clk=i.clk_x=i.clk_y=null},100)}function a(){if(e.fn.ajaxSubmit.debug){var t="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(t):window.opera&&window.opera.postError&&window.opera.postError(t)}}var n={};n.fileapi=void 0!==e("").get(0).files,n.formdata=void 0!==window.FormData;var i=!!e.fn.prop;e.fn.attr2=function(){if(!i)return this.attr.apply(this,arguments);var e=this.prop.apply(this,arguments);return e&&e.jquery||"string"==typeof e?e:this.attr.apply(this,arguments)},e.fn.ajaxSubmit=function(t){function r(r){var a,n,i=e.param(r,t.traditional).split("&"),o=i.length,s=[];for(a=0;o>a;a++)i[a]=i[a].replace(/\+/g," "),n=i[a].split("="),s.push([decodeURIComponent(n[0]),decodeURIComponent(n[1])]);return s}function o(a){for(var n=new FormData,i=0;i').val(m.extraData[d].value).appendTo(w)[0]:e('').val(m.extraData[d]).appendTo(w)[0]);m.iframeTarget||v.appendTo("body"),g.attachEvent?g.attachEvent("onload",s):g.addEventListener("load",s,!1),setTimeout(t,15);try{w.submit()}catch(h){var x=document.createElement("form").submit;x.apply(w)}}finally{w.setAttribute("action",i),w.setAttribute("enctype",c),r?w.setAttribute("target",r):f.removeAttr("target"),e(l).remove()}}function s(t){if(!x.aborted&&!F){if(M=n(g),M||(a("cannot access response document"),t=k),t===D&&x)return x.abort("timeout"),void S.reject(x,"timeout");if(t==k&&x)return x.abort("server abort"),void S.reject(x,"error","server abort");if(M&&M.location.href!=m.iframeSrc||T){g.detachEvent?g.detachEvent("onload",s):g.removeEventListener("load",s,!1);var r,i="success";try{if(T)throw"timeout";var o="xml"==m.dataType||M.XMLDocument||e.isXMLDoc(M);if(a("isXml="+o),!o&&window.opera&&(null===M.body||!M.body.innerHTML)&&--O)return a("requeing onLoad callback, DOM not available"),void setTimeout(s,250);var u=M.body?M.body:M.documentElement;x.responseText=u?u.innerHTML:null,x.responseXML=M.XMLDocument?M.XMLDocument:M,o&&(m.dataType="xml"),x.getResponseHeader=function(e){var t={"content-type":m.dataType};return t[e.toLowerCase()]},u&&(x.status=Number(u.getAttribute("status"))||x.status,x.statusText=u.getAttribute("statusText")||x.statusText);var c=(m.dataType||"").toLowerCase(),l=/(json|script|text)/.test(c);if(l||m.textarea){var f=M.getElementsByTagName("textarea")[0];if(f)x.responseText=f.value,x.status=Number(f.getAttribute("status"))||x.status,x.statusText=f.getAttribute("statusText")||x.statusText;else if(l){var p=M.getElementsByTagName("pre")[0],h=M.getElementsByTagName("body")[0];p?x.responseText=p.textContent?p.textContent:p.innerText:h&&(x.responseText=h.textContent?h.textContent:h.innerText)}}else"xml"==c&&!x.responseXML&&x.responseText&&(x.responseXML=X(x.responseText));try{E=_(x,c,m)}catch(y){i="parsererror",x.error=r=y||i}}catch(y){a("error caught: ",y),i="error",x.error=r=y||i}x.aborted&&(a("upload aborted"),i=null),x.status&&(i=x.status>=200&&x.status<300||304===x.status?"success":"error"),"success"===i?(m.success&&m.success.call(m.context,E,"success",x),S.resolve(x.responseText,"success",x),d&&e.event.trigger("ajaxSuccess",[x,m])):i&&(void 0===r&&(r=x.statusText),m.error&&m.error.call(m.context,x,i,r),S.reject(x,"error",r),d&&e.event.trigger("ajaxError",[x,m,r])),d&&e.event.trigger("ajaxComplete",[x,m]),d&&!--e.active&&e.event.trigger("ajaxStop"),m.complete&&m.complete.call(m.context,x,i),F=!0,m.timeout&&clearTimeout(j),setTimeout(function(){m.iframeTarget?v.attr("src",m.iframeSrc):v.remove(),x.responseXML=null},100)}}}var c,l,m,d,p,v,g,x,y,b,T,j,w=f[0],S=e.Deferred();if(S.abort=function(e){x.abort(e)},r)for(l=0;l'),v.css({position:"absolute",top:"-1000px",left:"-1000px"})),g=v[0],x={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(t){var r="timeout"===t?"timeout":"aborted";a("aborting upload... "+r),this.aborted=1;try{g.contentWindow.document.execCommand&&g.contentWindow.document.execCommand("Stop")}catch(n){}v.attr("src",m.iframeSrc),x.error=r,m.error&&m.error.call(m.context,x,r,t),d&&e.event.trigger("ajaxError",[x,m,r]),m.complete&&m.complete.call(m.context,x,r)}},d=m.global,d&&0===e.active++&&e.event.trigger("ajaxStart"),d&&e.event.trigger("ajaxSend",[x,m]),m.beforeSend&&m.beforeSend.call(m.context,x,m)===!1)return m.global&&e.active--,S.reject(),S;if(x.aborted)return S.reject(),S;y=w.clk,y&&(b=y.name,b&&!y.disabled&&(m.extraData=m.extraData||{},m.extraData[b]=y.value,"image"==y.type&&(m.extraData[b+".x"]=w.clk_x,m.extraData[b+".y"]=w.clk_y)));var D=1,k=2,A=e("meta[name=csrf-token]").attr("content"),L=e("meta[name=csrf-param]").attr("content");L&&A&&(m.extraData=m.extraData||{},m.extraData[L]=A),m.forceSync?o():setTimeout(o,10);var E,M,F,O=50,X=e.parseXML||function(e,t){return window.ActiveXObject?(t=new ActiveXObject("Microsoft.XMLDOM"),t.async="false",t.loadXML(e)):t=(new DOMParser).parseFromString(e,"text/xml"),t&&t.documentElement&&"parsererror"!=t.documentElement.nodeName?t:null},C=e.parseJSON||function(e){return window.eval("("+e+")")},_=function(t,r,a){var n=t.getResponseHeader("content-type")||"",i="xml"===r||!r&&n.indexOf("xml")>=0,o=i?t.responseXML:t.responseText;return i&&"parsererror"===o.documentElement.nodeName&&e.error&&e.error("parsererror"),a&&a.dataFilter&&(o=a.dataFilter(o,r)),"string"==typeof o&&("json"===r||!r&&n.indexOf("json")>=0?o=C(o):("script"===r||!r&&n.indexOf("javascript")>=0)&&e.globalEval(o)),o};return S}if(!this.length)return a("ajaxSubmit: skipping submit process - no element selected"),this;var u,c,l,f=this;"function"==typeof t?t={success:t}:void 0===t&&(t={}),u=t.type||this.attr2("method"),c=t.url||this.attr2("action"),l="string"==typeof c?e.trim(c):"",l=l||window.location.href||"",l&&(l=(l.match(/^([^#]+)/)||[])[1]),t=e.extend(!0,{url:l,success:e.ajaxSettings.success,type:u||e.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},t);var m={};if(this.trigger("form-pre-serialize",[this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(t.beforeSerialize&&t.beforeSerialize(this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSerialize callback"),this;var d=t.traditional;void 0===d&&(d=e.ajaxSettings.traditional);var p,h=[],v=this.formToArray(t.semantic,h);if(t.data&&(t.extraData=t.data,p=e.param(t.data,d)),t.beforeSubmit&&t.beforeSubmit(v,this,t)===!1)return a("ajaxSubmit: submit aborted via beforeSubmit callback"),this;if(this.trigger("form-submit-validate",[v,this,t,m]),m.veto)return a("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;var g=e.param(v,d);p&&(g=g?g+"&"+p:p),"GET"==t.type.toUpperCase()?(t.url+=(t.url.indexOf("?")>=0?"&":"?")+g,t.data=null):t.data=g;var x=[];if(t.resetForm&&x.push(function(){f.resetForm()}),t.clearForm&&x.push(function(){f.clearForm(t.includeHidden)}),!t.dataType&&t.target){var y=t.success||function(){};x.push(function(r){var a=t.replaceTarget?"replaceWith":"html";e(t.target)[a](r).each(y,arguments)})}else t.success&&x.push(t.success);if(t.success=function(e,r,a){for(var n=t.context||this,i=0,o=x.length;o>i;i++)x[i].apply(n,[e,r,a||f,f])},t.error){var b=t.error;t.error=function(e,r,a){var n=t.context||this;b.apply(n,[e,r,a,f])}}if(t.complete){var T=t.complete;t.complete=function(e,r){var a=t.context||this;T.apply(a,[e,r,f])}}var j=e("input[type=file]:enabled",this).filter(function(){return""!==e(this).val()}),w=j.length>0,S="multipart/form-data",D=f.attr("enctype")==S||f.attr("encoding")==S,k=n.fileapi&&n.formdata;a("fileAPI :"+k);var A,L=(w||D)&&!k;t.iframe!==!1&&(t.iframe||L)?t.closeKeepAlive?e.get(t.closeKeepAlive,function(){A=s(v)}):A=s(v):A=(w||D)&&k?o(v):e.ajax(t),f.removeData("jqxhr").data("jqxhr",A);for(var E=0;Ec;c++)if(d=u[c],f=d.name,f&&!d.disabled)if(t&&o.clk&&"image"==d.type)o.clk==d&&(a.push({name:f,value:e(d).val(),type:d.type}),a.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}));else if(m=e.fieldValue(d,!0),m&&m.constructor==Array)for(r&&r.push(d),l=0,h=m.length;h>l;l++)a.push({name:f,value:m[l]});else if(n.fileapi&&"file"==d.type){r&&r.push(d);var v=d.files;if(v.length)for(l=0;li;i++)r.push({name:a,value:n[i]});else null!==n&&"undefined"!=typeof n&&r.push({name:this.name,value:n})}}),e.param(r)},e.fn.fieldValue=function(t){for(var r=[],a=0,n=this.length;n>a;a++){var i=this[a],o=e.fieldValue(i,t);null===o||"undefined"==typeof o||o.constructor==Array&&!o.length||(o.constructor==Array?e.merge(r,o):r.push(o))}return r},e.fieldValue=function(t,r){var a=t.name,n=t.type,i=t.tagName.toLowerCase();if(void 0===r&&(r=!0),r&&(!a||t.disabled||"reset"==n||"button"==n||("checkbox"==n||"radio"==n)&&!t.checked||("submit"==n||"image"==n)&&t.form&&t.form.clk!=t||"select"==i&&-1==t.selectedIndex))return null;if("select"==i){var o=t.selectedIndex;if(0>o)return null;for(var s=[],u=t.options,c="select-one"==n,l=c?o+1:u.length,f=c?o:0;l>f;f++){var m=u[f];if(m.selected){var d=m.value;if(d||(d=m.attributes&&m.attributes.value&&!m.attributes.value.specified?m.text:m.value),c)return d;s.push(d)}}return s}return e(t).val()},e.fn.clearForm=function(t){return this.each(function(){e("input,select,textarea",this).clearFields(t)})},e.fn.clearFields=e.fn.clearInputs=function(t){var r=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var a=this.type,n=this.tagName.toLowerCase();r.test(a)||"textarea"==n?this.value="":"checkbox"==a||"radio"==a?this.checked=!1:"select"==n?this.selectedIndex=-1:"file"==a?/MSIE/.test(navigator.userAgent)?e(this).replaceWith(e(this).clone(!0)):e(this).val(""):t&&(t===!0&&/hidden/.test(a)||"string"==typeof t&&e(this).is(t))&&(this.value="")})},e.fn.resetForm=function(){return this.each(function(){("function"==typeof this.reset||"object"==typeof this.reset&&!this.reset.nodeType)&&this.reset()})},e.fn.enable=function(e){return void 0===e&&(e=!0),this.each(function(){this.disabled=!e})},e.fn.selected=function(t){return void 0===t&&(t=!0),this.each(function(){var r=this.type;if("checkbox"==r||"radio"==r)this.checked=t;else if("option"==this.tagName.toLowerCase()){var a=e(this).parent("select");t&&a[0]&&"select-one"==a[0].type&&a.find("option").selected(!1),this.selected=t}})},e.fn.ajaxSubmit.debug=!1}); \ No newline at end of file diff --git a/contactsnew/lang/index.php b/contactsnew/lang/index.php new file mode 100644 index 0000000..9c20174 --- /dev/null +++ b/contactsnew/lang/index.php @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/contactsnew/lang/ru.txt b/contactsnew/lang/ru.txt new file mode 100644 index 0000000..3eb87da --- /dev/null +++ b/contactsnew/lang/ru.txt @@ -0,0 +1,166 @@ +contacts = "Контакты New" +mod_info = "В данном разделе приведен список всех контактных форм. Вы можете, добавить новую форму или отредактировать существующую." +forms = "Список форм" +form = "Форма" +noforms = "В модуле пока нет ни одной контактной формы" +form_new = "Создать форму" +form_deleting = "Вы уверены, что хотите удалить форму?" + +form_creating = "Создание новой формы" +form_notfound = "указанная форма не найдена" +form_editing = "Редактирование формы" +main_sets = "Основные параметры" +title = "Название" +alias = "Алиас" +protection = "Защита от повторной отправки" +protect_i = "Рекомендуется включать для форм без Ajax.<br/><br/>Если защита включена, на финишной странице (после успешной отправки формы) при обновлении страницы пользователь не увидит сообщения "Подтвердите повторную отправку данных...". Вместо этого загрузится заново чистая форма." +demo = "Создать пример формы" +demo_noajax = "без Ajax" +demo_ajax = "Ajax, сервер возвращает код формы" +demo_ajax_o = "Ajax, сервер возвращает результат валидации" +alias_i = "Опционально. Алиас формы позволяет использовать легко запоминающийся тег [mod_contact:alias] вместо [mod_contact:id]. Алиас не должен являться числом, может содержать только цифры, латинские буквы, дефис, подчёркивание, иметь длину не более 20 символов и быть уникальным в пределах модуля" +alias_accept = "Этот алиас можно использовать" +alias_er_syn = "Неверный алиас!
Алиас не должен являться числом, может содержать только цифры, латинские буквы, дефис, подчёркивание и иметь длину не более 20 символов" +alias_er_exists = "Неверный алиас!
Данный алиас уже привязан к другой контактной форме" +recs = "Получатели" +name = "Имя" +fields_sets = "Настройки полей" +active_i = "Активировать поле (если чекбокс пустой, тег в шаблоне будет заменён на пустую строку)" +type = "Тип" +doc = "Документ" +multidoc = "Документ (multi)" +other_input = "Другой input" +other_input_i = "Аттрибут type" +pattern_i = "Шаблон для preg_match
Пример: /^[A-Za-z0-9]+$/ie

Либо фильтр для filter_var
Пример: FILTER_VALIDATE_EMAIL" +pattern = "Валидация" +defaultval = "По умолчанию" +sets = "Параметры" +attributes = "Аттрибуты тега поля" +field_add = "Добавить поле" +form_tpl = "Шаблон формы" +mail_tpl = "Шаблон письма" +finish_tpl = "Шаблон страницы после отправки формы" +conditions = "Условия" +rubheader = "Скрипты и стили, необходимые для оформления и функционирования формы" +rubheader_info = "Избегайте дублирования скриптов в модуле и шаблоне" +tag = "Тег" +field_creating = "Добавление поля..." +field_new_error = "Укажите название поля!" +type_i = "Для input в аттрибутах можно указать свой type (по умолчанию подставится text)" +fld_tpl_toggle = "Показать/свернуть шаблон вывода поля" +field_tpl = "Шаблон поля" +fld_del = "Вы уверены, что хотите удалить это поле?" +fld_deleting = "Удаление поля..." +required = "Обязательное поле" +setting_empty = "Сначала настройте опции для выбора (слева)" +yes = "да" +no = "нет" +fld_i = "Поле работает только если его тег вставлен в шаблон и слева стоит галочка активации" +copy_fld_i = "Отправка копии будет выполнена, даже если в значении по умолчанию стоит галка, а тег в шаблон не вставлен / поле не активировано" +select_req_i = "Селект будет считаться не заполненным, если выбран первый вариант" +file_size = "Макс. размер, мб" +file_size2 = "Ограничение размера файла, мб" + +create = "Создать" +edit = "Редактировать" +copy = "Копировать" +delete = "Удалить" +actions = "Действия" +saved = "Сохранено" +notsaved = "Во время сохранения произошла ошибка" +created = "Форма успешно создана" +copied = "Форма успешно скопирована и сохранена
Отредактируйте название и алиас" +deleting = "Удаление..." +add_refresh = "Добавить и обновить" +save = "Сохранить" +return_to_forms = "Вернуться к списку контактных форм" +refresh = "Обновить" +mail_set = "Настройки письма" +format = "Формат" +text = "Текст" +from_email = "Email отправителя" +from_name = "Имя отправителя" +recs_main = "Главные получатели" +recs_main_i = "Эти адресаты получат письмо в любом случае" +subject_tpl = "Шаблон темы" + +email_accept = "Правильный Email" +email_error = "Неверный синтаксис Email-а!" + +tag_fld = "Тег поля, поле подставляется с использованием своего шаблона" +tag_fld_mail = "Значение поля, введённое пользователем" +tag_fld_tpl = "Тег поля, поле подставляется с подстановкой аттрибутов" +tag_attr = "Вставить основные аттрибуты" +tag_id = "Id поля" +tag_title = "Тег названия поля" +tag_valid = "Выведет контент, если поле соответствует заданному шаблону" +tag_invalid = "Выведет контент, если поле не соответствует заданному шаблону" +tag_nempty = "Выведет контент, если поле помечено как обязательное и пользователь ввёл данные" +tag_empty = "Выведет контент, если поле помечено как обязательное и пользователь не ввёл данные" +tag_path = "Корневой путь установки" +tag_media = "Путь до папки с шаблоном

Пример: [tag:mediapath]images/logo.gif" +tag_css = "Сжимает несколько css-файлов в один. Возвращает путь.
FFF - имена файлов через запятую
P - путь к папке с файлами, не обязательно. По умолчанию - [tag:mediapath]css/

Пример: href="[tag:css:reset.css,style.css]"" +tag_js = "Сжимает несколько js-файлов в один. Возвращает путь.
FFF - имена файлов через запятую
P - путь к папке с файлами, не обязательно. По умолчанию - [tag:mediapath]js/

Пример: href="[tag:js:common.js,main.js]"" +tag_formtitle = "Название формы" +tag_formalias = "Алиас формы (или id, если алиас не назначен)" +tag_url = "URL текущей страницы" +tag_docid = "ID текущего документа" +tag_hide = "Тег, позволяющий скрыть контент для определенных групп пользователей

Х - номер группы
TEXT - текст, если доступ запрещён

Пример: [tag:hide:2:Эта форма не для вас!][/tag:hide]" +tag_uemail = "Email пользователя (на основе данных из профиля, а не формы!)" +tag_uname = "И. Фамилия пользователя (на основе данных из профиля)" +tag_ufname = "Имя пользователя (на основе данных из профиля)" +tag_ulname = "Фамилия пользователя (на основе данных из профиля)" +tag_ulogin = "Логин пользователя (на основе данных из профиля)" +tag_if_fld = "Условие на значение поля. В теге используйте стандартные конструкции сравнения PHP/JS

Пример:
[tag:if_fld:15 == '1']
...
[tag:elseif_fld:15 > '2']
...
[tag:else_fld]
...
[/tag:if_fld]" +tag_f_valid = "Выведет контент, если все поля формы прошли валидацию" +tag_f_invalid = "Выведет контент, если хотя бы одно поле формы не прошло валидацию" +tag_easymail = "Быстро генерирует список всех значений полей, участвующих в шаблоне формы (вместо того, чтобы прописывать все теги вручную)" +tag_if_user = "Выведет контент в письме пользователю, заполнившему форму" +tag_if_admin = "Выведет контент в письме получателям-админам ("главным получателям" или адресату из поля "получатель на выбор")" +tag_fld_subject = "Значение поля Тема" +tag_fld_email = "Значение поля Email" +tag_sitename = "Название сайта" +tag_sitehost = "Адрес сайта" +info_php_tags = "Доступен php и теги" + +code = "Исполняемый код" +code_info = "Данные формы (валидация, шаблоны, получатели и т.д.) хранятся в переменной класса $this->form." +code_onsubmit = "Код, исполняемый сразу после отправки формы (до валидации)" +code_onvalidate = "Код, исполняемый после валидации формы" +code_onsend = "Код, исполняемый после отправки писем" + +mfld_email = "Email" +mfld_subject = "Тема" +mfld_receivers = "Получатель на выбор" +mfld_captcha = "Капча" +mfld_copy = "Отправка копии" + +tag_mail_empty = "не заполнено" + +history = "История" +date = "Дата" +author = "Автор" +status = "Статус" +stat_new = "Новое" +list_new = "Новых" +stat_viewed = "Просмотрено" +list_viewed = "Просмотренных" +stat_replied = "Отвечено" +list_replied = "Отвеченных" +request = "Обращение" +response = "Ответ" +responses = "Ответы" +write_response = "Написать ответ" +body = "Тело письма" +save_draft = "Сохранить черновик" +send = "Отправить ответ" +return_dialogs = "Вернуться к списку обращений" +profile_look = "Перейти к профилю" +write_email = "Написать письмо" +from = "от" +look = "Посмотреть" +set_replied = "Пометить как отвеченное" +marked_replied = "Было отмечено как отвеченное" +attach = "Вложения" + +respose_sent = "Ответ успешно отправлен" \ No newline at end of file diff --git a/contactsnew/module.php b/contactsnew/module.php new file mode 100644 index 0000000..4941333 --- /dev/null +++ b/contactsnew/module.php @@ -0,0 +1,155 @@ +[mod_contactsnew:XXX], где XXX - это id или алиас формы.'; + $modul['ModuleAutor'] = 'vudaltsov UPD Repellent'; + $modul['ModuleCopyright'] = '© 2007-2016 AVE.CMS Team'; + $modul['ModuleIsFunction'] = 1; + $modul['ModuleAdminEdit'] = 1; + $modul['ModuleFunction'] = 'mod_contactsnew'; + $modul['ModuleTag'] = '[mod_contactsnew:alias/id:email]'; + $modul['ModuleTagLink'] = null; + $modul['ModuleAveTag'] = '#\\\[mod_contactsnew:([A-Za-z0-9_]{1,20})]#'; + $modul['ModulePHPTag'] = ""; +} + +/** + * Тег + */ +function mod_contactsnew($alias_id) +{ + global $AVE_Template; + + require_once(BASE_DIR . '/modules/contactsnew/class.contactsnew.php'); + $contactsnew = new ContactsNew; + $contactsnew->tpl_dir = BASE_DIR . '/modules/contactsnew/templates/'; + + $lang_file = BASE_DIR . '/modules/contactsnew/lang/' . $_SESSION['user_language'] . '.txt'; + $AVE_Template->config_load($lang_file); + + echo $contactsnew->form_display($alias_id); +} + +/** + * AJAX-методы + */ +if (!defined('ACP') && isset($_REQUEST['module']) && $_REQUEST['module'] == 'contactsnew') +{ + global $AVE_Template; + $alias_id = $_REQUEST['alias_id']; + + require_once(BASE_DIR . '/modules/contactsnew/class.contactsnew.php'); + $contactsnew = new ContactsNew; + $contactsnew->tpl_dir = BASE_DIR . '/modules/contactsnew/templates/'; + + $lang_file = BASE_DIR . '/modules/contactsnew/lang/' . $_SESSION['user_language'] . '.txt'; + $AVE_Template->config_load($lang_file); + + switch($_REQUEST['action']) + { + case '': + case 'full': + exit ($contactsnew->form_display($alias_id)); + + case 'validate': + $contactsnew->form_display($alias_id); + exit (json_encode($contactsnew->form['ajax'])); + } +} + +/** + * Админка + */ +if (defined('ACP') && isset($_REQUEST['mod']) && $_REQUEST['mod'] == 'contactsnew' && !empty($_REQUEST['moduleaction'])) +{ + $fid = !empty($_REQUEST['fid']) ? (int)$_REQUEST['fid'] : 0; + + require_once(BASE_DIR . '/modules/contactsnew/class.contactsnew.php'); + $contactsnew = new ContactsNew; + $contactsnew->tpl_dir = BASE_DIR . '/modules/contactsnew/templates/'; + + $lang_file = BASE_DIR . '/modules/contactsnew/lang/' . $_SESSION['admin_language'] . '.txt'; + $AVE_Template->config_load($lang_file); + + // создаём переменные с версией движка + $ave14 = ((float)str_replace(',','.',APP_VERSION) < 1.5); + $AVE_Template->assign('ave14', $ave14); + $AVE_Template->assign('ave15', !$ave14); + + switch($_REQUEST['moduleaction']) + { + case '1': + $contactsnew->forms_list(); + break; + + case 'form_edit': + $response = $contactsnew->form_edit($fid); + break; + + case 'form_save': + $response = $contactsnew->form_save($fid); + // если передан запрос на обновление полей, передаём tpl + if (isset($_REQUEST['fields_reload']) && $_REQUEST['fields_reload'] == 1) + { + exit ($contactsnew->form_fields_fetch()); + } + break; + + case 'form_del': + $contactsnew->form_del($fid); + header('Location: index.php?do=modules&action=modedit&mod=contactsnew&moduleaction=1&cp=' . SESSION); + exit; + + case 'form_copy': + $fid_new = $contactsnew->form_copy($fid); + $_SESSION['module_contactsnew_admin'][$fid_new]['edit_alert'] = array('text' => 'copied', 'theme' => 'accept'); + header('Location: index.php?do=modules&action=modedit&mod=contactsnew&moduleaction=form_edit&fid=' . $fid_new . '&cp=' . SESSION); + exit; + + case 'email_validate': + $response = (int)$contactsnew->_email_validate($_REQUEST['email']); + break; + + case 'alias_validate': + $response = $contactsnew->_alias_validate($_REQUEST['alias'],$fid); + $response = ($response === 'syn') ? 'syn' : (int)$response; + break; + + case 'history_list': + $contactsnew->history_list($fid); + break; + + case 'history_dialog': + $hid = !empty($_REQUEST['hid']) ? (int)$_REQUEST['hid'] : 0; + $contactsnew->history_dialog($hid); + break; + + case 'history_dialog_submit': + $hid = !empty($_REQUEST['hid']) ? (int)$_REQUEST['hid'] : 0; + $contactsnew->history_dialog_submit($hid); + break; + + case 'dialog_status': + $hid = !empty($_REQUEST['hid']) ? (int)$_REQUEST['hid'] : 0; + $contactsnew->dialog_status($hid); + break; + } + if ($_REQUEST['ajax']) exit((string)$response); +} +?> diff --git a/contactsnew/sql.php b/contactsnew/sql.php new file mode 100644 index 0000000..76abc31 --- /dev/null +++ b/contactsnew/sql.php @@ -0,0 +1,133 @@ + \ No newline at end of file diff --git a/contactsnew/templates/dialog.tpl b/contactsnew/templates/dialog.tpl new file mode 100644 index 0000000..4911181 --- /dev/null +++ b/contactsnew/templates/dialog.tpl @@ -0,0 +1,265 @@ + +{if $ave15} +{include file="$codemirror_connect"} +{else} + +{literal} + +{/literal} + + + + + + +{/if} + +{literal} + +{/literal} + + + +
+
{#contacts#}
+
+
+
{#mod_info#}
+
+ + +
+
+
{#history#}: {$subject}
+
+ + + + + + + + + + + {assign var=item value=$dialog.request} + + + + {if $dialog.response} + + + + {foreach from=$dialog.response item=item} + + + + + {/foreach} + {else} + + + + {/if} + +
{#request#}
+ {if $item.user_name} + [{$item.user_name}] {if $item.firstname || $item.lastname}{$item.firstname} {$item.lastname}{/if}
+ {/if} + {$email}
+ {$date|date_format:$TIME_FORMAT|pretty_date} +
+ {if $item.format=='text'} +
{$item.body}
+ {else} + {$item.body} + {/if} +
{if $dialog.response|@count == 1}{#response#}{else}{#responses#}{/if}
+ {if $item.user_name} + [{$item.user_name}] {if $item.firstname || $item.lastname}{$item.firstname} {$item.lastname}{/if}
+ {/if} + {#from#} {$item.from_email} <{$item.from_name|escape}>
+ {$item.date|date_format:$TIME_FORMAT|pretty_date} +
+ {if $item.format=='text'} +
{$item.body}
+ {else} + {$item.body} + {/if} +
+ {if $status!=='replied'}{#set_replied#} + {else} + {#marked_replied#} + {/if} +
+
+ +
+
+
+
{#write_response#}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + {* + + + *} + +
{#from_name#}:
{#from_email#}:
{#mfld_subject#}:
{#format#}: + + + + +
{#body#} + +
+ | OL | UL | LI | P | B | I | H1 | H2 | H3 | H4 | H5 | DIV | A | IMG | SPAN | PRE | BR | TAB | +
+
{#attach#}
+
+   +   + {#return_dialogs#} +
+
+
+ +{literal} + +{/literal} + +{assign var=cdmr_id value=response_body} +{assign var=cdmr_h value=300} +{if $ave15} + {include file="$codemirror_editor" ctrls='response_save();' conn_id="_$cdmr_id" textarea_id=$cdmr_id height=$cdmr_h} +{else} + +{/if} \ No newline at end of file diff --git a/contactsnew/templates/form_edit.tpl b/contactsnew/templates/form_edit.tpl new file mode 100644 index 0000000..4c93927 --- /dev/null +++ b/contactsnew/templates/form_edit.tpl @@ -0,0 +1,801 @@ + +{if $ave15} +{include file="$codemirror_connect"} +{else} + +{literal} + +{/literal} + + + + + + +{/if} + + +{literal} + +{/literal} + + + +
+
{#contacts#}
+
+ +
+
+
+
{#main_sets#}
+ +
+ + + + + + + + + + + + + + + + + + + {if !$fid} + + + + + {/if} + +
{#title#}: + +
+
+ {#alias#} + : +
+
+ + +
+
+ {#protection#} + : +
+
+ +
{#demo#}: + +
+ {if !$fid} +
+ +
+ {/if} +
+ + {if $fid} +
+
+
{#rubheader#}
+
+
+
{#rubheader_info#}
+ + + + + + + + + + + + + + + + + + + + + +
[tag:path] + +
[tag:mediapath]
[tag:css:FFF:P], [tag:js:FFF:P]
HTML tags | OL | UL | LI | P | B | I | H1 | H2 | H3 | H4 | H5 | DIV | A | IMG | SPAN | PRE | BR | TAB |
+
+
+ +
+
+
{#fields_sets#}
+
+
+ {include file=$form_fields_tpl fields=$form.fields} +
+
+ +
+
+
{#form_tpl#}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{#conditions#} | + [tag:if_fld:XXX == '123'][/tag:if_fld] | + [tag:elseif_fld:XXX > 2] | + [tag:else_fld] | +
| + [tag:if_form_valid][/tag:if_form_valid] | + [tag:if_form_invalid][/tag:if_form_invalid] | +
[tag:fld:XXX]
[tag:title:XXX]
[tag:docid]
[tag:document]
[tag:formalias]
[tag:formtitle]
[tag:path]
[tag:mediapath]
[tag:hide:X,X:TEXT][/tag:hide]
[tag:uemail]
[tag:ulogin]
[tag:uname]
[tag:ufname]
[tag:ulname]
[tag:sitename]
[tag:sitehost]
HTML Tags | FORM | OL | UL | LI | P | B | I | H1 | H2 | H3 | H4 | H5 | DIV | A | IMG | SPAN | PRE | BR | TAB |
+ +
+ +
+
+
{#mail_set#}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{#from_name#}: + + +
{#from_email#}: + + +
{#subject_tpl#}: + + +
{#recs_main#} : + {foreach from=$form.mail_set.receivers item=receiver name=receivers} +
+ + + {if $smarty.foreach.receivers.index == 0} + + {else} + + {/if} +
+ {/foreach} +
{#format#}: + + + + +
+
{#mail_tpl#}
+
{#conditions#} | + [tag:if_fld:XXX == '123'][/tag:if_fld] | + [tag:elseif_fld:XXX > 2] | + [tag:else_fld] | +
| + [tag:if_user][/tag:if_user] | + [tag:if_admin][/tag:if_admin] | +
[tag:fld:XXX]
[tag:title:XXX]
[tag:docid]
[tag:document]
[tag:formtitle]
[tag:formalias]
[tag:path]
[tag:easymail]
[tag:uemail]
[tag:ulogin]
[tag:uname]
[tag:ufname]
[tag:ulname]
[tag:sitename]
[tag:sitehost]
HTML Tags | OL | UL | LI | P | B | I | H1 | H2 | H3 | H4 | H5 | DIV | A | IMG | SPAN | PRE | BR | TAB |
+ +
+ +
+
+
{#finish_tpl#}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
[tag:docid]
[tag:document]
[tag:formalias]
[tag:formtitle]
[tag:path]
[tag:mediapath]
[tag:uemail]
[tag:ulogin]
[tag:uname]
[tag:sitename]
[tag:sitehost]
HTML Tags | OL | UL | LI | P | B | I | H1 | H2 | H3 | H4 | H5 | DIV | A | IMG | SPAN | PRE | BR | TAB |
+ +
+ +
+
+
{#code#}
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
{#code_info#}
{#code_onsubmit#}
{#code_onvalidate#}
{#code_onsend#}
+ +
+ {/if} +
+ +{literal} + +{/literal} + + +{foreach from=$codemirror key='cdmr_id' item='cdmr_h'} + {if $ave15} + {include file="$codemirror_editor" ctrls='form_save();' conn_id="_$cdmr_id" textarea_id=$cdmr_id height=$cdmr_h} + {else} + + {/if} +{/foreach} + \ No newline at end of file diff --git a/contactsnew/templates/form_fields.tpl b/contactsnew/templates/form_fields.tpl new file mode 100644 index 0000000..eb8c1b2 --- /dev/null +++ b/contactsnew/templates/form_fields.tpl @@ -0,0 +1,398 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + {foreach from=$fields item=field key=field_id} + + + + + {if $field.main && $field.title != 'subject' && $field.title != 'email'} + + {else} + + + {/if} + + + + + + + + + {/foreach} + + + + + + + + + + + +
ID{#title#}{#type#}{#sets#}
!
{#defaultval#}
+ + +
+ + {if $field.main} + [tag:fld:{$field.title}] + {else} + [tag:fld:{$field.id}] + {/if} +
+
+ {if $field.main} +
+ {$field.title_lang|escape} + + {if $field.title=='copy'}{/if} +
+ {else} + + {/if} +
+ + {if $field.main && $field.title=='receivers'} + {foreach from=$field.setting item=receiver name=receivers} +
+ + + {if $smarty.foreach.receivers.index == 0} + + {else} + + {/if} +
+ {/foreach} + {else} + + {/if} +
+ {if $field.main} + + {else} +
+ + +
+ {/if} +
+ {if $field.type=='input' || $field.type=='textarea'} +
+ + +
+ {elseif $field.type=='select' || $field.type=='multiselect'} + {foreach from=$field.setting item=title name=select} +
+ + {if $smarty.foreach.select.index == 0} + + {else} + + {/if} +
+ {/foreach} + {elseif $field.type=='doc' || $field.type=='multidoc'} + + {elseif $field.type == 'file'} + + {/if} +
+ {if !($field.type == 'doc' || $field.type == 'multidoc' || ($field.main && ($field.title == 'copy' || $field.title == 'receivers')))} + + {if $field.main && $field.title=='captcha'} + + {/if} + {/if} + {if !$field.main && $field.type == 'select'} + + {/if} + + {if $field.main && $field.title=='captcha'} + {elseif $field.type=='input' || $field.type=='textarea'} + + + + {if $ave15} + {include file="$codemirror_editor" ctrls='form_save();' conn_id="_field_defaultval_$field_id" textarea_id="field_defaultval[$field_id]" height=60} + {else} + + {/if} + {elseif ($field.type=='select' || $field.type=='multiselect')} + {if !$field.setting_empty} + + {else} + {#setting_empty#} + {/if} + {elseif $field.type=='checkbox'} + + + {/if} + + + + + {if !$field.main} + + {/if} +
+
+
{#attributes#}
+ +
| + php | + | + [tag:id] | + [tag:title] | + [tag:if_notempty][/tag:if_notempty] | + [tag:if_empty][/tag:if_empty] | +
| + [tag:uemail] | + [tag:uname] | + [tag:ufname] | + [tag:ulname] | + {if $field.type=='input' || $field.type=='textarea' || $field.type=='file'} +
| + [tag:if_valid][/tag:if_valid] | + [tag:if_invalid][/tag:if_invalid] | + {/if} + {if $field.main && $field.title == 'captcha'} +
| + [tag:captcha] | + {/if} +
+
+
+
{#field_tpl#}
+ +
| + php | + [tag:fld] | + [tag:id] | + [tag:title] | + [tag:if_notempty][/tag:if_notempty] | + [tag:if_empty][/tag:if_empty] | +
| + [tag:uemail] | + [tag:uname] | + [tag:ufname] | + [tag:ulname] | + {if $field.type=='input' || $field.type=='textarea' || $field.type=='file'} +
| + [tag:if_valid][/tag:if_valid] | + [tag:if_invalid][/tag:if_invalid] | + {/if} + {if $field.main && $field.title == 'captcha'} +
| + [tag:captcha] | + captcha_img | + {/if} +
+
+
{#field_add#}
+ + + + + + + + +
+ + +{foreach from=$fields item=field key=field_id} + {if $ave15} + {include file="$codemirror_editor" ctrls='form_save();' conn_id="_field_attr_$field_id" textarea_id="field_attr[$field_id]" height=176} + {include file="$codemirror_editor" ctrls='form_save();' conn_id="_field_tpl_$field_id" textarea_id="field_tpl[$field_id]" height=176} + {else} + + {/if} +{/foreach} + + + + + \ No newline at end of file diff --git a/contactsnew/templates/forms.tpl b/contactsnew/templates/forms.tpl new file mode 100644 index 0000000..6865a94 --- /dev/null +++ b/contactsnew/templates/forms.tpl @@ -0,0 +1,98 @@ +{literal} + +{/literal} +
+
{#contacts#}
+
+
+
{#mod_info#}
+
+ +
+
+
{#forms#}
+ +
+ + + + + + + + + + + + + + + + + + + + + + {foreach from=$forms item=form} + + + + + + + + + + + {foreachelse} + + + + {/foreach} + +
ID{#title#}{#tag#}{#history#}{#actions#}
{$form.id} + {$form.title|stripslashes|escape} + + + + + {if $form.history_new > 0}{#list_new#}: {$form.history_new}{else}{#list_new#}: {$form.history_new}{/if}
+ {#list_viewed#}: {$form.history_viewed}
+ {#list_replied#}: {$form.history_replied} +
+ + + + + + + +
+
    +
  • {#noforms#}
  • +
+
+
+{if $page_nav} + +{/if} \ No newline at end of file diff --git a/contactsnew/templates/history.tpl b/contactsnew/templates/history.tpl new file mode 100644 index 0000000..7b73a9f --- /dev/null +++ b/contactsnew/templates/history.tpl @@ -0,0 +1,129 @@ +{literal} + +{/literal} + + + +
+
{#contacts#}
+
+
+
{#mod_info#}
+
+ +
+
+
{#history#}
+
+ + + + + + + + + + + + + + + + + {foreach from=$dialogs item=dialog} + + + + + + + {foreachelse} + + + + {/foreach} + +
{#date#}{#mfld_subject#}{#author#}{#status#}
+ {$dialog.date|date_format:$TIME_FORMAT|pretty_date} + + {$dialog.subject|stripslashes|escape} + + {$dialog.email} + + {if $dialog.status!='replied'} + + {else}{#stat_replied#} + {/if} +
+
    +
  • {#noforms#}
  • +
+
+
+ +{if $page_nav} + +{/if} + +{literal} + +{/literal} \ No newline at end of file diff --git a/contactsnew/templates/index.php b/contactsnew/templates/index.php new file mode 100644 index 0000000..9c20174 --- /dev/null +++ b/contactsnew/templates/index.php @@ -0,0 +1,8 @@ + \ No newline at end of file