PageRenderTime 30ms CodeModel.GetById 34ms RepoModel.GetById 4ms app.codeStats 0ms

/ww.plugins/forms/frontend/validate-and-send.php

http://kv-webme.googlecode.com/
PHP | 468 lines | 372 code | 19 blank | 77 comment | 51 complexity | 4092481a20bf3618920dad9cede1f422 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, BSD-3-Clause, BSD-2-Clause, Apache-2.0, MIT, LGPL-2.1
  1. <?php
  2. /**
  3. * scripts for validating and sending forms
  4. *
  5. * PHP Version 5
  6. *
  7. * @category None
  8. * @package None
  9. * @subpackage None
  10. * @author Kae Verens <kae@kvsites.ie>
  11. * @license GPL Version 2
  12. * @link www.kvweb.me
  13. */
  14. if (!function_exists('mime_content_type')) {
  15. /**
  16. * create function mime_content_type if it's not already there
  17. *
  18. * @param string $filename the filename to test
  19. *
  20. * @return string the mime type
  21. */
  22. function mime_content_type($filename) {
  23. $mime_types = array(
  24. 'txt' => 'text/plain',
  25. 'htm' => 'text/html',
  26. 'html' => 'text/html',
  27. 'php' => 'text/html',
  28. 'css' => 'text/css',
  29. 'js' => 'application/javascript',
  30. 'json' => 'application/json',
  31. 'xml' => 'application/xml',
  32. 'swf' => 'application/x-shockwave-flash',
  33. 'flv' => 'video/x-flv',
  34. // images
  35. 'png' => 'image/png',
  36. 'jpe' => 'image/jpeg',
  37. 'jpeg' => 'image/jpeg',
  38. 'jpg' => 'image/jpeg',
  39. 'gif' => 'image/gif',
  40. 'bmp' => 'image/bmp',
  41. 'ico' => 'image/vnd.microsoft.icon',
  42. 'tiff' => 'image/tiff',
  43. 'tif' => 'image/tiff',
  44. 'svg' => 'image/svg+xml',
  45. 'svgz' => 'image/svg+xml',
  46. // archives
  47. 'zip' => 'application/zip',
  48. 'rar' => 'application/x-rar-compressed',
  49. 'exe' => 'application/x-msdownload',
  50. 'msi' => 'application/x-msdownload',
  51. 'cab' => 'application/vnd.ms-cab-compressed',
  52. // audio/video
  53. 'mp3' => 'audio/mpeg',
  54. 'qt' => 'video/quicktime',
  55. 'mov' => 'video/quicktime',
  56. // adobe
  57. 'pdf' => 'application/pdf',
  58. 'psd' => 'image/vnd.adobe.photoshop',
  59. 'ai' => 'application/postscript',
  60. 'eps' => 'application/postscript',
  61. 'ps' => 'application/postscript',
  62. // ms office
  63. 'doc' => 'application/msword',
  64. 'rtf' => 'application/rtf',
  65. 'xls' => 'application/vnd.ms-excel',
  66. 'ppt' => 'application/vnd.ms-powerpoint',
  67. // open office
  68. 'odt' => 'application/vnd.oasis.opendocument.text',
  69. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  70. );
  71. $ext = strtolower(array_pop(explode('.', $filename)));
  72. if (array_key_exists($ext, $mime_types)) {
  73. return $mime_types[$ext];
  74. }
  75. elseif (function_exists('finfo_open')) {
  76. $finfo = finfo_open(FILEINFO_MIME);
  77. $mimetype = finfo_file($finfo, $filename);
  78. finfo_close($finfo);
  79. return $mimetype;
  80. }
  81. else {
  82. return 'application/octet-stream';
  83. }
  84. }
  85. }
  86. // { Form_readonly
  87. /**
  88. * get a readonly version of the form (for sending as email)
  89. *
  90. * @param array $page_id page db row
  91. * @param array &$vars page meta data
  92. * @param array &$form_fields array of fields
  93. *
  94. * @return HTML of the form
  95. */
  96. function Form_readonly($page_id, &$vars, &$form_fields) {
  97. if (!isset($_SESSION['forms'])) {
  98. $_SESSION['forms']=array();
  99. }
  100. $c='';
  101. // { set up delimiters
  102. $vals_wrapper_start='<table>';
  103. $vals_field_start='<tr><th>';
  104. $vals_field_middle='</th><td>';
  105. $vals_field_end='</td></tr>';
  106. $vals_2col_start='<tr><td colspan="2">';
  107. $vals_2col_end='</td></tr>';
  108. $vals_wrapper_end='</table>';
  109. // }
  110. if (@$vars['forms_template'] && @strpos($vars['forms_template'], '{{')===false) {
  111. @$vars['forms_template']='';
  112. } // }}
  113. if (!@$vars['forms_template']||@$vars['forms_template']=='&nbsp;') {
  114. $c.='<div>'.$vals_wrapper_start;
  115. }
  116. $required=array();
  117. $cnt=0;
  118. foreach ($form_fields as $r2) {
  119. $name=preg_replace('/[^a-zA-Z0-9_]/', '', $r2['name']);
  120. $class='';
  121. if ($r2['isrequired']) {
  122. $required[]=$name.','.$r2['type'];
  123. $class=' required';
  124. }
  125. if (isset($_REQUEST[$name])) {
  126. $_SESSION['forms'][$name]=$_REQUEST[$name];
  127. }
  128. $val=Form_valueDefault($name);
  129. if (!isset($_REQUEST[$name])) {
  130. $_REQUEST[$name]='';
  131. }
  132. switch ($r2['type']) {
  133. case 'ccdate': // {
  134. if ($_REQUEST[$name]=='') {
  135. $_REQUEST[$name]=date('Y-m');
  136. }
  137. $d=preg_replace(
  138. '#.* ([a-zA-Z]*, [0-9]+)#',
  139. "$1",
  140. Core_dateM2H($_REQUEST[$name])
  141. );
  142. break; // }
  143. case 'date': // {
  144. if ($_REQUEST[$name]=='') {
  145. $_REQUEST[$name]=date('Y-m-d');
  146. }
  147. $d=Core_dateM2H($_REQUEST[$name]);
  148. break; // }
  149. case 'file': // {
  150. $d=__('If there are any files, they are attached to this email');
  151. break; // }
  152. case 'hidden': // {
  153. $d=htmlspecialchars($r2['extra']);
  154. break; // }
  155. case 'html-block':
  156. case 'page-next': case 'page-previous': case 'page-break': // {
  157. $d='';
  158. break; // }
  159. default: // { # input boxes, and anything which was not handled already
  160. $d=nl2br(htmlspecialchars($_REQUEST[$name]));
  161. // }
  162. }
  163. if (@$vars['forms_template']&&@$vars['forms_template']!='&nbsp;') {
  164. @$vars['forms_template']=str_replace(
  165. '{{$'.$cnt.'}}',
  166. $d,
  167. @$vars['forms_template']
  168. );
  169. @$vars['forms_template']=str_replace(
  170. '{{$'.htmlspecialchars($r2['name']).'}}',
  171. $d,
  172. $vars['forms_template']
  173. );
  174. }
  175. elseif ($d!='') {
  176. $c.=$vals_field_start.htmlspecialchars($r2['name']);
  177. $c.=$vals_field_middle.$d.$vals_field_end;
  178. }
  179. $cnt++;
  180. }
  181. if (@$vars['forms_template']&&@$vars['forms_template']!='&nbsp;') {
  182. $c.=$vars['forms_template'];
  183. }
  184. else {
  185. $c.=$vals_2col_start;
  186. }
  187. return $c;
  188. }
  189. // }
  190. // { Form_saveValues
  191. /**
  192. * save submitted form values
  193. *
  194. * @param integer $formid ID of the form being saved
  195. * @param array &$form_fields array of fields
  196. *
  197. * @return void
  198. */
  199. function Form_saveValues($formid, &$form_fields) {
  200. dbQuery(
  201. "insert into forms_saved (forms_id,date_created) values($formid,now())"
  202. );
  203. $id=dbLastInsertId();
  204. foreach ($form_fields as $r) {
  205. $name=preg_replace('/[^a-zA-Z0-9_]/', '', $r['name']);
  206. if (isset($_REQUEST[$name])) {
  207. $val=addslashes($_REQUEST[$name]);
  208. }
  209. else {
  210. $val='';
  211. }
  212. $key=addslashes($r['name']);
  213. dbQuery(
  214. 'insert into forms_saved_values (forms_saved_id,name,value)'
  215. ." values($id,'$key','$val')"
  216. );
  217. }
  218. }
  219. // }
  220. // { Form_send
  221. /**
  222. * sends a form, or displays the form instead with errors on top
  223. *
  224. * @param array $page page db row
  225. * @param array $vars page meta data
  226. * @param array $form_fields array of fields
  227. *
  228. * @return HTML of either the result, or the form with errors on top
  229. */
  230. function Form_send($page, $vars, $form_fields) {
  231. $c='';
  232. $plaintext='';
  233. $values=array();
  234. $email='';
  235. foreach ($form_fields as $r2) {
  236. $name=preg_replace('/[^a-zA-Z0-9_]/', '', $r2['name']);
  237. $separator="\n".str_repeat('-', 80)."\n";
  238. $val='';
  239. switch ($r2['type']) {
  240. case 'checkbox': // {
  241. $val=@$_REQUEST[$name];
  242. $values[$r2['name']]=($val=='on')?'yes':'no';
  243. if ($val=='on') {
  244. $plaintext.='selected option: '
  245. .htmlspecialchars($r2['name']).$separator;
  246. }
  247. break; // }
  248. case 'date':case 'ccdate': // {
  249. $val=Core_dateM2H(@$_REQUEST[$name]);
  250. if ($r2['type']=='ccdate') {
  251. $val=preg_replace('#.* ([a-zA-Z]*, [0-9]+)#', "$1", $val);
  252. }
  253. $values[$r2['name']]=$val;
  254. $plaintext.=htmlspecialchars($r2['name'])."\n"
  255. .htmlspecialchars($val).$separator;
  256. break; // }
  257. case 'email': // {
  258. $val=@$_REQUEST[$name];
  259. $values[$r2['name']]=$val;
  260. $plaintext.=htmlspecialchars($r2['name'])."\n"
  261. .htmlspecialchars($val).$separator;
  262. $email=$val;
  263. break; // }
  264. case 'file': // { build $files array which emulates the $_FILES array
  265. // { first remove old uploads
  266. $dir=USERBASE.'/f/.files/forms/';
  267. if (!is_dir($dir)) {
  268. break;
  269. }
  270. $fs=new DirectoryIterator($dir);
  271. $time=time();
  272. foreach ($fs as $f) {
  273. if ($f->isDot()) {
  274. continue;
  275. }
  276. if ($f->isDir()) {
  277. $diff=$time-$f->getMTime();
  278. if ($diff>600) { // file is older than 10 minutes
  279. CoreDirectory::delete($f->getPathname());
  280. }
  281. }
  282. }
  283. // }
  284. $session_id=session_id();
  285. $dir.=$session_id;
  286. if (!is_dir($dir)) {
  287. break;
  288. }
  289. $_FILES=array();
  290. $uploads=new DirectoryIterator($dir);
  291. foreach ($uploads as $upload) {
  292. if ($upload->isDot()||$upload->isDir()) {
  293. continue;
  294. }
  295. array_push(
  296. $_FILES,
  297. array(
  298. 'name'=>$upload->getFileName(),
  299. 'type'=>mime_content_type($upload->getPathname()),
  300. 'tmp_name'=>$upload->getPathname(),
  301. 'error'=>0,
  302. 'size'=>$upload->getSize()
  303. )
  304. );
  305. }
  306. break; // }
  307. case 'html-block': case 'next-page-link': case 'previous-page-link':
  308. case 'page-break': // { not inputs - don't add them
  309. break; // }
  310. default: // {
  311. $val=@$_REQUEST[$name];
  312. $values[$r2['name']]=$val;
  313. $val=nl2br($val);
  314. $plaintext.=htmlspecialchars($r2['name'])."\n"
  315. .htmlspecialchars($val).$separator;
  316. // }
  317. }
  318. }
  319. $from_field=preg_replace('/[^a-zA-Z]/', '', $vars['forms_replyto']);
  320. $from=isset($_REQUEST[$from_field])?$_REQUEST[$from_field]:'';
  321. if (@$vars['forms_create_user']) {
  322. $id=dbOne(
  323. 'select id from user_accounts where email="'.addslashes($email).'"',
  324. 'id'
  325. );
  326. if (!$id) {
  327. dbQuery(
  328. 'insert into user_accounts set email="'.addslashes($email).'",'
  329. .'extras="'.addslashes(json_encode($values)).'"'
  330. );
  331. $id=dbLastInsertId();
  332. if (isset($_FILES) && count($_FILES)) {
  333. @mkdir(USERBASE.'/f/user-files');
  334. @mkdir(USERBASE.'/f/user-files/'.$id);
  335. foreach ($_FILES as $file) {
  336. copy(
  337. $file['tmp_name'],
  338. USERBASE.'/f/user-files/'.$id.'/'.$file['name']
  339. );
  340. }
  341. }
  342. }
  343. }
  344. if ($vars['forms_send_as_email']) {
  345. $form=Form_readonly($page['id'], $vars, $form_fields);
  346. $to=$vars['forms_recipient'];
  347. $form=str_replace(
  348. array(
  349. '<input type="submit" value="'.__('Submit Form').'" />',
  350. '<form action="'.$_SERVER['REQUEST_URI'].'" method="post" '
  351. .'class="ww_form" enctype="multipart/form-data">',
  352. '</form>'
  353. ),
  354. '',
  355. $form
  356. );
  357. cmsMail(
  358. $to,
  359. $from,
  360. $_SERVER['HTTP_HOST'].' '.__FromJson($page['name']),
  361. '<html><head></head><body>'.$form.'</body></html>',
  362. $_FILES
  363. );
  364. if (is_dir(USERBASE.'/f/.files/forms/'.session_id())) { // remove uploaded files
  365. CoreDirectory::delete(USERBASE.'/f/.files/forms/'.session_id());
  366. }
  367. }
  368. if ($vars['forms_record_in_db']) {
  369. Form_saveValues($page['id'], $form_fields);
  370. }
  371. $c.='<div id="thankyoumessage">'.$vars['forms_successmsg'].'</div>';
  372. return $c;
  373. }
  374. // }
  375. // { Form_validate
  376. /**
  377. * validate the inputs for a form
  378. *
  379. * @param array &$vars page meta data
  380. * @param array &$form_fields array of fields
  381. *
  382. * @return an array of the errors
  383. */
  384. function Form_validate(&$vars, &$form_fields) {
  385. $errors=array();
  386. foreach ($form_fields as $r2) {
  387. $name=preg_replace('/[^a-zA-Z0-9_]/', '', $r2['name']);
  388. if ($r2['type']=='email' && $r2['extra']) {
  389. if (!isset($_SESSION['emails'])
  390. || $_SESSION['emails'][@$_REQUEST[$name]]!==true
  391. ) {
  392. $errors[]=__('Email validation code was not correct.');
  393. }
  394. }
  395. if ($r2['isrequired'] && @$_REQUEST[$name]=='') {
  396. $n=$r2['name'];
  397. $errors[]=__(
  398. 'You must fill in the <strong>%1</strong> field.',
  399. array($n),
  400. 'core'
  401. );
  402. }
  403. if ($r2['type']=='email'
  404. && $_REQUEST[$name]
  405. && !filter_var(@$_REQUEST[$name], FILTER_VALIDATE_EMAIL)
  406. ) {
  407. $n=$r2['name'];
  408. $errors[]=__(
  409. 'You must provide a valid email in the <strong>%1</strong> field.',
  410. array($n),
  411. 'core'
  412. );
  413. }
  414. }
  415. // { check the captcha
  416. if (@$vars['forms_captcha_required']) {
  417. require_once $_SERVER['DOCUMENT_ROOT'].'/ww.incs/recaptcha.php';
  418. if (!isset($_REQUEST['recaptcha_challenge_field'])) {
  419. $errors[]=__('You must fill in the captcha (image text).');
  420. }
  421. else {
  422. $result
  423. = recaptcha_check_answer(
  424. RECAPTCHA_PRIVATE,
  425. $_SERVER['REMOTE_ADDR'],
  426. $_REQUEST['recaptcha_challenge_field'],
  427. $_REQUEST['recaptcha_response_field']
  428. );
  429. if (!$result->is_valid) {
  430. $errors[]=__('Invalid captcha. Please try again.');
  431. }
  432. }
  433. }
  434. // }
  435. // { check the From field
  436. $from_field=preg_replace('/[^a-zA-Z]/', '', @$vars['forms_replyto']);
  437. $from=isset($_REQUEST[$from_field])?$_REQUEST[$from_field]:'';
  438. if ($from == '') {
  439. if (!(@$vars['forms_replyto'])) {
  440. $errors[]=__('No replyto field has been set up by the admin!');
  441. }
  442. else {
  443. $errors[]='please fill in the "'.$vars['forms_replyto'].'" field.';
  444. }
  445. }
  446. // }
  447. return $errors;
  448. }
  449. // }