webform.report.inc 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. <?php
  2. /**
  3. * @file
  4. * This file includes helper functions for creating reports for webform.module
  5. *
  6. * @author Nathan Haug <nate@lullabot.com>
  7. */
  8. // All functions within this file need the webform.submissions.inc.
  9. module_load_include('inc', 'webform', 'includes/webform.submissions');
  10. /**
  11. * Retrieve lists of submissions for a given webform.
  12. */
  13. function webform_results_submissions($node, $user_filter, $pager_count) {
  14. global $user;
  15. if (isset($_GET['results']) && is_numeric($_GET['results'])) {
  16. $pager_count = $_GET['results'];
  17. }
  18. $header = theme('webform_results_submissions_header', array('node' => $node));
  19. if ($user_filter) {
  20. if ($user->uid) {
  21. drupal_set_title(t('Submissions for %user', array('%user' => $user->name)), PASS_THROUGH);
  22. }
  23. else {
  24. drupal_set_title(t('Your submissions'));
  25. webform_disable_page_cache();
  26. }
  27. webform_set_breadcrumb($node);
  28. $submissions = webform_get_submissions(array('nid' => $node->nid, 'uid' => $user->uid), $header, $pager_count);
  29. $count = webform_get_submission_count($node->nid, $user->uid);
  30. }
  31. else {
  32. $submissions = webform_get_submissions($node->nid, $header, $pager_count);
  33. $count = webform_get_submission_count($node->nid);
  34. }
  35. $operation_column = end($header);
  36. $operation_total = $operation_column['colspan'];
  37. $rows = array();
  38. foreach ($submissions as $sid => $submission) {
  39. $row = array(
  40. $submission->is_draft ? t('@sid (draft)', array('@sid' => $sid)) : $sid,
  41. format_date($submission->submitted, 'small'),
  42. );
  43. if (webform_results_access($node, $user)) {
  44. $row[] = theme('username', array('account' => $submission));
  45. $row[] = $submission->remote_addr;
  46. }
  47. $row[] = l(t('View'), "node/$node->nid/submission/$sid");
  48. $operation_count = 1;
  49. // No need to call this multiple times, just reference this in a variable.
  50. $destination = drupal_get_destination();
  51. if (webform_submission_access($node, $submission, 'edit', $user)) {
  52. $row[] = l(t('Edit'), "node/$node->nid/submission/$sid/edit", array('query' => $destination));
  53. $operation_count++;
  54. }
  55. if (webform_submission_access($node, $submission, 'delete', $user)) {
  56. $row[] = l(t('Delete'), "node/$node->nid/submission/$sid/delete", array('query' => $destination));
  57. $operation_count++;
  58. }
  59. if ($operation_count < $operation_total) {
  60. $row[count($row) - 1] = array('data' => $row[count($row) - 1], 'colspan' => $operation_total - $operation_count + 1);
  61. }
  62. $rows[] = $row;
  63. }
  64. $element['#theme'] = 'webform_results_submissions';
  65. $element['#node'] = $node;
  66. $element['#submissions'] = $submissions;
  67. $element['#total_count'] = $count;
  68. $element['#pager_count'] = $pager_count;
  69. $element['#attached']['library'][] = array('webform', 'admin');
  70. $element['table']['#theme'] = 'table';
  71. $element['table']['#header'] = $header;
  72. $element['table']['#rows'] = $rows;
  73. $element['table']['#operation_total'] = $operation_total;
  74. return drupal_render($element);
  75. }
  76. /**
  77. * Theme the list of links for selecting the number of results per page.
  78. *
  79. * @param $total_count
  80. * The total number of results available.
  81. * @param $pager_count
  82. * The current number of results displayed per page.
  83. */
  84. function theme_webform_results_per_page($variables) {
  85. $total_count = $variables['total_count'];
  86. $pager_count = $variables['pager_count'];
  87. $output = '';
  88. // Create a list of results-per-page options.
  89. $counts = array(
  90. '20' => '20',
  91. '50' => '50',
  92. '100' => '100',
  93. '200' => '200',
  94. '500' => '500',
  95. '1000' => '1000',
  96. '0' => t('All'),
  97. );
  98. $count_links = array();
  99. foreach ($counts as $number => $text) {
  100. if ($number < $total_count) {
  101. $count_links[] = l($text, $_GET['q'], array('query' => array('results' => $number), 'attributes' => array('class' => array($pager_count == $number ? 'selected' : ''))));
  102. }
  103. }
  104. $output .= '<div class="webform-results-per-page">';
  105. if (count($count_links) > 1) {
  106. $output .= t('Show !count results per page.', array('!count' => implode(' | ', $count_links)));
  107. }
  108. else {
  109. $output .= t('Showing all results.');
  110. }
  111. if ($total_count > 1) {
  112. $output .= ' ' . t('@total results total.', array('@total' => $total_count));
  113. }
  114. $output .= '</div>';
  115. return $output;
  116. }
  117. /**
  118. * Theme the header of the submissions table.
  119. *
  120. * This is done in it's own function so that webform can retrieve the header and
  121. * use it for sorting the results.
  122. */
  123. function theme_webform_results_submissions_header($variables) {
  124. $node = $variables['node'];
  125. $columns = array(
  126. array('data' => t('#'), 'field' => 'sid', 'sort' => 'desc'),
  127. array('data' => t('Submitted'), 'field' => 'submitted'),
  128. );
  129. if (webform_results_access($node)) {
  130. $columns[] = array('data' => t('User'), 'field' => 'name');
  131. $columns[] = array('data' => t('IP Address'), 'field' => 'remote_addr');
  132. }
  133. $columns[] = array('data' => t('Operations'), 'colspan' => module_exists('print') ? 5 : 3);
  134. return $columns;
  135. }
  136. /**
  137. * Preprocess function for webform-results-submissions.tpl.php
  138. */
  139. function template_preprocess_webform_results_submissions(&$vars) {
  140. $vars['node'] = $vars['element']['#node'];
  141. $vars['submissions'] = $vars['element']['#submissions'];
  142. $vars['table'] = $vars['element']['table'];
  143. $vars['total_count'] = $vars['element']['#total_count'];
  144. $vars['pager_count'] = $vars['element']['#pager_count'];
  145. $vars['is_submissions'] = (arg(2) == 'submissions')? 1 : 0;
  146. unset($vars['element']);
  147. }
  148. /**
  149. * Create a table containing all submitted values for a webform node.
  150. */
  151. function webform_results_table($node, $pager_count = 0) {
  152. if (isset($_GET['results']) && is_numeric($_GET['results'])) {
  153. $pager_count = $_GET['results'];
  154. }
  155. // Get all the submissions for the node.
  156. $header = theme('webform_results_table_header', array('node' => $node));
  157. $submissions = webform_get_submissions($node->nid, $header, $pager_count);
  158. $total_count = webform_get_submission_count($node->nid);
  159. $output = theme('webform_results_table', array('node' => $node, 'components' => $node->webform['components'], 'submissions' => $submissions, 'total_count' => $total_count, 'pager_count' => $pager_count));
  160. if ($pager_count) {
  161. $output .= theme('pager');
  162. }
  163. return $output;
  164. }
  165. function theme_webform_results_table_header($variables) {
  166. return array(
  167. array('data' => t('#'), 'field' => 'sid', 'sort' => 'desc'),
  168. array('data' => t('Submitted'), 'field' => 'submitted'),
  169. array('data' => t('User'), 'field' => 'name'),
  170. array('data' => t('IP Address'), 'field' => 'remote_addr'),
  171. );
  172. }
  173. /**
  174. * Theme the results table displaying all the submissions for a particular node.
  175. *
  176. * @param $node
  177. * The node whose results are being displayed.
  178. * @param $components
  179. * An associative array of the components for this webform.
  180. * @param $submissions
  181. * An array of all submissions for this webform.
  182. * @param $total_count
  183. * The total number of submissions to this webform.
  184. * @param $pager_count
  185. * The number of results to be shown per page.
  186. */
  187. function theme_webform_results_table($variables) {
  188. drupal_add_library('webform', 'admin');
  189. $node = $variables['node'];
  190. $components = $variables['components'];
  191. $submissions = $variables['submissions'];
  192. $total_count = $variables['total_count'];
  193. $pager_count = $variables['pager_count'];
  194. $header = array();
  195. $rows = array();
  196. $cell = array();
  197. // This header has to be generated seperately so we can add the SQL necessary.
  198. // to sort the results.
  199. $header = theme('webform_results_table_header', array('node' => $node));
  200. // Generate a row for each submission.
  201. foreach ($submissions as $sid => $submission) {
  202. $cell[] = l($sid, 'node/' . $node->nid . '/submission/' . $sid);
  203. $cell[] = format_date($submission->submitted, 'small');
  204. $cell[] = theme('username', array('account' => $submission));
  205. $cell[] = $submission->remote_addr;
  206. $component_headers = array();
  207. // Generate a cell for each component.
  208. foreach ($node->webform['components'] as $component) {
  209. $data = isset($submission->data[$component['cid']]['value']) ? $submission->data[$component['cid']]['value'] : NULL;
  210. $submission_output = webform_component_invoke($component['type'], 'table', $component, $data);
  211. if ($submission_output !== NULL) {
  212. $component_headers[] = check_plain($component['name']);
  213. $cell[] = $submission_output;
  214. }
  215. }
  216. $rows[] = $cell;
  217. unset($cell);
  218. }
  219. if (!empty($component_headers)) {
  220. $header = array_merge($header, $component_headers);
  221. }
  222. if (count($rows) == 0) {
  223. $rows[] = array(array('data' => t('There are no submissions for this form. <a href="!url">View this form</a>.', array('!url' => url('node/' . $node->nid))), 'colspan' => 4));
  224. }
  225. $output = '';
  226. $output .= theme('webform_results_per_page', array('total_count' => $total_count, 'pager_count' => $pager_count));
  227. $output .= theme('table', array('header' => $header, 'rows' => $rows));
  228. return $output;
  229. }
  230. /**
  231. * Delete all submissions for a node.
  232. *
  233. * @param $nid
  234. * The node id whose submissions will be deleted.
  235. */
  236. function webform_results_clear($nid) {
  237. $node = node_load($nid);
  238. $submissions = webform_get_submissions($nid);
  239. foreach ($submissions as $submission) {
  240. webform_submission_delete($node, $submission);
  241. }
  242. }
  243. /**
  244. * Confirmation form to delete all submissions for a node.
  245. *
  246. * @param $nid
  247. * ID of node for which to clear submissions.
  248. */
  249. function webform_results_clear_form($form, $form_state, $node) {
  250. drupal_set_title(t('Clear Form Submissions'));
  251. $form = array();
  252. $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
  253. $question = t('Are you sure you want to delete all submissions for this form?');
  254. return confirm_form($form, $question, 'node/' . $node->nid . '/webform-results', NULL, t('Clear'), t('Cancel'));
  255. }
  256. function webform_results_clear_form_submit($form, &$form_state) {
  257. webform_results_clear($form_state['values']['nid']);
  258. $node = node_load($form_state['values']['nid']);
  259. $title = $node->title;
  260. $message = t('Webform %title entries cleared.', array('%title' => $title));
  261. drupal_set_message($message);
  262. watchdog('webform', $message);
  263. $form_state['redirect'] = 'node/' . $form_state['values']['nid'] . '/webform-results';
  264. }
  265. /**
  266. * Form to configure the download of CSV files.
  267. */
  268. function webform_results_download_form($form, &$form_state, $node) {
  269. module_load_include('inc', 'webform', 'includes/webform.export');
  270. module_load_include('inc', 'webform', 'includes/webform.components');
  271. $form = array();
  272. $form['node'] = array(
  273. '#type' => 'value',
  274. '#value' => $node,
  275. );
  276. $form['format'] = array(
  277. '#type' => 'radios',
  278. '#title' => t('Export format'),
  279. '#options' => webform_export_list(),
  280. '#default_value' => isset($form_state['values']['format']) ? $form_state['values']['format'] : variable_get('webform_export_format', 'delimited'),
  281. );
  282. $form['delimiter'] = array(
  283. '#type' => 'select',
  284. '#title' => t('Delimited text format'),
  285. '#description' => t('This is the delimiter used in the CSV/TSV file when downloading Webform results. Using tabs in the export is the most reliable method for preserving non-latin characters. You may want to change this to another character depending on the program with which you anticipate importing results.'),
  286. '#default_value' => isset($form_state['values']['delimiter']) ? $form_state['values']['delimiter'] : variable_get('webform_csv_delimiter', '\t'),
  287. '#options' => array(
  288. ',' => t('Comma (,)'),
  289. '\t' => t('Tab (\t)'),
  290. ';' => t('Semicolon (;)'),
  291. ':' => t('Colon (:)'),
  292. '|' => t('Pipe (|)'),
  293. '.' => t('Period (.)'),
  294. ' ' => t('Space ( )'),
  295. ),
  296. );
  297. $form['select_options'] = array(
  298. '#type' => 'fieldset',
  299. '#title' => t('Select list options'),
  300. '#collapsible' => TRUE,
  301. '#collapsed' => TRUE,
  302. );
  303. $form['select_options']['select_keys'] = array(
  304. '#type' => 'radios',
  305. '#title' => t('Select keys'),
  306. '#options' => array(
  307. 0 => t('Full, human-readable options (values)'),
  308. 1 => t('Short, raw options (keys)'),
  309. ),
  310. '#default_value' => isset($form_state['values']['select_options']['select_keys']) ? $form_state['values']['select_options']['select_keys'] : 0,
  311. '#description' => t('Choose which part of options should be displayed from key|value pairs.'),
  312. );
  313. $form['select_options']['select_format'] = array(
  314. '#type' => 'radios',
  315. '#title' => t('Select list format'),
  316. '#options' => array(
  317. 'separate' => t('Separate'),
  318. 'compact' => t('Compact'),
  319. ),
  320. '#default_value' => isset($form_state['values']['select_options']['select_format']) ? $form_state['values']['select_options']['select_format'] : 'separate',
  321. '#attributes' => array('class' => array('webform-select-list-format')),
  322. '#theme' => 'webform_results_download_select_format',
  323. );
  324. $csv_components = array(
  325. 'info' => t('Submission information'),
  326. 'serial' => '-' . t('Submission Number'),
  327. 'sid' => '-' . t('Submission ID'),
  328. 'time' => '-' . t('Time'),
  329. 'draft' => '-' . t('Draft'),
  330. 'ip_address' => '-' . t('IP Address'),
  331. 'uid' => '-' . t('User ID'),
  332. 'username' => '-' . t('Username'),
  333. );
  334. $csv_components += webform_component_list($node, 'csv', TRUE);
  335. $form['components'] = array(
  336. '#type' => 'select',
  337. '#title' => t('Included export components'),
  338. '#options' => $csv_components,
  339. '#default_value' => isset($form_state['values']['components']) ? $form_state['values']['components'] : array_keys($csv_components),
  340. '#multiple' => TRUE,
  341. '#size' => 10,
  342. '#description' => t('The selected components will be included in the export.'),
  343. '#process' => array('webform_component_select'),
  344. );
  345. $form['range'] = array(
  346. '#type' => 'fieldset',
  347. '#title' => t('Download range options'),
  348. '#collapsible' => TRUE,
  349. '#collapsed' => TRUE,
  350. '#tree' => TRUE,
  351. '#theme' => 'webform_results_download_range',
  352. '#element_validate' => array('webform_results_download_range_validate'),
  353. '#after_build' => array('webform_results_download_range_after_build'),
  354. );
  355. $form['range']['range_type'] = array(
  356. '#type' => 'radios',
  357. '#options' => array(
  358. 'all' => t('All submissions'),
  359. 'new' => t('Only new submissions since your last download'),
  360. 'latest' => t('Only the latest'),
  361. 'range' => t('All submissions starting from'),
  362. ),
  363. '#default_value' => 'all',
  364. );
  365. $form['range']['latest'] = array(
  366. '#type' => 'textfield',
  367. '#size' => 5,
  368. '#maxlength' => 8,
  369. '#default_value' => isset($form_state['values']['latest']) ? $form_state['values']['latest'] : '',
  370. );
  371. $form['range']['start'] = array(
  372. '#type' => 'textfield',
  373. '#size' => 5,
  374. '#maxlength' => 8,
  375. '#default_value' => '',
  376. );
  377. $form['range']['end'] = array(
  378. '#type' => 'textfield',
  379. '#size' => 5,
  380. '#maxlength' => 8,
  381. '#default_value' => '',
  382. '#description' => '',
  383. );
  384. // By default results are downloaded. User can override this value if
  385. // programmatically submitting this form.
  386. $form['download'] = array(
  387. '#type' => 'value',
  388. '#default_value' => TRUE
  389. );
  390. $form['submit'] = array(
  391. '#type' => 'submit',
  392. '#value' => t('Download'),
  393. );
  394. return $form;
  395. }
  396. /**
  397. * FormAPI element validate function for the range fieldset.
  398. */
  399. function webform_results_download_range_validate($element, $form_state) {
  400. switch ($element['range_type']['#value']) {
  401. case 'latest':
  402. // Download latest x submissions.
  403. if ($element['latest']['#value'] == '') {
  404. form_error($element['latest'], t('Latest number of submissions field is required.'));
  405. }
  406. else{
  407. if (!is_numeric($element['latest']['#value'])) {
  408. form_error($element['latest'], t('Latest number of submissions must be numeric.'));
  409. }
  410. else{
  411. if ($element['latest']['#value'] <= 0) {
  412. form_error($element['latest'], t('Latest number of submissions must be greater than 0.'));
  413. }
  414. }
  415. }
  416. break;
  417. case 'range':
  418. // Download Start-End range of submissions.
  419. // Start submission number.
  420. if ($element['start']['#value'] == '') {
  421. form_error($element['start'], t('Start submission number is required.'));
  422. }
  423. else{
  424. if (!is_numeric($element['start']['#value'])) {
  425. form_error($element['start'], t('Start submission number must be numeric.'));
  426. }
  427. else{
  428. if ($element['start']['#value'] <= 0) {
  429. form_error($element['start'], t('Start submission number must be greater than 0.'));
  430. }
  431. }
  432. }
  433. // End submission number.
  434. if ($element['end']['#value'] != '') {
  435. if (!is_numeric($element['end']['#value'])) {
  436. form_error($element['end'], t('End submission number must be numeric.'));
  437. }
  438. else{
  439. if ($element['end']['#value'] <= 0) {
  440. form_error($element['end'], t('End submission number must be greater than 0.'));
  441. }
  442. else{
  443. if ($element['end']['#value'] < $element['start']['#value']) {
  444. form_error($element['end'], t('End submission number may not be less than Start submission number.'));
  445. }
  446. }
  447. }
  448. }
  449. break;
  450. }
  451. }
  452. /**
  453. * Validate handler for webform_results_download_form().
  454. */
  455. function webform_results_download_form_submit(&$form, &$form_state) {
  456. $options = array(
  457. 'delimiter' => $form_state['values']['delimiter'],
  458. 'components' => array_keys(array_filter($form_state['values']['components'])),
  459. 'select_keys' => $form_state['values']['select_keys'],
  460. 'select_format' => $form_state['values']['select_format'],
  461. 'range_type' => $form_state['values']['range']['range_type'],
  462. 'download' => $form_state['values']['download'],
  463. );
  464. // Retrieve the list of required SIDs.
  465. if ($options['range_type'] != 'all') {
  466. $options['sids'] = webform_download_sids($form_state['values']['node']->nid, $form_state['values']['range']);
  467. }
  468. $export_info = webform_results_export($form_state['values']['node'], $form_state['values']['format'], $options);
  469. // If webform result file should be downloaded, send the file to the browser,
  470. // otherwise save information about the created file in $form_state.
  471. if ($options['download']) {
  472. webform_results_download($form_state['values']['node'], $export_info);
  473. }
  474. else {
  475. $form_state['export_info'] = $export_info;
  476. }
  477. }
  478. /**
  479. * FormAPI after build function for the download range fieldset.
  480. */
  481. function webform_results_download_range_after_build($element, &$form_state) {
  482. $node = $form_state['values']['node'];
  483. // Build a list of counts of new and total submissions.
  484. $count = webform_get_submission_count($node->nid);
  485. $sids = webform_download_sids($node->nid, array('range_type' => 'new'));
  486. $last_download = webform_download_last_download_info($node->nid);
  487. $element['#webform_download_info']['sid'] = $last_download ? $last_download['sid'] : 0;
  488. $element['#webform_download_info']['requested'] = $last_download ? $last_download['requested'] : $node->created;
  489. $element['#webform_download_info']['total'] = $count;
  490. $element['#webform_download_info']['new'] = count($sids);
  491. return $element;
  492. }
  493. /**
  494. * Theme the output of the export range fieldset.
  495. */
  496. function theme_webform_results_download_range($variables) {
  497. drupal_add_library('webform', 'admin');
  498. $element = $variables['element'];
  499. $download_info = $element['#webform_download_info'];
  500. // Set description for total of all submissions.
  501. $element['range_type']['all']['#theme_wrappers'] = array('webform_inline_radio');
  502. $element['range_type']['all']['#description'] = '(' . t('@count total', array('@count' => $download_info['total'])) . ')';
  503. // Set description for "New submissions since last download".
  504. $format = webform_date_format('short');
  505. $requested_date = format_date($download_info['requested'], 'custom', $format);
  506. $element['range_type']['new']['#theme_wrappers'] = array('webform_inline_radio');
  507. $element['range_type']['new']['#description'] = '(' . t('@count new since @date', array('@count' => $download_info['new'], '@date' => $requested_date)) . ')';
  508. // Disable option if there are no new submissions.
  509. if ($download_info['new'] == 0) {
  510. $element['range_type']['new']['#attributes']['disabled'] = 'disabled';
  511. }
  512. // Render latest x submissions option.
  513. $element['latest']['#attributes']['class'] = array('webform-set-active');
  514. $element['range_type']['latest']['#theme_wrappers'] = array('webform_inline_radio');
  515. $element['range_type']['latest']['#inline_element'] = t('Only the latest !number submissions', array('!number' => drupal_render($element['latest'])));
  516. $element['range_type']['latest']['#title'] = NULL;
  517. // Render Start-End submissions option.
  518. $element['start']['#attributes']['class'] = array('webform-set-active');
  519. $element['end']['#attributes']['class'] = array('webform-set-active');
  520. $element['range_type']['range']['#theme_wrappers'] = array('webform_inline_radio');
  521. $element['range_type']['range']['#inline_element'] = t('All submissions starting from: !start and optionally to: !end', array('!start' => drupal_render($element['start']), '!end' => drupal_render($element['end'])));
  522. $element['range_type']['range']['#title'] = NULL;
  523. $last_sid = $download_info['sid'] ? $download_info['sid'] : drupal_placeholder(t('none'));
  524. $element['range_type']['range']['#description'] = '(' . t('Use submission IDs for the range. Last downloaded end SID: !sid.', array('!sid' => $last_sid)) . ')';
  525. return drupal_render_children($element);
  526. }
  527. /**
  528. * Theme the output of the select list format radio buttons.
  529. */
  530. function theme_webform_results_download_select_format($variables) {
  531. drupal_add_library('webform', 'admin');
  532. $element = $variables['element'];
  533. $output = '';
  534. // Build an example table for the separate option.
  535. $header = array(t('Option A'), t('Option B'), t('Option C'));
  536. $rows = array(
  537. array('X', '', ''),
  538. array('X', '', 'X'),
  539. array('', 'X', 'X'),
  540. );
  541. $element['separate']['#attributes']['class'] = array();
  542. $element['separate']['#description'] = theme('table', array('header' => $header, 'rows' => $rows));
  543. $element['separate']['#description'] .= t('Separate options are more suitable for building reports, graphs, and statistics in a spreadsheet application.');
  544. $output .= drupal_render($element['separate']);
  545. // Build an example table for the compact option.
  546. $header = array(t('My select list'));
  547. $rows = array(
  548. array('Option A'),
  549. array('Option A,Option C'),
  550. array('Option B,Option C'),
  551. );
  552. $element['compact']['#attributes']['class'] = array();
  553. $element['compact']['#description'] = theme('table', array('header' => $header, 'rows' => $rows));
  554. $element['compact']['#description'] .= t('Compact options are more suitable for importing data into other systems.');
  555. $output .= drupal_render($element['compact']);
  556. return $output;
  557. }
  558. /**
  559. * Generate a Excel-readable CSV file containing all submissions for a Webform.
  560. *
  561. * The CSV requires that the data be presented in a flat file. In order
  562. * to maximize usability to the Excel community and minimize subsequent
  563. * stats or spreadsheet programming this program extracts data from the
  564. * various records for a given session and presents them as a single file
  565. * where each row represents a single record.
  566. * The structure of the file is:
  567. * Heading Line 1: Gives group overviews padded by empty cells to the
  568. * next group. A group may be a question and corresponds
  569. * to a component in the webform philosophy. Each group
  570. * overview will have a fixed number of columns beneath it.
  571. * Heading line 2: gives column headings
  572. * Data line 1 .....
  573. * Data line 2 .....
  574. *
  575. * An example of this format is given below. Note the columns have had spaces
  576. * added so the columns line up. This is not the case with actual file where
  577. * a column may be null. Note also, that multiple choice questions as produced
  578. * by checkboxes or radio buttons have been presented as "yes" or "no" and the
  579. * actual choice text is retained only in the header line 2.
  580. * Data from text boxes and input fields are written out in the body of the table.
  581. *
  582. * Submission Details, , , ,Question 1, , ,.., ,Question 2, , ,.., ,Question n
  583. * timestamp ,time,SID,userid,Choice 1 ,Choice 2,Choice 3,..,Choice n,Choice 1 ,Choice 2,Choice 3,..,Choice n,Comment
  584. * 21 Feb 2005 ,1835,23 ,34 ,X , , ,.., ,X ,X ,X ,..,X ,My comment
  585. * 23 Feb 2005 ,1125,24 ,89 ,X ,X , ,.., ,X ,X ,X ,..,X ,Hello
  586. * .................................................................................................................................
  587. * 27 Feb 2005 ,1035,56 ,212 ,X , , ,.., ,X ,X ,X ,..,X ,How is this?
  588. *
  589. */
  590. function webform_results_export($node, $format = 'delimited', $options = array()) {
  591. global $user;
  592. module_load_include('inc', 'webform', 'includes/webform.export');
  593. module_load_include('inc', 'webform', 'includes/webform.components');
  594. $submission_information = array(
  595. 'serial' => t('Serial'),
  596. 'sid' => t('SID'),
  597. 'time' => t('Time'),
  598. 'draft' => t('Draft'),
  599. 'ip_address' => t('IP Address'),
  600. 'uid' => t('UID'),
  601. 'username' => t('Username'),
  602. );
  603. if (empty($options)) {
  604. $options = array(
  605. 'delimiter' => variable_get('webform_csv_delimiter', '\t'),
  606. 'components' => array_merge(array_keys($submission_information), array_keys(webform_component_list($node, 'csv', TRUE))),
  607. 'select_keys' => 0,
  608. 'select_format' => 'separate',
  609. 'range_type' => 'all',
  610. );
  611. }
  612. else {
  613. foreach ($submission_information as $key => $label) {
  614. if (!in_array($key, $options['components'])) {
  615. unset($submission_information[$key]);
  616. }
  617. }
  618. }
  619. // Open a new Webform exporter object.
  620. $exporter = webform_export_create_handler($format, $options);
  621. $file_name = drupal_tempnam('temporary://', 'webform_');
  622. $handle = @fopen($file_name, 'w'); // The @ suppresses errors.
  623. $exporter->bof($handle);
  624. // Fill in the header for the submission information (if any).
  625. $header[2] = $header[1] = $header[0] = count($submission_information) ? array_fill(0, count($submission_information), '') : array();
  626. if (count($submission_information)) {
  627. $header[0][0] = $node->title;
  628. $header[1][0] = t('Submission Details');
  629. foreach (array_values($submission_information) as $column => $label) {
  630. $header[2][$column] = $label;
  631. }
  632. }
  633. // Compile header information for components.
  634. foreach ($options['components'] as $cid) {
  635. if (isset($node->webform['components'][$cid])) {
  636. $component = $node->webform['components'][$cid];
  637. // Let each component determine its headers.
  638. if (webform_component_feature($component['type'], 'csv')) {
  639. $component_header = (array) webform_component_invoke($component['type'], 'csv_headers', $component, $options);
  640. $header[0] = array_merge($header[0], (array) $component_header[0]);
  641. $header[1] = array_merge($header[1], (array) $component_header[1]);
  642. $header[2] = array_merge($header[2], (array) $component_header[2]);
  643. }
  644. }
  645. }
  646. // Add headers to the file.
  647. foreach ($header as $row) {
  648. $exporter->add_row($handle, $row);
  649. }
  650. // Get all the required submissions for the download.
  651. $filters['nid'] = $node->nid;
  652. if (!empty($options['sids'])){
  653. $filters['sid'] = $options['sids'];
  654. }
  655. $submissions = webform_get_submissions($filters);
  656. // Generate a row for each submission.
  657. $row_count = 0;
  658. foreach ($submissions as $sid => $submission) {
  659. $row_count++;
  660. $row = array();
  661. if (isset($submission_information['serial'])) {
  662. $row[] = $row_count;
  663. }
  664. if (isset($submission_information['sid'])) {
  665. $row[] = $sid;
  666. }
  667. if (isset($submission_information['time'])) {
  668. $row[] = format_date($submission->submitted, 'small');
  669. }
  670. if (isset($submission_information['draft'])) {
  671. $row[] = $submission->is_draft;
  672. }
  673. if (isset($submission_information['ip_address'])) {
  674. $row[] = $submission->remote_addr;
  675. }
  676. if (isset($submission_information['uid'])) {
  677. $row[] = $submission->uid;
  678. }
  679. if (isset($submission_information['username'])) {
  680. $row[] = $submission->name;
  681. }
  682. foreach ($options['components'] as $cid) {
  683. if (isset($node->webform['components'][$cid])) {
  684. $component = $node->webform['components'][$cid];
  685. // Let each component add its data.
  686. $raw_data = isset($submission->data[$cid]['value']) ? $submission->data[$cid]['value'] : NULL;
  687. if (webform_component_feature($component['type'], 'csv')) {
  688. $data = webform_component_invoke($component['type'], 'csv_data', $component, $options, $raw_data);
  689. if (is_array($data)) {
  690. $row = array_merge($row, array_values($data));
  691. }
  692. else {
  693. $row[] = isset($data) ? $data : '';
  694. }
  695. }
  696. }
  697. }
  698. // Write data from submissions.
  699. $data = $exporter->add_row($handle, $row);
  700. }
  701. // Add the closing bytes.
  702. $exporter->eof($handle);
  703. // Close the file.
  704. @fclose($handle);
  705. $export_info['options'] = $options;
  706. $export_info['file_name'] = $file_name;
  707. $export_info['exporter'] = $exporter;
  708. $export_info['row_count'] = $row_count;
  709. return $export_info;
  710. }
  711. /**
  712. * Send a generated webform results file to the user's browser.
  713. *
  714. * @param $node
  715. * The webform node.
  716. * @param $export_info
  717. * Export information array retrieved from webform_results_export().
  718. */
  719. function webform_results_download($node, $export_info) {
  720. global $user;
  721. // $exporter, $file_name, $row_count
  722. $export_name = _webform_safe_name($node->title);
  723. $export_info['exporter']->set_headers($export_name);
  724. @readfile($export_info['file_name']); // The @ makes it silent.
  725. @unlink($export_info['file_name']); // Clean up, the @ makes it silent.
  726. // Update user last downloaded sid if required.
  727. if ($options['range_type'] != 'range' && $row_count > 0) {
  728. // Delete existing record.
  729. db_delete('webform_last_download')
  730. ->condition('nid', $node->nid)
  731. ->condition('uid', $user->uid)
  732. ->execute();
  733. // Write new record.
  734. db_insert('webform_last_download')
  735. ->fields(array(
  736. 'nid' => $node->nid,
  737. 'uid' => $user->uid,
  738. 'sid' => $sid,
  739. 'requested' => REQUEST_TIME,
  740. ))
  741. ->execute();
  742. }
  743. exit();
  744. }
  745. /**
  746. * Provides a simple analysis of all submissions to a webform.
  747. *
  748. * @param $node
  749. * The webform node on which to generate the analysis.
  750. * @param $sids
  751. * An array of submission IDs to which this analysis may be filtered. May be
  752. * used to generate results that are per-user or other groups of submissions.
  753. * @param $analysis_component
  754. * A webform component. If passed in, additional information may be returned
  755. * relating specifically to that component's analysis, such as a list of
  756. * "Other" values within a select list.
  757. */
  758. function webform_results_analysis($node, $sids = array(), $analysis_component = NULL) {
  759. if (!is_array($sids)) {
  760. $sids = array();
  761. }
  762. // If showing a component's details, we don't want to loose the menu tabs.
  763. if ($analysis_component) {
  764. $item = menu_get_item('node/' . $node->nid . '/webform-results/analysis');
  765. menu_set_item(NULL, $item);
  766. }
  767. $components = isset($analysis_component) ? array($analysis_component['cid'] => $analysis_component) : $node->webform['components'];
  768. $data = array();
  769. foreach ($components as $cid => $component) {
  770. // Do component specific call.
  771. if ($row_data = webform_component_invoke($component['type'], 'analysis', $component, $sids, isset($analysis_component))) {
  772. $data[$cid] = $row_data;
  773. }
  774. }
  775. return theme('webform_results_analysis', array('node' => $node, 'data' => $data, 'sids' => $sids, 'component' => $analysis_component));
  776. }
  777. /**
  778. * Output the content of the Analysis page.
  779. *
  780. * @see webform_results_analysis()
  781. */
  782. function theme_webform_results_analysis($variables) {
  783. $node = $variables['node'];
  784. $data = $variables['data'];
  785. $sids = $variables['sids'];
  786. $analysis_component = $variables['component'];
  787. $rows = array();
  788. $question_number = 0;
  789. $single = isset($analysis_component);
  790. $header = array(
  791. $single ? $analysis_component['name'] : t('Q'),
  792. array('data' => $single ? '&nbsp;' : t('responses'), 'colspan' => '10')
  793. );
  794. foreach ($data as $cid => $row_data) {
  795. $question_number++;
  796. if (is_array($row_data)) {
  797. $row = array();
  798. if (!$single) {
  799. $row['data'][] = array('data' => '<strong>' . $question_number . '</strong>', 'rowspan' => count($row_data) + 1, 'valign' => 'top');
  800. $row['data'][] = array('data' => '<strong>' . check_plain($node->webform['components'][$cid]['name']) . '</strong>', 'colspan' => '10');
  801. $row['class'][] = 'webform-results-question';
  802. }
  803. $rows = array_merge($rows, array_merge(array($row), $row_data));
  804. }
  805. }
  806. if (count($rows) == 0) {
  807. $rows[] = array(array('data' => t('There are no submissions for this form. <a href="!url">View this form</a>.', array('!url' => url('node/' . $node->nid))), 'colspan' => 20));
  808. }
  809. return theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => array('webform-results-analysis'))));
  810. }
  811. /**
  812. * Given a set of range options, retrieve a set of SIDs for a webform node.
  813. */
  814. function webform_download_sids($nid, $range_options, $uid = NULL) {
  815. $query = db_select('webform_submissions', 'ws')
  816. ->fields('ws', array('sid'))
  817. ->condition('nid', $nid);
  818. switch ($range_options['range_type']) {
  819. case 'all':
  820. // All Submissions.
  821. $query->orderBy('sid', 'ASC');
  822. break;
  823. case 'new':
  824. // All Since Last Download.
  825. $download_info = webform_download_last_download_info($nid, $uid);
  826. $last_sid = $download_info ? $download_info['sid'] : 0;
  827. $query
  828. ->condition('sid', $last_sid, '>')
  829. ->orderBy('sid', 'ASC');
  830. break;
  831. case 'latest':
  832. // Last x Submissions.
  833. $query
  834. ->orderBy('sid', 'DESC')
  835. ->range(0, $range_options['latest']);
  836. break;
  837. case 'range':
  838. // Submissions Start-End.
  839. $query->condition('sid', $range_options['start'], '>=');
  840. if ($range_options['end']){
  841. $query->condition('sid', $range_options['end'], '<=');
  842. }
  843. $query->orderBy('sid', 'ASC');
  844. break;
  845. }
  846. $sids = $query->execute()->fetchCol();
  847. // The last x submissions option has SIDs that are in reverse order.
  848. if ($range_options['range_type'] == 'latest') {
  849. $sids = array_reverse($sids);
  850. }
  851. return $sids;
  852. }
  853. /**
  854. * Get this user's last download information, including the SID and timestamp.
  855. *
  856. * This function provides an array of information about the last download that
  857. * a user had for a particular Webform node. Currently it only returns an array
  858. * with two keys:
  859. * - sid: The last submission ID that was downloaded.
  860. * - requested: The timestamp of the last download request.
  861. *
  862. * @param $nid
  863. * The Webform NID.
  864. * @param $uid
  865. * The user account ID for which to retrieve download information.
  866. * @return
  867. * An array of download information or FALSE if this user has never downloaded
  868. * results for this particular node.
  869. */
  870. function webform_download_last_download_info($nid, $uid = NULL) {
  871. $uid = isset($uid) ? $uid : $GLOBALS['user']->uid;
  872. $info = db_select('webform_last_download', 'wld')
  873. ->fields('wld')
  874. ->condition('nid', $nid)
  875. ->condition('uid', $uid)
  876. ->execute()
  877. ->fetchAssoc();
  878. return $info;
  879. }