PageRenderTime 40ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

/application/maxsite/plugins/forms/index.php

https://github.com/dimmaq/MaxSiteCMSTest
PHP | 421 lines | 267 code | 99 blank | 55 comment | 60 complexity | c633c9ee8cc866630c2ed66bd40f97ac MD5 | raw file
  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * MaxSite CMS
  4. * (c) http://max-3000.com/
  5. * Дополнения: Н. Громов (http://nicothin.ru/)
  6. */
  7. # функция автоподключения плагина
  8. function forms_autoload($args = array())
  9. {
  10. mso_hook_add( 'content', 'forms_content'); # хук на вывод контента
  11. }
  12. #
  13. function forms_content_callback($matches)
  14. {
  15. $text = $matches[1];
  16. $text = str_replace("\r", "", $text);
  17. $text = str_replace('&nbsp;', ' ', $text);
  18. $text = str_replace("\t", ' ', $text);
  19. $text = str_replace('<br />', "<br>", $text);
  20. $text = str_replace('<br>', "\n", $text);
  21. $text = str_replace("\n\n", "\n", $text);
  22. $text = str_replace(' ', ' ', $text);
  23. $text = str_replace(' ', ' ', $text);
  24. $text = str_replace(' ', ' ', $text);
  25. $text = str_replace(' ', ' ', $text);
  26. $text = str_replace("\n ", "\n", $text);
  27. $text = str_replace("\n\n", "\n", $text);
  28. $text = trim($text);
  29. $out = ''; // убиваем исходный текст формы
  30. //$r = preg_match_all('!\[email=(.*?)\]|\[redirect=(.*?)\]\[subject=(.*?)\]|\[field\](.*?)\[\/field\]|\[ushka=(.*?)\]!is', $text, $all);
  31. // на какой email отправляем
  32. $r = preg_match_all('!\[email=(.*?)\]!is', $text, $all);
  33. if ($r)
  34. $email = trim(implode(' ', $all[1]));
  35. else
  36. $email = mso_get_option('admin_email', 'general', 'admin@site.com');
  37. // тема письма
  38. $r = preg_match_all('!\[subject=(.*?)\]!is', $text, $all);
  39. if ($r)
  40. $subject = trim(implode(' ', $all[1]));
  41. else
  42. $subject = tf('Обратная связь');
  43. // куда редиректить после отправки
  44. $r = preg_match_all('!\[redirect=(.*?)\]!is', $text, $all);
  45. if ($r)
  46. $redirect = trim(implode(' ', $all[1]));
  47. else
  48. $redirect = '';
  49. // eirf к форме
  50. $r = preg_match_all('!\[ushka=(.*?)\]!is', $text, $all);
  51. if ($r)
  52. $ushka = trim(implode(' ', $all[1]));
  53. else
  54. $ushka = '';
  55. // отправить копию на ваш email
  56. $r = preg_match_all('!\[nocopy\]!is', $text, $all);
  57. if ($r)
  58. $forms_subscribe = false;
  59. else
  60. $forms_subscribe = true;
  61. // кнопка Сброс формы
  62. $r = preg_match_all('!\[noreset\]!is', $text, $all);
  63. if ($r)
  64. $reset = false;
  65. else
  66. $reset = true;
  67. // pr($all);
  68. // поля формы
  69. $r = preg_match_all('!\[field\](.*?)\[\/field\]!is', $text, $all);
  70. $f = array(); // массив для полей
  71. if ($r)
  72. {
  73. $fields = $all[1];
  74. /*
  75. pr($fields);
  76. pr($email);
  77. pr($redirect);
  78. pr($subject);
  79. pr($ushka);
  80. */
  81. if ($subject)
  82. {
  83. // поле тема письма делаем в виде обязательнного поля select.
  84. // формируем массив для формы
  85. $subject_f['require'] = 1;
  86. $subject_f['type'] = 'select';
  87. $subject_f['description'] = tf('Тема письма');
  88. //$subject_f['tip'] = t('Выберите тему письма');
  89. $subject_f['values'] = $subject;
  90. $subject_f['default'] = '';
  91. // преобразования, чтобы сделать ключ для поля
  92. $f1['subject'] = $subject_f; // у поля тема будет ключ subject
  93. foreach($f as $key=>$val) $f1[$key] = $val;
  94. $f = $f1;
  95. }
  96. $i = 0;
  97. foreach ($fields as $val)
  98. {
  99. $val = trim($val);
  100. if (!$val) continue;
  101. $val = str_replace(' = ', '=', $val);
  102. $val = str_replace('= ', '=', $val);
  103. $val = str_replace(' =', '=', $val);
  104. $val = explode("\n", $val); // разделим на строки
  105. $ar_val = array();
  106. foreach ($val as $pole)
  107. {
  108. $pole = preg_replace('!=!', '_VAL_', $pole, 1);
  109. $ar_val = explode('_VAL_', $pole); // строки разделены = type = select
  110. if ( isset($ar_val[0]) and isset($ar_val[1]))
  111. $f[$i][$ar_val[0]] = $ar_val[1];
  112. }
  113. $i++;
  114. }
  115. if (!$f) return ''; // нет полей - выходим
  116. // теперь по-идее у нас есть вся необходимая информация по полям и по форме
  117. // смотрим есть ли POST. Если есть, то проверяем введенные поля и если они корректные,
  118. // то выполняем отправку почты, выводим сообщение и редиректимся
  119. // если POST нет, то выводим обычную форму
  120. // pr($f);
  121. if ($_POST) $_POST = mso_clean_post(array(
  122. 'forms_antispam1' => 'integer',
  123. 'forms_antispam2' => 'integer',
  124. 'forms_antispam' => 'integer',
  125. 'forms_name' => 'base',
  126. 'forms_email' => 'email',
  127. 'forms_session' => 'base',
  128. ));
  129. if ( $post = mso_check_post(array('forms_session', 'forms_antispam1', 'forms_antispam2', 'forms_antispam',
  130. 'forms_name', 'forms_email', 'forms_submit' )) )
  131. {
  132. mso_checkreferer();
  133. $out .= '<div class="forms-post">';
  134. // верный email?
  135. if (!$ok = mso_valid_email($post['forms_email']))
  136. {
  137. $out .= '<div class="message error small">' . tf('Неверный email!') . '</div>';
  138. }
  139. // антиспам
  140. if ($ok)
  141. {
  142. $antispam1s = (int) $post['forms_antispam1'];
  143. $antispam2s = (int) $post['forms_antispam2'];
  144. $antispam3s = (int) $post['forms_antispam'];
  145. if ( ($antispam1s/984 + $antispam2s/765) != $antispam3s )
  146. { // неверный код
  147. $ok = false;
  148. $out .= '<div class="message error small">' . tf('Неверная сумма антиспама') . '</div>';
  149. }
  150. }
  151. if ($ok) // проверим обязательные поля
  152. {
  153. foreach ($f as $key=>$val)
  154. {
  155. if ( $ok and isset($val['require']) and $val['require'] == 1 ) // поле отмечено как обязательное
  156. {
  157. if (!isset($post['forms_fields'][$key]) or !$post['forms_fields'][$key])
  158. {
  159. $ok = false;
  160. $out .= '<div class="message error small">' . tf('Заполните все необходимые поля!') . '</div>';
  161. }
  162. }
  163. if (!$ok) break;
  164. }
  165. }
  166. // всё ок
  167. if ($ok)
  168. {
  169. //pr($post);
  170. // pr($f);
  171. // pr($redirect);
  172. // pr($email);
  173. // pr($subject);
  174. // формируем письмо и отправляем его
  175. if (!mso_valid_email($email))
  176. $email = mso_get_option('admin_email', 'general', 'admin@site.com'); // куда приходят письма
  177. $message = t('Имя: ') . $post['forms_name'] . "\n";
  178. $message .= t('Email: ') . $post['forms_email'] . "\n";
  179. foreach ($post['forms_fields'] as $key=>$val)
  180. {
  181. //pr($key);
  182. if ($key === 'subject' and $val)
  183. {
  184. $subject = $val;
  185. //pr($subject);
  186. continue;
  187. }
  188. $message .= $f[$key]['description'] . ': ' . $val . "\n\n";
  189. }
  190. if ($_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_REFERER'] and $_SERVER['HTTP_USER_AGENT'])
  191. {
  192. $message .= "\n" . tf('IP-адрес: ') . $_SERVER['REMOTE_ADDR'] . "\n";
  193. $message .= tf('Отправлено со страницы: ') . $_SERVER['HTTP_REFERER'] . "\n";
  194. $message .= tf('Браузер: ') . $_SERVER['HTTP_USER_AGENT'] . "\n";
  195. }
  196. // pr($message);
  197. $form_hide = mso_mail($email, $subject, $message, $post['forms_email']);
  198. if ( $forms_subscribe and isset($post['forms_subscribe']) )
  199. mso_mail($post['forms_email'], tf('Вами отправлено сообщение:') . ' ' . $subject, $message);
  200. $out .= '<div class="message ok small">' . tf('Ваше сообщение отправлено!') . '</div><p>'
  201. . str_replace("\n", '<br>', htmlspecialchars($subject. "\n" . $message))
  202. . '</p>';
  203. if ($redirect) mso_redirect($redirect, true);
  204. }
  205. else // какая-то ошибка, опять отображаем форму
  206. {
  207. $out .= forms_show_form($f, $ushka, $forms_subscribe, $reset, $subject);
  208. }
  209. $out .= '</div>';
  210. $out .= mso_load_jquery('jquery.scrollto.js');
  211. $out .= '<script>$(document).ready(function(){$.scrollTo("div.forms-post", 500);})</script>';
  212. }
  213. else // нет post
  214. {
  215. $out .= forms_show_form($f, $ushka, $forms_subscribe, $reset, $subject);
  216. }
  217. }
  218. return $out;
  219. }
  220. function forms_show_form($f = array(), $ushka = '', $forms_subscribe = true, $reset = true, $subject = '')
  221. {
  222. $out = '';
  223. $antispam1 = rand(1, 10);
  224. $antispam2 = rand(1, 10);
  225. $id = 1; // счетчик для id label
  226. if ($subject)
  227. {
  228. // поле тема письма делаем в виде обязательнного поля select.
  229. // формируем массив для формы
  230. $subject_f['require'] = 1;
  231. $subject_f['type'] = 'select';
  232. $subject_f['description'] = tf('Тема письма');
  233. //$subject_f['tip'] = t('Выберите тему письма');
  234. $subject_f['values'] = $subject;
  235. $subject_f['default'] = '';
  236. // преобразования, чтобы сделать ключ для поля
  237. $f1['subject'] = $subject_f; // у поля тема будет ключ subject
  238. foreach($f as $key=>$val) $f1[$key] = $val;
  239. $f = $f1;
  240. }
  241. $out .= NR . '<div class="forms"><form method="post" class="plugin_forms fform">' . mso_form_session('forms_session');
  242. $out .= '<input type="hidden" name="forms_antispam1" value="' . $antispam1 * 984 . '">';
  243. $out .= '<input type="hidden" name="forms_antispam2" value="' . $antispam2 * 765 . '">';
  244. // обязательные поля
  245. $out .= '<p><label class="ffirst ftitle" title="' . tf('Обязательное поле') . '" for="id-' . ++$id . '">' . t('Ваше имя*') . '</label><span><input name="forms_name" type="text" value="" placeholder="' . t('Ваше имя') . '" required id="id-' . $id . '"></span></p>';
  246. $out .= '<p><label class="ffirst ftitle" title="' . tf('Обязательное поле') . '" for="id-' . ++$id . '">' . t('Ваш email*') . '</label><span><input name="forms_email" type="email" value="" placeholder="' . t('Ваш email') . '" required id="id-' . $id . '"></span></p>';
  247. // тут указанные поля в $f
  248. // pr($f);
  249. foreach ($f as $key=>$val)
  250. {
  251. if (!isset($val['description'])) continue;
  252. if (!isset($val['type'])) continue;
  253. $val['type'] = trim($val['type']);
  254. $val['description'] = trim($val['description']);
  255. if (isset($val['require']) and trim($val['require']) == 1)
  256. {
  257. $require = '*';
  258. $require_title = ' title="' . tf('Обязательное поле') . '"';
  259. $required = ' required';
  260. }
  261. else
  262. {
  263. $require = '';
  264. $require_title = '';
  265. $required = '';
  266. }
  267. if (isset($val['attr']) and trim($val['attr'])) $attr = ' ' . trim($val['attr']);
  268. else $attr = '';
  269. if (isset($val['value']) and trim($val['value'])) $pole_value = htmlspecialchars(tf(trim($val['value'])));
  270. else $pole_value = '';
  271. if (isset($val['placeholder']) and trim($val['placeholder'])) $placeholder = ' placeholder="' . htmlspecialchars(tf(trim($val['placeholder']))) . '"';
  272. else $placeholder = '';
  273. $description = t(trim($val['description']));
  274. if (isset($val['tip']) and trim($val['tip']) ) $tip = NR . '<p class="nop"><span class="ffirst"></span><span class="fhint">'. trim($val['tip']) . '</span></p>';
  275. else $tip = '';
  276. if ($val['type'] == 'text') #####
  277. {
  278. //type_text - type для input HTML5
  279. if (isset($val['type_text']) and trim($val['type_text'])) $type_text = htmlspecialchars(trim($val['type_text']));
  280. else $type_text = 'text';
  281. $out .= NR . '<p><label class="ffirst ftitle" for="id-' . ++$id . '"' . $require_title . '>' . $description . $require . '</label><span><input name="forms_fields[' . $key . ']" type="' . $type_text . '" value="' . $pole_value . '" id="id-' . $id . '"' . $placeholder . $required . $attr . '></span></p>' . $tip;
  282. }
  283. elseif ($val['type'] == 'select') #####
  284. {
  285. if (!isset($val['default'])) continue;
  286. if (!isset($val['values'])) continue;
  287. $out .= NR . '<p><label class="ffirst ftitle" for="id-' . ++$id . '"' . $require_title . '>' . $description . $require . '</label><span><select name="forms_fields[' . $key . ']" id="id-' . $id . '"' . $attr . '>';
  288. $default = trim($val['default']);
  289. $values = explode('#', $val['values']);
  290. foreach ($values as $value)
  291. {
  292. $value = trim($value);
  293. if ($value == $default) $checked = ' selected="selected"';
  294. else $checked = '';
  295. $out .= '<option' . $checked . '>' . htmlspecialchars(tf($value)) . '</option>';
  296. }
  297. $out .= '</select></span></p>' . $tip;
  298. }
  299. elseif ($val['type'] == 'textarea') #####
  300. {
  301. $out .= NR . '<p><label class="ffirst ftitle ftop" for="id-' . ++$id . '"' . $require_title . '>' . $description . $require . '</label><span><textarea name="forms_fields[' . $key . ']" id="id-' . $id . '"' . $placeholder . $required. $attr . '>' . $pole_value . '</textarea></span></p>' . $tip;
  302. }
  303. }
  304. // обязательные поля антиспама и отправка и ресет
  305. $out .= NR . '<p><label class="ffirst ftitle" for="id-' . ++$id . '">' . $antispam1 . ' + ' . $antispam2 . ' =</label>';
  306. $out .= '<span><input name="forms_antispam" type="text" required maxlength="3" value="" placeholder="' . t('Укажите свой ответ') . '" id="id-' . $id . '"></span><p>';
  307. if ($forms_subscribe)
  308. $out .= NR . '<p><span class="ffirst"></span><label><input name="forms_subscribe" value="" type="checkbox" class="forms_checkbox"> ' . tf('Отправить копию письма на ваш e-mail') . '</label></p>';
  309. $out .= NR . '<p><span class="ffirst"></span><span class="submit"><button name="forms_submit" type="submit" class="forms_submit">' . tf('Отправить') . '</button>';
  310. if ($reset) $out .= ' <button name="forms_clear" type="reset" class="forms_reset">' . tf('Очистить форму') . '</button>';
  311. $out .= '</span></p>';
  312. if (function_exists('ushka')) $out .= ushka($ushka);
  313. $out .= '</form></div>' . NR;
  314. return $out;
  315. }
  316. # функции плагина
  317. function forms_content($text = '')
  318. {
  319. if (strpos($text, '[form]') !== false) $text = preg_replace_callback('!\[form\](.*?)\[/form\]!is', 'forms_content_callback', $text );
  320. return $text;
  321. }
  322. # end file