webform.submissions.inc 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. <?php
  2. /**
  3. * @file
  4. * Submission handling functions.
  5. *
  6. * This file is loaded when handling submissions, either submitting new,
  7. * editing, or viewing. It also contains all CRUD functions for submissions.
  8. *
  9. * @author Nathan Haug <nate@lullabot.com>
  10. */
  11. /**
  12. * Given an array of submitted values, flatten it into data for a submission.
  13. *
  14. * @param $node
  15. * The node object containing the current webform.
  16. * @param $submitted
  17. * The submitted user values from the webform.
  18. *
  19. * @return array
  20. * An array suitable for use in the 'data' property of a $submission object.
  21. */
  22. function webform_submission_data($node, $submitted) {
  23. $data = array();
  24. foreach ($submitted as $cid => $values) {
  25. // Don't save pseudo-fields or pagebreaks as submitted data.
  26. if (!isset($node->webform['components'][$cid]) || $node->webform['components'][$cid]['type'] == 'pagebreak') {
  27. continue;
  28. }
  29. if (is_array($values)) {
  30. $data[$cid] = $values;
  31. }
  32. else {
  33. $data[$cid][0] = $values;
  34. }
  35. }
  36. return $data;
  37. }
  38. /**
  39. * Given set of $form_state values, prepare a psuedo-submission.
  40. *
  41. * @param object $node
  42. * The webform node object.
  43. * @param object $account
  44. * The user account that is creating this submission.
  45. * @param array $form_state
  46. * The form_state containing the values for the submission.
  47. * @param object $prototype
  48. * An existing submission that is being previewed, if any.
  49. *
  50. * @return object
  51. * A new submission object, possibly for preview
  52. */
  53. function webform_submission_create($node, $account, array $form_state, $is_preview = FALSE, $prototype = NULL) {
  54. $data = webform_submission_data($node, $form_state['values']['submitted']);
  55. if (is_object($prototype)) {
  56. $submission = clone $prototype;
  57. $submission->preview = $is_preview;
  58. $submission->data = $data;
  59. }
  60. else {
  61. $submission = (object) array(
  62. 'nid' => $node->nid,
  63. 'uid' => $account->uid,
  64. 'sid' => NULL,
  65. 'submitted' => REQUEST_TIME,
  66. 'completed' => 0,
  67. 'modified' => REQUEST_TIME,
  68. 'remote_addr' => webform_ip_address($node),
  69. 'is_draft' => TRUE,
  70. 'highest_valid_page' => 0,
  71. 'preview' => $is_preview,
  72. 'serial' => NULL,
  73. 'data' => $data,
  74. );
  75. drupal_alter('webform_submission_create', $submission, $node, $account, $form_state);
  76. }
  77. return $submission;
  78. }
  79. /**
  80. * Update a webform submission entry in the database.
  81. *
  82. * @param $node
  83. * The node object containing the current webform.
  84. * @param $submission
  85. * The webform submission object to be saved into the database.
  86. *
  87. * @return int
  88. * The existing submission SID.
  89. */
  90. function webform_submission_update($node, $submission) {
  91. $transaction = db_transaction();
  92. // Allow other modules to modify the submission before saving.
  93. foreach (module_implements('webform_submission_presave') as $module) {
  94. $function = $module . '_webform_submission_presave';
  95. $function($node, $submission);
  96. }
  97. $submission->completed = empty($submission->completed) && !$submission->is_draft ? REQUEST_TIME : $submission->completed;
  98. $submission->modified = REQUEST_TIME;
  99. // Update the main submission info.
  100. drupal_write_record('webform_submissions', $submission, 'sid');
  101. // If is draft, only delete data for components submitted, to
  102. // preserve any data from form pages not visited in this submission.
  103. if ($submission->is_draft) {
  104. $submitted_cids = array_keys($submission->data);
  105. if ($submitted_cids) {
  106. db_delete('webform_submitted_data')
  107. ->condition('sid', $submission->sid)
  108. ->condition('cid', $submitted_cids, 'IN')
  109. ->execute();
  110. }
  111. }
  112. else {
  113. db_delete('webform_submitted_data')
  114. ->condition('sid', $submission->sid)
  115. ->execute();
  116. }
  117. // Then re-add submission data to the database.
  118. $submission->is_new = FALSE;
  119. webform_submission_insert($node, $submission);
  120. module_invoke_all('webform_submission_update', $node, $submission);
  121. return $submission->sid;
  122. }
  123. /**
  124. * Insert a webform submission entry in the database.
  125. *
  126. * @param $node
  127. * The node object containing the current webform.
  128. * @param $submission
  129. * The webform submission object to be saved into the database.
  130. *
  131. * @return int
  132. * The new submission SID.
  133. */
  134. function webform_submission_insert($node, $submission) {
  135. $transaction = db_transaction();
  136. // The submission ID may already be set if being called as an update.
  137. if (!isset($submission->sid) && (!isset($submission->is_new) || $submission->is_new == FALSE)) {
  138. // Allow other modules to modify the submission before saving.
  139. foreach (module_implements('webform_submission_presave') as $module) {
  140. $function = $module . '_webform_submission_presave';
  141. $function($node, $submission);
  142. }
  143. $submission->nid = $node->webform['nid'];
  144. if (empty($submission->serial)) {
  145. $submission->serial = _webform_submission_serial_next_value($node->nid);
  146. }
  147. $submission->completed = empty($submission->completed) && !$submission->is_draft ? REQUEST_TIME : $submission->completed;
  148. drupal_write_record('webform_submissions', $submission);
  149. $is_new = TRUE;
  150. }
  151. foreach ($submission->data as $cid => $values) {
  152. foreach ($values as $delta => $value) {
  153. $data = array(
  154. 'nid' => $node->webform['nid'],
  155. 'sid' => $submission->sid,
  156. 'cid' => $cid,
  157. 'no' => $delta,
  158. 'data' => is_null($value) ? '' : $value,
  159. );
  160. drupal_write_record('webform_submitted_data', $data);
  161. }
  162. }
  163. // Invoke the insert hook after saving all the data.
  164. if (isset($is_new)) {
  165. module_invoke_all('webform_submission_insert', $node, $submission);
  166. }
  167. return $submission->sid;
  168. }
  169. /**
  170. * Delete a single submission.
  171. *
  172. * @param $node
  173. * The node object containing the current webform.
  174. * @param $submission
  175. * The webform submission object to be deleted from the database.
  176. */
  177. function webform_submission_delete($node, $submission) {
  178. $transaction = db_transaction();
  179. // Iterate through all components and let each do cleanup if necessary.
  180. foreach ($node->webform['components'] as $cid => $component) {
  181. if (isset($submission->data[$cid])) {
  182. webform_component_invoke($component['type'], 'delete', $component, $submission->data[$cid]);
  183. }
  184. }
  185. // Delete any anonymous session information.
  186. if (isset($_SESSION['webform_submission'][$submission->sid])) {
  187. unset($_SESSION['webform_submission'][$submission->sid]);
  188. }
  189. db_delete('webform_submitted_data')
  190. ->condition('nid', $node->nid)
  191. ->condition('sid', $submission->sid)
  192. ->execute();
  193. db_delete('webform_submissions')
  194. ->condition('nid', $node->nid)
  195. ->condition('sid', $submission->sid)
  196. ->execute();
  197. module_invoke_all('webform_submission_delete', $node, $submission);
  198. }
  199. /**
  200. * Send related e-mails related to a submission.
  201. *
  202. * This function is usually invoked when a submission is completed, but may be
  203. * called any time e-mails should be redelivered.
  204. *
  205. * @param $node
  206. * The node object containing the current webform.
  207. * @param $submission
  208. * The webform submission object to be used in sending e-mails.
  209. * @param $emails
  210. * (optional) An array of specific e-mail settings to be used. If omitted, all
  211. * e-mails in $node->webform['emails'] will be sent.
  212. * @param bool $send_disabled
  213. * (optional) When TRUE, send all emails, even those that are disabled.
  214. *
  215. * @return int
  216. * Number of mail sent.
  217. */
  218. function webform_submission_send_mail($node, $submission, $emails = NULL, $send_disabled = FALSE) {
  219. // Get the list of e-mails we'll be sending.
  220. $emails = isset($emails) ? $emails : $node->webform['emails'];
  221. // Create a themed message for mailing.
  222. $send_count = 0;
  223. foreach ($emails as $eid => $email) {
  224. if (!$send_disabled && !$email['status']) {
  225. continue;
  226. }
  227. $mail = _webform_submission_prepare_mail($node, $submission, $email);
  228. if (!$mail) {
  229. continue;
  230. }
  231. $addresses_final = $mail['addresses_final'];
  232. $send_increment = $mail['send_increment'];
  233. $language = $mail['language'];
  234. $mail_params = $mail['mail_params'];
  235. // Mail the webform results.
  236. foreach ($addresses_final as $address) {
  237. $message = drupal_mail('webform', 'submission', $address, $language, $mail_params, $email['from']);
  238. if ($message['result']) {
  239. $send_count += $send_increment;
  240. }
  241. }
  242. }
  243. return $send_count;
  244. }
  245. /**
  246. * Prepare a submission email for use by webform_submission_send_mail()
  247. *
  248. * @param $node
  249. * The node object containing the current webform.
  250. * @param $submission
  251. * The webform submission object to be used in sending e-mails.
  252. * @param $email
  253. * The e-mail settings to be used. This will have some of its values adjusted.
  254. *
  255. * @return array|null
  256. * An array of the information about the email needed by drupal_mail().
  257. */
  258. function _webform_submission_prepare_mail($node, $submission, &$email) {
  259. global $user;
  260. // Set the HTML property based on availablity of MIME Mail.
  261. $email['html'] = ($email['html'] && webform_variable_get('webform_email_html_capable'));
  262. // Pass through the theme layer if using the default template.
  263. if ($email['template'] == 'default') {
  264. $email['message'] = theme(array('webform_mail_' . $node->nid, 'webform_mail', 'webform_mail_message'), array('node' => $node, 'submission' => $submission, 'email' => $email));
  265. }
  266. else {
  267. $email['message'] = $email['template'];
  268. }
  269. // Replace tokens in the message.
  270. $email['message'] = webform_replace_tokens($email['message'], $node, $submission, $email, (boolean) $email['html']);
  271. // Build the e-mail headers.
  272. $email['headers'] = theme(array('webform_mail_headers_' . $node->nid, 'webform_mail_headers'), array('node' => $node, 'submission' => $submission, 'email' => $email));
  273. // Assemble the From string.
  274. if (isset($email['headers']['From'])) {
  275. // If a header From is already set, don't override it.
  276. $email['from'] = $email['headers']['From'];
  277. unset($email['headers']['From']);
  278. }
  279. else {
  280. // Format the From address.
  281. $mapping = isset($email['extra']['from_address_mapping']) ? $email['extra']['from_address_mapping'] : NULL;
  282. $email['from'] = webform_format_email_address($email['from_address'], $email['from_name'], $node, $submission, TRUE, TRUE, NULL, $mapping);
  283. }
  284. // If "Use Reply-To header" is set in Webform settings and the Reply-To
  285. // header is not already set, set Reply-To to the From and set From address
  286. // to webform_default_from_name and webform_default_from_address.
  287. if (webform_variable_get('webform_email_replyto') &&
  288. empty($email['headers']['Reply-To']) &&
  289. ($default_from_name = webform_variable_get('webform_default_from_name')) &&
  290. ($default_from_address = webform_variable_get('webform_default_from_address')) &&
  291. $email['from'] !== $default_from_name) {
  292. $email['headers']['Reply-To'] = $email['from'];
  293. $email['from'] = $default_from_address;
  294. if (webform_variable_get('webform_email_address_format') == 'long') {
  295. $email_parts = webform_parse_email_address($email['headers']['Reply-To']);
  296. $from_name = t('!name via !site_name',
  297. array(
  298. '!name' => strlen($email_parts['name']) ? $email_parts['name'] : $email_parts['address'],
  299. '!site_name' => $default_from_name,
  300. ));
  301. $from_name = str_replace('"', "'", $from_name);
  302. $from_name = implode(' ', array_map('mime_header_encode', explode(' ', $from_name)));
  303. $email['from'] = '"' . $from_name . '" <' . $email['from'] . '>';
  304. }
  305. }
  306. // Update the subject if set in the themed headers.
  307. if (isset($email['headers']['Subject'])) {
  308. $email['subject'] = $email['headers']['Subject'];
  309. unset($email['headers']['Subject']);
  310. }
  311. else {
  312. $email['subject'] = webform_format_email_subject($email['subject'], $node, $submission);
  313. }
  314. // Update the to e-mail if set in the themed headers.
  315. if (isset($email['headers']['To'])) {
  316. $email['email'] = $email['headers']['To'];
  317. unset($email['headers']['To']);
  318. $addresses = array_filter(explode(',', $email['email']));
  319. }
  320. else {
  321. // Format the To address(es).
  322. $mapping = isset($email['extra']['email_mapping']) ? $email['extra']['email_mapping'] : NULL;
  323. $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, TRUE, FALSE, NULL, $mapping);
  324. $email['email'] = implode(',', $addresses);
  325. }
  326. // Generate the list of addresses that this e-mail will be sent to.
  327. $addresses_final = array_filter($addresses, 'webform_valid_email_address');
  328. if (!$addresses_final) {
  329. return;
  330. }
  331. // Verify that this submission is not attempting to send any spam hacks.
  332. foreach ($addresses_final as $address) {
  333. if (_webform_submission_spam_check($address, $email['subject'], $email['from'], $email['headers'])) {
  334. watchdog('webform', 'Possible spam attempt from @remote !message',
  335. array('@remote' => ip_address(), '!message' => "<br />\n" . nl2br(htmlentities($email['message']))));
  336. drupal_set_message(t('Illegal information. Data not submitted.'), 'error');
  337. return;
  338. }
  339. }
  340. // Consolidate addressees into one message if permitted by configuration.
  341. $send_increment = 1;
  342. if (!webform_variable_get('webform_email_address_individual')) {
  343. $send_increment = count($addresses_final);
  344. $addresses_final = array(implode(', ', $addresses_final));
  345. }
  346. // Prepare the variables used by drupal_mail().
  347. $language = $user->uid ? user_preferred_language($user) : language_default();
  348. $mail_params = array(
  349. 'message' => $email['message'],
  350. 'subject' => $email['subject'],
  351. 'headers' => $email['headers'],
  352. 'node' => $node,
  353. 'submission' => $submission,
  354. 'email' => $email,
  355. );
  356. if (webform_variable_get('webform_email_html_capable')) {
  357. // Load attachments for the e-mail.
  358. $attachments = array();
  359. if ($email['attachments']) {
  360. webform_component_include('file');
  361. foreach ($node->webform['components'] as $component) {
  362. if (webform_component_feature($component['type'], 'attachment') && !empty($submission->data[$component['cid']][0])) {
  363. if (webform_component_implements($component['type'], 'attachments')) {
  364. $files = webform_component_invoke($component['type'], 'attachments', $component, $submission->data[$component['cid']]);
  365. if ($files) {
  366. $attachments = array_merge($attachments, $files);
  367. }
  368. }
  369. }
  370. }
  371. }
  372. // Add the attachments to the mail parameters.
  373. $mail_params['attachments'] = $attachments;
  374. // Set all other properties for HTML e-mail handling.
  375. $mail_params['plain'] = !$email['html'];
  376. $mail_params['plaintext'] = $email['html'] ? NULL : $email['message'];
  377. $mail_params['headers'] = $email['headers'];
  378. if ($email['html']) {
  379. // MIME Mail requires this header or it will filter all text.
  380. $mail_params['headers']['Content-Type'] = 'text/html; charset=UTF-8';
  381. }
  382. }
  383. return array(
  384. 'addresses_final' => $addresses_final,
  385. 'send_increment' => $send_increment,
  386. 'language' => $language,
  387. 'mail_params' => $mail_params,
  388. );
  389. }
  390. /**
  391. * Confirm form to delete a single form submission.
  392. *
  393. * @param $form
  394. * The new form array.
  395. * @param $form_state
  396. * The current form state.
  397. * @param $node
  398. * The node for which this webform was submitted.
  399. * @param $submission
  400. * The submission to be deleted (from webform_submitted_data).
  401. */
  402. function webform_submission_delete_form($form, $form_state, $node, $submission) {
  403. webform_set_breadcrumb($node, $submission);
  404. // Set the correct page title.
  405. drupal_set_title(webform_submission_title($node, $submission));
  406. // Keep the NID and SID in the same location as the webform_client_form().
  407. $form['#tree'] = TRUE;
  408. $form['details']['nid'] = array(
  409. '#type' => 'value',
  410. '#value' => $node->nid,
  411. );
  412. $form['details']['sid'] = array(
  413. '#type' => 'value',
  414. '#value' => $submission->sid,
  415. );
  416. $question = t('Are you sure you want to delete this submission?');
  417. return confirm_form($form, NULL, "node/{$node->nid}/submission/{$submission->sid}", $question, t('Delete'), t('Cancel'));
  418. }
  419. /**
  420. * Form submit handler.
  421. */
  422. function webform_submission_delete_form_submit($form, &$form_state) {
  423. $node = node_load($form_state['values']['details']['nid']);
  424. $submission = webform_get_submission($form_state['values']['details']['nid'], $form_state['values']['details']['sid']);
  425. webform_submission_delete($node, $submission);
  426. drupal_set_message(t('Submission deleted.'));
  427. // If no destination query was supplied in the URL (for example, Edit tab),
  428. // redirect to the most-privledged destination.
  429. $form_state['redirect'] = 'node/' . $node->nid .
  430. (webform_results_access($node) ? '/webform-results' : '/submissions');
  431. }
  432. /**
  433. * Menu title callback; Return the submission number as a title.
  434. */
  435. function webform_submission_title($node, $submission) {
  436. return t('Submission #@serial', array('@serial' => $submission->serial));
  437. }
  438. /**
  439. * Menu callback; Present a Webform submission page for display or editing.
  440. */
  441. function webform_submission_page($node, $submission, $format) {
  442. global $user;
  443. // Render the admin UI breadcrumb.
  444. webform_set_breadcrumb($node, $submission);
  445. // Set the correct page title.
  446. drupal_set_title(webform_submission_title($node, $submission));
  447. if ($format == 'form') {
  448. $output = drupal_get_form('webform_client_form_' . $node->nid, $node, $submission);
  449. }
  450. else {
  451. $renderable = webform_submission_render($node, $submission, NULL, $format);
  452. $renderable['#attached']['css'][] = drupal_get_path('module', 'webform') . '/css/webform.css';
  453. $output = drupal_render($renderable);
  454. }
  455. // Determine the mode in which we're displaying this submission.
  456. $mode = ($format != 'form') ? 'display' : 'form';
  457. if (strpos(request_path(), 'print/') !== FALSE) {
  458. $mode = 'print';
  459. }
  460. if (strpos(request_path(), 'printpdf/') !== FALSE) {
  461. $mode = 'pdf';
  462. }
  463. // Add navigation for administrators.
  464. if (webform_results_access($node)) {
  465. $navigation = theme('webform_submission_navigation', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
  466. $information = theme('webform_submission_information', array('node' => $node, 'submission' => $submission, 'mode' => $mode));
  467. }
  468. else {
  469. $navigation = NULL;
  470. $information = NULL;
  471. }
  472. // Actions may be shown to all users.
  473. $actions = theme('links', array('links' => module_invoke_all('webform_submission_actions', $node, $submission), 'attributes' => array('class' => array('links', 'inline', 'webform-submission-actions'))));
  474. // Disable the page cache for anonymous users viewing or editing submissions.
  475. if (!$user->uid) {
  476. webform_disable_page_cache();
  477. }
  478. $page = array(
  479. '#theme' => 'webform_submission_page',
  480. '#node' => $node,
  481. '#mode' => $mode,
  482. '#submission' => $submission,
  483. '#submission_content' => $output,
  484. '#submission_navigation' => $navigation,
  485. '#submission_information' => $information,
  486. '#submission_actions' => $actions,
  487. );
  488. $page['#attached']['library'][] = array('webform', 'admin');
  489. return $page;
  490. }
  491. /**
  492. * Form to resend specific e-mails associated with a submission.
  493. */
  494. function webform_submission_resend($form, $form_state, $node, $submission) {
  495. // Render the admin UI breadcrumb.
  496. webform_set_breadcrumb($node, $submission);
  497. $form['#tree'] = TRUE;
  498. $form['#node'] = $node;
  499. $form['#submission'] = $submission;
  500. foreach ($node->webform['emails'] as $eid => $email) {
  501. $mapping = isset($email['extra']['email_mapping']) ? $email['extra']['email_mapping'] : NULL;
  502. $addresses = webform_format_email_address($email['email'], NULL, $node, $submission, FALSE, FALSE, NULL, $mapping);
  503. $addresses_valid = array_map('webform_valid_email_address', $addresses);
  504. $valid_email = count($addresses) == array_sum($addresses_valid);
  505. $form['resend'][$eid] = array(
  506. '#type' => 'checkbox',
  507. '#default_value' => $valid_email && $email['status'],
  508. '#disabled' => !$valid_email,
  509. );
  510. $form['emails'][$eid]['email'] = array(
  511. '#markup' => nl2br(check_plain(implode("\n", $addresses))),
  512. );
  513. if (!$valid_email) {
  514. $form['emails'][$eid]['email']['#markup'] .= ' (' . t('empty or invalid') . ')';
  515. }
  516. $form['emails'][$eid]['subject'] = array(
  517. '#markup' => check_plain(webform_format_email_subject($email['subject'], $node, $submission)),
  518. );
  519. $form['actions'] = array('#type' => 'actions');
  520. $form['actions']['submit'] = array(
  521. '#type' => 'submit',
  522. '#value' => t('Resend e-mails'),
  523. );
  524. $form['actions']['cancel'] = array(
  525. '#type' => 'markup',
  526. '#markup' => l(t('Cancel'), isset($_GET['destination']) ? $_GET['destination'] : 'node/' . $node->nid . '/submission/' . $submission->sid),
  527. );
  528. }
  529. return $form;
  530. }
  531. /**
  532. * Validate handler for webform_submission_resend().
  533. */
  534. function webform_submission_resend_validate($form, &$form_state) {
  535. if (count(array_filter($form_state['values']['resend'])) == 0) {
  536. form_set_error('emails', t('You must select at least one email address to resend submission.'));
  537. }
  538. }
  539. /**
  540. * Submit handler for webform_submission_resend().
  541. */
  542. function webform_submission_resend_submit($form, &$form_state) {
  543. $node = $form['#node'];
  544. $submission = $form['#submission'];
  545. $emails = array();
  546. foreach ($form_state['values']['resend'] as $eid => $checked) {
  547. if ($checked) {
  548. $emails[] = $form['#node']->webform['emails'][$eid];
  549. }
  550. }
  551. $sent_count = webform_submission_send_mail($node, $submission, $emails, TRUE);
  552. if ($sent_count) {
  553. drupal_set_message(format_plural($sent_count,
  554. 'Successfully re-sent submission #@sid to 1 recipient.',
  555. 'Successfully re-sent submission #@sid to @count recipients.',
  556. array('@sid' => $submission->sid)
  557. ));
  558. }
  559. else {
  560. drupal_set_message(t('No e-mails were able to be sent due to a server error.'), 'error');
  561. }
  562. }
  563. /**
  564. * Theme the node components form. Use a table to organize the components.
  565. *
  566. * @param array $variables
  567. * Array with key "form" containing the form array.
  568. *
  569. * @return string
  570. * Formatted HTML form, ready for display.
  571. *
  572. * @throws Exception
  573. */
  574. function theme_webform_submission_resend(array $variables) {
  575. $form = $variables['form'];
  576. $header = array(t('Send'), t('E-mail to'), t('Subject'));
  577. $rows = array();
  578. if (!empty($form['emails'])) {
  579. foreach (element_children($form['emails']) as $eid) {
  580. // Add each component to a table row.
  581. $rows[] = array(
  582. drupal_render($form['resend'][$eid]),
  583. drupal_render($form['emails'][$eid]['email']),
  584. drupal_render($form['emails'][$eid]['subject']),
  585. );
  586. }
  587. }
  588. else {
  589. $rows[] = array(array('data' => t('This webform is currently not setup to send emails.'), 'colspan' => 3));
  590. }
  591. $output = '';
  592. $output .= theme('table', array('header' => $header, 'rows' => $rows, 'sticky' => FALSE, 'attributes' => array('id' => 'webform-emails')));
  593. $output .= drupal_render_children($form);
  594. return $output;
  595. }
  596. /**
  597. * Prepare a Webform submission for display on a page or in an e-mail.
  598. *
  599. * @param object $node
  600. * The node object.
  601. * @param object $submission
  602. * The submission object.
  603. * @param array $email
  604. * The email configuration array.
  605. * @param string $format
  606. * The format the form should be displayed as. May be one of the following:
  607. * - form: Show as an editable form.
  608. * - html: Show as HTML results.
  609. * - text: Show as plain text.
  610. * @param array $excluded_components
  611. * An array of components to exclude as cid.
  612. *
  613. * @return array
  614. * A renderable array of the submission.
  615. */
  616. function webform_submission_render($node, $submission, $email, $format, $excluded_components = NULL) {
  617. $component_tree = array();
  618. $renderable = array();
  619. $page_count = 1;
  620. // Meta data that may be useful for modules implementing
  621. // hook_webform_submission_render_alter().
  622. $renderable['#node'] = $node;
  623. $renderable['#submission'] = $submission;
  624. $renderable['#email'] = $email;
  625. $renderable['#format'] = $format;
  626. // Set the theme function for submissions.
  627. $renderable['#theme'] = array('webform_submission_' . $node->nid, 'webform_submission');
  628. $components = $node->webform['components'];
  629. // Remove excluded components.
  630. if (is_array($excluded_components)) {
  631. foreach ($excluded_components as $cid) {
  632. unset($components[$cid]);
  633. }
  634. if (!empty($email['exclude_empty'])) {
  635. foreach ($submission->data as $cid => $data) {
  636. // Caution. Grids store their data in an array index by question key.
  637. if (implode($data) == '') {
  638. unset($components[$cid]);
  639. }
  640. }
  641. }
  642. }
  643. module_load_include('inc', 'webform', 'includes/webform.components');
  644. _webform_components_tree_build($components, $component_tree, 0, $page_count);
  645. // Make sure at least one field is available.
  646. if (isset($component_tree['children'])) {
  647. // Recursively add components to the form.
  648. $sorter = webform_get_conditional_sorter($node);
  649. $input_values = $sorter->executeConditionals($submission->data);
  650. foreach ($component_tree['children'] as $cid => $component) {
  651. if ($sorter->componentVisibility($cid, $component['page_num']) == webformConditionals::componentShown) {
  652. _webform_client_form_add_component($node, $component, NULL, $renderable, $renderable, $input_values, $format);
  653. }
  654. }
  655. }
  656. drupal_alter('webform_submission_render', $renderable);
  657. return $renderable;
  658. }
  659. /**
  660. * Return all the submissions for a particular node.
  661. *
  662. * @param $filters
  663. * An array of filters to apply to this query. Usually in the format
  664. * array('nid' => $nid, 'uid' => $uid). A single integer may also be passed
  665. * in, which will be equivalent to specifying a $nid filter.
  666. * @param $header
  667. * If the results of this fetch will be used in a sortable
  668. * table, pass the array header of the table.
  669. * @param $pager_count
  670. * Optional. The number of submissions to include in the results.
  671. *
  672. * @return array
  673. * Array of submission data for a particular node.
  674. */
  675. function webform_get_submissions($filters = array(), $header = NULL, $pager_count = 0) {
  676. return webform_get_submissions_load(webform_get_submissions_query($filters, $header, $pager_count));
  677. }
  678. /**
  679. * Returns an unexecuted webform_submissions query on for the arguments.
  680. *
  681. * This is an internal routine and not intended for use by other modules.
  682. *
  683. * @param $filters
  684. * An array of filters to apply to this query. Usually in the format
  685. * array('nid' => $nid, 'uid' => $uid). A single integer may also be passed
  686. * in, which will be equivalent to specifying a $nid filter. 'sid' may also
  687. * be included, either as a single sid or an array of sid's.
  688. * @param $header
  689. * If the results of this fetch will be used in a sortable
  690. * table, pass the array header of the table.
  691. * @param $pager_count
  692. * Optional. The number of submissions to include in the results.
  693. *
  694. * @return QueryExtendableInterface|SelectQueryInterface
  695. * The query object.
  696. */
  697. function webform_get_submissions_query($filters = array(), $header = NULL, $pager_count = 0) {
  698. if (!is_array($filters)) {
  699. $filters = array('ws.nid' => $filters);
  700. }
  701. // Qualify all filters with a table alias. ws.* is assumed, except for u.uid.
  702. foreach ($filters as $column => $value) {
  703. if (strpos($column, '.') === FALSE) {
  704. $filters[($column == 'uid' ? 'u.' : 'ws.') . $column] = $value;
  705. unset($filters[$column]);
  706. }
  707. }
  708. // If the sid is specified, but there are none, force the query to fail
  709. // rather than query on an empty array.
  710. if (isset($filters['ws.sid']) && empty($filters['ws.sid'])) {
  711. $filters['ws.sid'] = 0;
  712. }
  713. // Build the list of submissions and load their basic information.
  714. $pager_query = db_select('webform_submissions', 'ws')
  715. // Ensure only one row per submission is returned. Could be more than one if
  716. // sorting on a column that uses multiple rows for its data.
  717. ->distinct()
  718. ->addTag('webform_get_submissions_sids')
  719. ->fields('ws');
  720. // Add each filter.
  721. foreach ($filters as $column => $value) {
  722. $pager_query->condition($column, $value);
  723. }
  724. // Join to the users table to include user name in results.
  725. $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
  726. $pager_query->fields('u', array('name'));
  727. if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
  728. if (!empty($_SESSION['webform_submission'])) {
  729. $anonymous_sids = array_keys($_SESSION['webform_submission']);
  730. $pager_query->condition('ws.sid', $anonymous_sids, 'IN');
  731. }
  732. else {
  733. $pager_query->condition('ws.sid', 0);
  734. }
  735. }
  736. if (is_array($header)) {
  737. $metadata_columns = array();
  738. foreach ($header as $header_item) {
  739. $metadata_columns[] = $header_item['data'];
  740. }
  741. $sort = drupal_get_query_parameters();
  742. // Sort by submitted data column if order is set but not in
  743. // $metadata_columns.
  744. if (isset($sort['order']) && !in_array($sort['order'], $metadata_columns, TRUE)) {
  745. // Default if sort is unset or invalid.
  746. if (!isset($sort['sort']) || !in_array($sort['sort'], array('asc', 'desc'), TRUE)) {
  747. $sort['sort'] = '';
  748. }
  749. $pager_query->leftJoin('webform_component', 'wc', 'ws.nid = wc.nid AND wc.name = :form_key', array('form_key' => $sort['order']));
  750. $pager_query->leftJoin('webform_submitted_data', 'wsd', 'wc.nid = wsd.nid AND ws.sid = wsd.sid AND wc.cid = wsd.cid');
  751. $pager_query->orderBy('wsd.data', $sort['sort']);
  752. $pager_query->orderBy('ws.sid', 'ASC');
  753. }
  754. // Sort by metadata column.
  755. else {
  756. // Extending the query instantiates a new query object.
  757. $pager_query = $pager_query->extend('TableSort');
  758. $pager_query->orderByHeader($header);
  759. }
  760. }
  761. else {
  762. $pager_query->orderBy('ws.sid', 'ASC');
  763. }
  764. if ($pager_count) {
  765. // Extending the query instantiates a new query object.
  766. $pager_query = $pager_query->extend('PagerDefault');
  767. $pager_query->limit($pager_count);
  768. }
  769. return $pager_query;
  770. }
  771. /**
  772. * Retrieve and load the submissions for the specified submissions query.
  773. *
  774. * This is an internal routine and not intended for use by other modules.
  775. *
  776. * @params object $pager_query
  777. * A select or extended select query containing the needed fields:
  778. * webform_submissions: all fields
  779. * user: name
  780. *
  781. * @return array
  782. * An array of loaded webform submissions.
  783. */
  784. function webform_get_submissions_load($pager_query) {
  785. // If the "$pager_query" is actually an unextended select query, then instead
  786. // of querying the webform_submissions_data table with a potentially huge
  787. // array of sids in an IN clause, use the select query directly as this will
  788. // be much faster. Extended queries don't work in join clauses. The query
  789. // is assumed to include the sid.
  790. if ($pager_query instanceof SelectQuery) {
  791. $submissions_query = clone $pager_query;
  792. }
  793. // Extract any filter on node id to use in an optimization below.
  794. foreach ($pager_query->conditions() as $index => $condition) {
  795. if ($index !== '#conjunction' && $condition['operator'] === '=' && ($condition['field'] === 'nid' || $condition['field'] === 'ws.nid')) {
  796. $nid = $condition['value'];
  797. break;
  798. }
  799. }
  800. $result = $pager_query->execute();
  801. $submissions = $result->fetchAllAssoc('sid');
  802. // If there are no submissions being retrieved, return an empty array.
  803. if (!$submissions) {
  804. return $submissions;
  805. }
  806. foreach ($submissions as $sid => $submission) {
  807. $submissions[$sid]->preview = FALSE;
  808. $submissions[$sid]->data = array();
  809. }
  810. // Query the required submission data.
  811. $query = db_select('webform_submitted_data', 'sd');
  812. $query
  813. ->addTag('webform_get_submissions_data')
  814. ->fields('sd', array('sid', 'cid', 'no', 'data'))
  815. ->orderBy('sd.sid', 'ASC')
  816. ->orderBy('sd.cid', 'ASC')
  817. ->orderBy('sd.no', 'ASC');
  818. if (isset($submissions_query)) {
  819. // If available, prefer joining on the subquery as it is much faster than an
  820. // IN clause on a large array. A subquery with the IN operator doesn't work
  821. // when the subquery has a LIMIT clause, requiring an inner join instead.
  822. $query->innerJoin($submissions_query, 'ws2', 'sd.sid = ws2.sid');
  823. }
  824. else {
  825. $query->condition('sd.sid', array_keys($submissions), 'IN');
  826. }
  827. // By adding the NID to this query we allow MySQL to use the primary key on
  828. // in webform_submitted_data for sorting (nid_sid_cid_no).
  829. if (isset($nid)) {
  830. $query->condition('sd.nid', $nid);
  831. }
  832. $result = $query->execute();
  833. // Convert the queried rows into submission data.
  834. foreach ($result as $row) {
  835. $submissions[$row->sid]->data[$row->cid][$row->no] = $row->data;
  836. }
  837. foreach (module_implements('webform_submission_load') as $module) {
  838. $function = $module . '_webform_submission_load';
  839. $function($submissions);
  840. }
  841. return $submissions;
  842. }
  843. /**
  844. * Return a count of the total number of submissions for a node.
  845. *
  846. * @param $nid
  847. * The node ID for which submissions are being fetched.
  848. * @param $uid
  849. * Optional; the user ID to filter the submissions by.
  850. * @param $is_draft
  851. * Optional; NULL for all, truthy for drafts only, falsy for completed only.
  852. * The default is completed submissions only.
  853. *
  854. * @return int
  855. * The number of submissions.
  856. */
  857. function webform_get_submission_count($nid, $uid = NULL, $is_draft = 0) {
  858. $counts = &drupal_static(__FUNCTION__);
  859. if (!isset($counts[$nid][$uid])) {
  860. $query = db_select('webform_submissions', 'ws')
  861. ->addTag('webform_get_submission_count')
  862. ->condition('ws.nid', $nid);
  863. if ($uid !== NULL) {
  864. $query->condition('ws.uid', $uid);
  865. }
  866. if ($uid === 0) {
  867. $submissions = isset($_SESSION['webform_submission']) ? $_SESSION['webform_submission'] : NULL;
  868. if ($submissions) {
  869. $query->condition('ws.sid', array_keys($submissions), 'IN');
  870. }
  871. else {
  872. // Intentionally never match anything if the anonymous user has no
  873. // submissions.
  874. $query->condition('ws.sid', 0);
  875. }
  876. }
  877. if (isset($is_draft)) {
  878. $query->condition('ws.is_draft', $is_draft);
  879. }
  880. $counts[$nid][$uid] = $query->countQuery()->execute()->fetchField();
  881. }
  882. return $counts[$nid][$uid];
  883. }
  884. /**
  885. * Fetch a specified submission for a webform node.
  886. */
  887. function webform_get_submission($nid, $sid) {
  888. $submissions = &drupal_static(__FUNCTION__, array());
  889. // Load the submission if needed.
  890. if (!isset($submissions[$sid])) {
  891. $new_submissions = webform_get_submissions(array('nid' => $nid, 'sid' => $sid));
  892. $submissions[$sid] = isset($new_submissions[$sid]) ? $new_submissions[$sid] : FALSE;
  893. }
  894. return $submissions[$sid];
  895. }
  896. /**
  897. * Verify that an email is not attempting to send any spam.
  898. */
  899. function _webform_submission_spam_check($to, $subject, $from, $headers = array()) {
  900. $headers = implode('\n', (array) $headers);
  901. // Check if they are attempting to spam using a bcc or content type hack.
  902. if (preg_match('/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers)) {
  903. // Possible spam attempt.
  904. return TRUE;
  905. }
  906. // Not spam.
  907. return FALSE;
  908. }
  909. /**
  910. * Check if the current user has exceeded the limit on this form.
  911. *
  912. * @param $node
  913. * The webform node to be checked.
  914. * @param $account
  915. * Optional parameter. Specify the account you want to check the limit
  916. * against.
  917. *
  918. * @return bool
  919. * Boolean TRUE if the user has exceeded their limit. FALSE otherwise.
  920. */
  921. function webform_submission_user_limit_check($node, $account = NULL) {
  922. global $user;
  923. $tracking_mode = webform_variable_get('webform_tracking_mode');
  924. if (!isset($account)) {
  925. $account = $user;
  926. }
  927. // We can only check access for anonymous users through their cookies.
  928. if ($user->uid !== 0 && $account->uid === 0) {
  929. watchdog('webform', 'Unable to check anonymous user submission limit when logged in as user @uid.', array('@uid' => $user->uid), WATCHDOG_WARNING);
  930. return FALSE;
  931. }
  932. // Check if submission limiting is enabled.
  933. if ($node->webform['submit_limit'] == '-1') {
  934. // No check enabled.
  935. return FALSE;
  936. }
  937. // Fetch all the entries from the database within the submit interval with
  938. // this username and IP.
  939. $num_submissions_database = 0;
  940. if (!$node->webform['confidential'] &&
  941. ($account->uid !== 0 || $tracking_mode === 'ip_address' || $tracking_mode === 'strict')) {
  942. $query = db_select('webform_submissions')
  943. ->addTag('webform_submission_user_limit_check')
  944. ->condition('nid', $node->nid)
  945. ->condition('is_draft', 0);
  946. if ($node->webform['submit_interval'] != -1) {
  947. $query->condition('submitted', REQUEST_TIME - $node->webform['submit_interval'], '>');
  948. }
  949. if ($account->uid) {
  950. $query->condition('uid', $account->uid);
  951. }
  952. else {
  953. $query->condition('remote_addr', ip_address());
  954. }
  955. $num_submissions_database = $query->countQuery()->execute()->fetchField();
  956. }
  957. // Double check the submission history from the users machine using cookies.
  958. $num_submissions_cookie = 0;
  959. if ($account->uid === 0 && ($tracking_mode === 'cookie' || $tracking_mode === 'strict')) {
  960. $cookie_name = 'webform-' . $node->nid;
  961. if (isset($_COOKIE[$cookie_name]) && is_array($_COOKIE[$cookie_name])) {
  962. foreach ($_COOKIE[$cookie_name] as $key => $timestamp) {
  963. if ($node->webform['submit_interval'] != -1 && $timestamp <= REQUEST_TIME - $node->webform['submit_interval']) {
  964. // Remove the cookie if past the required time interval.
  965. $params = session_get_cookie_params();
  966. setcookie($cookie_name . '[' . $key . ']', '', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
  967. }
  968. }
  969. // Count the number of submissions recorded in cookies.
  970. $num_submissions_cookie = count($_COOKIE[$cookie_name]);
  971. }
  972. }
  973. if ($num_submissions_database >= $node->webform['submit_limit'] || $num_submissions_cookie >= $node->webform['submit_limit']) {
  974. // Limit exceeded.
  975. return TRUE;
  976. }
  977. // Limit not exceeded.
  978. return FALSE;
  979. }
  980. /**
  981. * Check if the total number of submissions has exceeded the limit on this form.
  982. *
  983. * @param $node
  984. * The webform node to be checked.
  985. *
  986. * @return bool
  987. * Boolean TRUE if the form has exceeded it's limit. FALSE otherwise.
  988. */
  989. function webform_submission_total_limit_check($node) {
  990. // Check if submission limiting is enabled.
  991. if ($node->webform['total_submit_limit'] == '-1') {
  992. // No check enabled.
  993. return FALSE;
  994. }
  995. // Retrieve submission data from the database.
  996. $query = db_select('webform_submissions')
  997. ->addTag('webform_submission_total_limit_check')
  998. ->condition('nid', $node->nid)
  999. ->condition('is_draft', 0);
  1000. if ($node->webform['total_submit_interval'] != -1) {
  1001. $query->condition('submitted', REQUEST_TIME - $node->webform['total_submit_interval'], '>');
  1002. }
  1003. // Fetch all the entries from the database within the submit interval.
  1004. $num_submissions_database = $query->countQuery()->execute()->fetchField();
  1005. if ($num_submissions_database >= $node->webform['total_submit_limit']) {
  1006. // Limit exceeded.
  1007. return TRUE;
  1008. }
  1009. // Limit not exceeded.
  1010. return FALSE;
  1011. }
  1012. /**
  1013. * Preprocess function for webform-submission.tpl.php.
  1014. */
  1015. function template_preprocess_webform_submission(&$vars) {
  1016. $vars['node'] = $vars['renderable']['#node'];
  1017. $vars['submission'] = $vars['renderable']['#submission'];
  1018. $vars['email'] = $vars['renderable']['#email'];
  1019. $vars['format'] = $vars['renderable']['#format'];
  1020. }
  1021. /**
  1022. * Preprocess function for webform-submission-navigation.tpl.php.
  1023. */
  1024. function template_preprocess_webform_submission_navigation(&$vars) {
  1025. $start_path = ($vars['mode'] == 'print') ? 'print/' : 'node/';
  1026. $previous_query = db_select('webform_submissions')
  1027. ->condition('nid', $vars['node']->nid)
  1028. ->condition('sid', $vars['submission']->sid, '<');
  1029. $previous_query->addExpression('MAX(sid)');
  1030. $next_query = db_select('webform_submissions')
  1031. ->condition('nid', $vars['node']->nid)
  1032. ->condition('sid', $vars['submission']->sid, '>');
  1033. $next_query->addExpression('MIN(sid)');
  1034. $vars['previous'] = $previous_query->execute()->fetchField();
  1035. $vars['next'] = $next_query->execute()->fetchField();
  1036. $vars['previous_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['previous'] . ($vars['mode'] == 'form' ? '/edit' : '');
  1037. $vars['next_url'] = $start_path . $vars['node']->nid . '/submission/' . $vars['next'] . ($vars['mode'] == 'form' ? '/edit' : '');
  1038. }
  1039. /**
  1040. * Preprocess function for webform-submission-navigation.tpl.php.
  1041. */
  1042. function template_preprocess_webform_submission_information(&$vars) {
  1043. $vars['account'] = user_load($vars['submission']->uid);
  1044. $vars['actions'] = theme('links', module_invoke_all('webform_submission_actions', $vars['node'], $vars['submission']));
  1045. }