time.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <?php
  2. /**
  3. * @file
  4. * Webform module time component.
  5. */
  6. // Time depends on functions provided by date.
  7. webform_component_include('date');
  8. /**
  9. * Implements _webform_defaults_component().
  10. */
  11. function _webform_defaults_time() {
  12. return array(
  13. 'name' => '',
  14. 'form_key' => NULL,
  15. 'pid' => 0,
  16. 'weight' => 0,
  17. 'value' => '',
  18. 'required' => 0,
  19. 'extra' => array(
  20. 'timezone' => 'user',
  21. 'start_time' => '',
  22. 'end_time' => '',
  23. 'hourformat' => '12-hour',
  24. 'minuteincrements' => 1,
  25. 'title_display' => 0,
  26. 'description' => '',
  27. 'description_above' => FALSE,
  28. 'private' => FALSE,
  29. 'analysis' => FALSE,
  30. ),
  31. );
  32. }
  33. /**
  34. * Implements _webform_theme_component().
  35. */
  36. function _webform_theme_time() {
  37. return array(
  38. 'webform_time' => array(
  39. 'render element' => 'element',
  40. 'file' => 'components/time.inc',
  41. ),
  42. 'webform_display_time' => array(
  43. 'render element' => 'element',
  44. 'file' => 'components/time.inc',
  45. ),
  46. );
  47. }
  48. /**
  49. * Implements _webform_edit_component().
  50. */
  51. function _webform_edit_time($component) {
  52. $form = array();
  53. $form['value'] = array(
  54. '#type' => 'textfield',
  55. '#title' => t('Default value'),
  56. '#default_value' => $component['value'],
  57. '#description' => t('The default value of the field.') . '<br />' . t('Accepts a time in any <a href="http://www.gnu.org/software/tar/manual/html_chapter/Date-input-formats.html">GNU Date Input Format</a>. Strings such as now, +2 hours, and 10:30pm are all valid.'),
  58. '#size' => 60,
  59. '#maxlength' => 127,
  60. '#weight' => 0,
  61. );
  62. $form['validation']['start_time'] = array(
  63. '#type' => 'textfield',
  64. '#title' => t('Start time'),
  65. '#default_value' => $component['extra']['start_time'],
  66. '#description' => t('The earliest time that may be entered into the field.'),
  67. '#size' => 10,
  68. '#weight' => 3,
  69. '#parents' => array('extra', 'start_time'),
  70. );
  71. $form['validation']['end_time'] = array(
  72. '#type' => 'textfield',
  73. '#title' => t('End time'),
  74. '#default_value' => $component['extra']['end_time'],
  75. '#description' => t('The latest time that may be entered into the field.'),
  76. '#size' => 10,
  77. '#weight' => 4,
  78. '#parents' => array('extra', 'end_time'),
  79. );
  80. $form['extra']['timezone'] = array(
  81. '#type' => 'radios',
  82. '#title' => t('Default value timezone'),
  83. '#default_value' => $component['extra']['timezone'],
  84. '#description' => t('If using relative dates for a default value (for example, "now") base the current time on this timezone.'),
  85. '#options' => array('user' => t('User timezone'), 'site' => t('Website timezone')),
  86. '#weight' => 2,
  87. '#access' => variable_get('configurable_timezones', 1),
  88. );
  89. $form['display']['hourformat'] = array(
  90. '#type' => 'radios',
  91. '#title' => t('Time format'),
  92. '#default_value' => $component['extra']['hourformat'],
  93. '#options' => array('12-hour' => t('12-hour (am/pm)'), '24-hour' => t('24-hour')),
  94. '#weight' => 2,
  95. '#parents' => array('extra', 'hourformat'),
  96. );
  97. $form['display']['minuteincrements'] = array(
  98. '#type' => 'select',
  99. '#title' => t('Minute increments'),
  100. '#default_value' => $component['extra']['minuteincrements'],
  101. '#options' => array(
  102. 1 => t('1 minute'),
  103. 5 => t('5 minute'),
  104. 10 => t('10 minute'),
  105. 15 => t('15 minute'),
  106. 30 => t('30 minute'),
  107. ),
  108. '#weight' => 3,
  109. '#parents' => array('extra', 'minuteincrements'),
  110. );
  111. $form['#validate'] = array('_webform_edit_time_validate');
  112. return $form;
  113. }
  114. /**
  115. * Implements hook_form_id_validate().
  116. *
  117. * Validate start and end times.
  118. */
  119. function _webform_edit_time_validate($form, &$form_state) {
  120. // Validate that the start and end times are valid. Don't validate the default
  121. // time because with token substitution, it might not be valid at component
  122. // definition time. The end time may be before the start time to facilitate
  123. // time ranges spanning midnight.
  124. foreach (array('start_time', 'end_time') as $field) {
  125. $time[$field] = FALSE;
  126. if (trim($form_state['values']['extra'][$field]) && ($time[$field] = strtotime('1-1-1970 UTC ' . $form_state['values']['extra'][$field])) === FALSE) {
  127. form_set_error("extra][$field", t("The @field isn't a valid time.", array('@field' => $form['validation'][$field]['#title'])));
  128. }
  129. }
  130. }
  131. /**
  132. * Implements _webform_render_component().
  133. */
  134. function _webform_render_time($component, $value = NULL, $filter = TRUE, $submission = NULL) {
  135. $node = isset($component['nid']) ? node_load($component['nid']) : NULL;
  136. $element = array(
  137. '#type' => 'webform_time',
  138. '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
  139. '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
  140. '#required' => $component['required'],
  141. '#weight' => $component['weight'],
  142. '#description' => $filter ? webform_filter_descriptions($component['extra']['description'], $node) : $component['extra']['description'],
  143. '#element_validate' => array('webform_validate_time'),
  144. '#start_time' => trim($component['extra']['start_time']),
  145. '#end_time' => trim($component['extra']['end_time']),
  146. '#hourformat' => $component['extra']['hourformat'],
  147. '#minuteincrements' => $component['extra']['minuteincrements'],
  148. '#default_value' => $filter ? webform_replace_tokens($component['value'], $node) : $component['value'],
  149. '#timezone' => $component['extra']['timezone'],
  150. '#process' => array('webform_expand_time'),
  151. '#theme' => 'webform_time',
  152. '#theme_wrappers' => array('webform_element'),
  153. '#translatable' => array('title', 'description'),
  154. );
  155. // Set the value from Webform if available.
  156. if (!empty($value[0])) {
  157. $element['#default_value'] = $value[0];
  158. }
  159. return $element;
  160. }
  161. /**
  162. * Form API #process function for Webform time fields.
  163. */
  164. function webform_expand_time($element) {
  165. // Expand the default value from a string into an array.
  166. if (!empty($element['#default_value'])) {
  167. // Adjust the time based on the user or site timezone.
  168. if (variable_get('configurable_timezones', 1) && $element['#timezone'] == 'user') {
  169. $timezone_name = isset($GLOBALS['user']->timezone) ? $GLOBALS['user']->timezone : 'UTC';
  170. }
  171. else {
  172. $timezone_name = variable_get('date_default_timezone', 'UTC');
  173. }
  174. $default_values = webform_date_array(webform_strtodate('c', $element['#default_value'], $timezone_name), 'time');
  175. }
  176. else {
  177. $default_values = array(
  178. 'hour' => '',
  179. 'minute' => '',
  180. 'second' => '',
  181. );
  182. }
  183. $start_hour = $element['#start_time'] ? date('G', strtotime('1-1-1970 ' . $element['#start_time'])) : FALSE;
  184. $end_hour = $element['#end_time'] ? date('G', strtotime('1-1-1970 ' . $element['#end_time'])) : FALSE;
  185. $reduced_range = ($start_hour !== FALSE && $start_hour > 0) || ($end_hour !== FALSE && $end_hour < 23);
  186. $format_12_hour = $element['#hourformat'] == '12-hour';
  187. // Generate the choices for the hour drop-down select.
  188. $hours = $format_12_hour && !$reduced_range ? array_slice(range(0, 12), 1, 12, TRUE) : range(0, 23);
  189. if ($format_12_hour && $reduced_range) {
  190. $hours = array_map(function ($hour) {
  191. return (1 + ($hour + 11) % 12) . ($hour < 12 ? ' am' : ' pm');
  192. }, $hours);
  193. }
  194. // Prune the hours to the allowed range.
  195. if ($reduced_range) {
  196. // $start_hour of FALSE type-juggles nicely to 0.
  197. $end_hour = $end_hour === FALSE ? 23 : $end_hour;
  198. if ($start_hour <= $end_hour) {
  199. $hours = array_intersect_key($hours, array_flip(range($start_hour, $end_hour)));
  200. }
  201. else {
  202. $hours = array_intersect_key($hours, array_flip(range($start_hour, 23))) +
  203. array_intersect_key($hours, array_flip(range(0, $end_hour)));
  204. }
  205. }
  206. // Generate the choices for the minute drop-down select.
  207. $minutes = range(0, 59, $element['#minuteincrements']);
  208. $minutes = array_combine($minutes, array_map(function ($minute) {
  209. return substr('00' . $minute, -2);
  210. }, $minutes));
  211. // Add the labels to the drop-down selects.
  212. $hours = array('' => t('Hour')) + $hours;
  213. $minutes = array('' => t('Minute')) + $minutes;
  214. // Adjust the default for minutes if needed, rounding down if needed.
  215. // Rounding down eliminate the problem of rounding up going to the next hour.
  216. // Worse, rounding 23:59 up would actually be the next day, which can't be
  217. // represented because time components aren't linked to date components.
  218. if (!isset($minutes[$default_values['minute']])) {
  219. $default_values['minute'] -= $default_values['minute'] % $element['#minuteincrements'];
  220. }
  221. // Set the overall default value.
  222. if ($default_values['hour'] !== '') {
  223. $element['#default_value'] = webform_date_string($default_values);
  224. }
  225. // Convert default to 12-hour if needed.
  226. if ($format_12_hour && !$reduced_range) {
  227. $default_values = webform_time_convert($default_values, '12-hour');
  228. }
  229. $element['hour'] = array(
  230. '#prefix' => '',
  231. '#type' => 'select',
  232. '#title' => t('Hour'),
  233. '#title_display' => 'invisible',
  234. '#default_value' => $default_values['hour'],
  235. '#options' => $hours,
  236. );
  237. $element['minute'] = array(
  238. '#prefix' => ':',
  239. '#type' => 'select',
  240. '#title' => t('Minute'),
  241. '#title_display' => 'invisible',
  242. '#default_value' => $default_values['minute'],
  243. '#options' => $minutes,
  244. );
  245. if ($format_12_hour && !$reduced_range) {
  246. $element['ampm'] = array(
  247. '#type' => 'radios',
  248. '#default_value' => $default_values['ampm'] ? $default_values['ampm'] : 'am',
  249. '#options' => array('am' => t('am'), 'pm' => t('pm')),
  250. );
  251. }
  252. return $element;
  253. }
  254. /**
  255. * Theme a webform time element.
  256. */
  257. function theme_webform_time($variables) {
  258. $element = $variables['element'];
  259. $element['hour']['#attributes']['class'][] = 'hour';
  260. $element['minute']['#attributes']['class'][] = 'minute';
  261. // Add error classes to all items within the element.
  262. if (form_get_error($element)) {
  263. $element['hour']['#attributes']['class'][] = 'error';
  264. $element['minute']['#attributes']['class'][] = 'error';
  265. }
  266. // Add HTML5 required attribute, if needed.
  267. if ($element['#required']) {
  268. $element['hour']['#attributes']['required'] = 'required';
  269. $element['minute']['#attributes']['required'] = 'required';
  270. if (!empty($element['ampm'])) {
  271. $element['ampm']['am']['#attributes']['required'] = 'required';
  272. $element['ampm']['pm']['#attributes']['required'] = 'required';
  273. }
  274. }
  275. $output = '<div class="webform-container-inline">' . drupal_render($element['hour']) . drupal_render($element['minute']) . drupal_render($element['ampm']) . '</div>';
  276. return $output;
  277. }
  278. /**
  279. * Validate that the time data is valid, calling form_error() if not.
  280. */
  281. function webform_validate_time($element, $form_state) {
  282. // Check if the user filled the required fields.
  283. if ($element['#required']) {
  284. foreach (array('hour', 'minute', 'ampm') as $field_type) {
  285. if (isset($element[$field_type]) && $element[$field_type]['#value'] === '') {
  286. form_error($element, t('!name field is required.', array('!name' => $element['#title'])));
  287. return;
  288. }
  289. }
  290. }
  291. // Check for a valid time. Allow a minute with no hour as "no time set".
  292. if ($element['hour']['#value'] !== '') {
  293. if (!is_numeric($element['hour']['#value']) || !is_numeric($element['minute']['#value']) || (isset($element['ampm']) && $element['ampm']['#value'] === '')) {
  294. form_error($element, t('Entered !name is not a valid time.', array('!name' => $element['#title'])));
  295. return;
  296. }
  297. // Enforce the start and end times, if any.
  298. $timestamp = strtotime($element['hour']['#value'] . ':' . $element['minute']['#value'] . ' ' .
  299. (isset($element['ampm']) ? $element['ampm']['#value'] : ''));
  300. $start_time = strtotime($element['#start_time']);
  301. $end_time = strtotime($element['#end_time']);
  302. $subs = array(
  303. '@start_time' => $element['#start_time'],
  304. '@end_time' => $element['#end_time'],
  305. );
  306. if ($start_time !== FALSE && $end_time !== FALSE && $start_time > $end_time) {
  307. // Validate as "over midnight" date range.
  308. if ($end_time < $timestamp && $timestamp < $start_time) {
  309. form_error($element, t('The entered time must be from @start_time to midnight to @end_time.', $subs));
  310. }
  311. }
  312. else {
  313. // Validate the start and end times are a regular (over noon) time range.
  314. if ($start_time !== FALSE && $timestamp < $start_time) {
  315. form_error($element, t('The entered time must be no earlier than @start_time.', $subs));
  316. }
  317. if ($end_time !== FALSE && $timestamp > $end_time) {
  318. form_error($element, t('The entered time must be no later than @end_time.', $subs));
  319. }
  320. }
  321. }
  322. }
  323. /**
  324. * Implements _webform_submit_component().
  325. */
  326. function _webform_submit_time($component, $value) {
  327. // Convert to 24-hour time before string conversion.
  328. if ($component['extra']['hourformat'] == '12-hour') {
  329. $value = webform_time_convert($value, '24-hour');
  330. }
  331. // Convert the value into a ISO 8601 string.
  332. return $value['hour'] !== '' ? webform_date_string($value, 'time') : '';
  333. }
  334. /**
  335. * Implements _webform_display_component().
  336. */
  337. function _webform_display_time($component, $value, $format = 'html', $submission = array()) {
  338. $value = webform_date_array(isset($value[0]) ? $value[0] : '', 'time');
  339. if ($component['extra']['hourformat'] == '12-hour') {
  340. $value = webform_time_convert($value, '12-hour');
  341. }
  342. return array(
  343. '#title' => $component['name'],
  344. '#title_display' => $component['extra']['title_display'] ? $component['extra']['title_display'] : 'before',
  345. '#weight' => $component['weight'],
  346. '#theme' => 'webform_display_time',
  347. '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
  348. '#format' => $format,
  349. '#hourformat' => $component['extra']['hourformat'],
  350. '#value' => $value,
  351. '#translatable' => array('title'),
  352. );
  353. }
  354. /**
  355. * Format the output of data for this component.
  356. */
  357. function theme_webform_display_time($variables) {
  358. $element = $variables['element'];
  359. $output = ' ';
  360. if (isset($element['#value']['hour']) && $element['#value']['hour'] !== '' && isset($element['#value']['minute']) && $element['#value']['minute'] !== '') {
  361. if ($element['#hourformat'] == '24-hour') {
  362. $output = sprintf('%02d', $element['#value']['hour']) . ':' . sprintf('%02d', $element['#value']['minute']);
  363. }
  364. else {
  365. $output = $element['#value']['hour'] . ':' . sprintf('%02d', $element['#value']['minute']) . ' ' . $element['#value']['ampm'];
  366. }
  367. }
  368. return $output;
  369. }
  370. /**
  371. * Implements _webform_analysis_component().
  372. */
  373. function _webform_analysis_time($component, $sids = array(), $single = FALSE, $join = NULL) {
  374. $query = db_select('webform_submitted_data', 'wsd', array('fetch' => PDO::FETCH_ASSOC))
  375. ->fields('wsd', array('no', 'data'))
  376. ->condition('wsd.nid', $component['nid'])
  377. ->condition('wsd.cid', $component['cid'])
  378. ->orderBy('wsd.sid');
  379. if (count($sids)) {
  380. $query->condition('wsd.sid', $sids, 'IN');
  381. }
  382. if ($join) {
  383. $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
  384. }
  385. $result = $query->execute();
  386. $times = array();
  387. $submissions = 0;
  388. foreach ($result as $row) {
  389. $submissions++;
  390. if ($row['data']) {
  391. $times[] = webform_date_array($row['data']);
  392. }
  393. }
  394. // Display stats.
  395. $nonblanks = count($times);
  396. $rows[0] = array(t('Left Blank'), ($submissions - $nonblanks));
  397. $rows[1] = array(t('User entered value'), $nonblanks);
  398. return array(
  399. 'table_rows' => $rows,
  400. );
  401. }
  402. /**
  403. * Implements _webform_table_component().
  404. */
  405. function _webform_table_time($component, $value) {
  406. if ($value[0]) {
  407. $time = webform_date_array($value[0], 'time');
  408. if ($component['extra']['hourformat'] == '24-hour') {
  409. return sprintf('%02d', $time['hour']) . ':' . sprintf('%02d', $time['minute']);
  410. }
  411. else {
  412. $time = webform_time_convert($time, '12-hour');
  413. return $time['hour'] . ':' . sprintf('%02d', $time['minute']) . ' ' . $time['ampm'];
  414. }
  415. }
  416. else {
  417. return '';
  418. }
  419. }
  420. /**
  421. * Implements _webform_csv_headers_component().
  422. */
  423. function _webform_csv_headers_time($component, $export_options) {
  424. $header = array();
  425. $header[0] = '';
  426. $header[1] = '';
  427. $header[2] = $export_options['header_keys'] ? $component['form_key'] : $component['name'];
  428. return $header;
  429. }
  430. /**
  431. * Implements _webform_csv_data_component().
  432. */
  433. function _webform_csv_data_time($component, $export_options, $value) {
  434. if ($value[0]) {
  435. $time = webform_date_array($value[0], 'time');
  436. // An ISO 8601 time is the same as 24-hour time.
  437. if (!empty($export_options['iso8601_time']) || $component['extra']['hourformat'] == '24-hour') {
  438. return sprintf('%02d', $time['hour']) . ':' . sprintf('%02d', $time['minute']);
  439. }
  440. else {
  441. $time = webform_time_convert($time, '12-hour');
  442. return $time['hour'] . ':' . sprintf('%02d', $time['minute']) . ' ' . $time['ampm'];
  443. }
  444. }
  445. else {
  446. return '';
  447. }
  448. }
  449. /**
  450. * Convert a time between a 24-hour and a 12-hour value.
  451. *
  452. * @param array $array
  453. * An array of hour, minute, second, and optionally ampm.
  454. * @param string $format
  455. * Either 12-hour or 24-hour.
  456. *
  457. * @return array
  458. * An array with hour, minute, second, and ampm (if using "12-hour").
  459. */
  460. function webform_time_convert($array, $format) {
  461. if ($array['hour'] !== '') {
  462. if ($format == '12-hour') {
  463. $array['ampm'] = ($array['hour'] >= 12 && $array['hour'] < 24) ? 'pm' : 'am';
  464. $array['hour'] = ($array['hour'] > 12 || $array['hour'] == 0) ? abs($array['hour'] - 12) : (int) $array['hour'];
  465. }
  466. elseif ($format == '24-hour' && isset($array['ampm'])) {
  467. $array['hour'] = ($array['hour'] < 12 && $array['ampm'] == 'pm') ? $array['hour'] + 12 : (int) $array['hour'];
  468. $array['hour'] = ($array['hour'] == 12 && $array['ampm'] == 'am') ? 0 : $array['hour'];
  469. }
  470. }
  471. if ($format == '12-hour' && !isset($array['ampm'])) {
  472. $array['ampm'] = '';
  473. }
  474. elseif ($format == '24-hour' && isset($array['ampm'])) {
  475. unset($array['ampm']);
  476. }
  477. return $array;
  478. }