Projet

Général

Profil

Paste
Télécharger (142 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / webform / webform.module @ a2baadd1

1
<?php
2

    
3
/**
4
 * This module provides a simple way to create forms and questionnaires.
5
 *
6
 * The initial development of this module was sponsered by ÅF Industri AB, Open
7
 * Source City and Karlstad University Library. Continued development sponsored
8
 * by Lullabot.
9
 *
10
 * @author Nathan Haug <nate@lullabot.com>
11
 */
12

    
13
/**
14
 * Implements hook_help().
15
 */
16
function webform_help($section = 'admin/help#webform', $arg = NULL) {
17
  $output = '';
18
  switch ($section) {
19
    case 'admin/config/content/webform':
20
      module_load_include('inc', 'webform', 'includes/webform.admin');
21
      $type_list = webform_admin_type_list();
22
      $output = t('Webform enables nodes to have attached forms and questionnaires.');
23
      if ($type_list) {
24
        $output .= ' ' . t('To add one, create a !types piece of content.', array('!types' => $type_list));
25
      }
26
      else {
27
        $output .= ' <strong>' . t('Webform is currently not enabled on any content types.') . '</strong> ' . t('To use Webform, please enable it on at least one content type on this page.');
28
      }
29
      $output = '<p>' . $output . '</p>';
30
      break;
31
    case 'admin/content/webform':
32
      $output = '<p>' . t('This page lists all of the content on the site that may have a webform attached to it.') . '</p>';
33
      break;
34
    case 'admin/help#webform':
35
      module_load_include('inc', 'webform', 'includes/webform.admin');
36
      $types = webform_admin_type_list();
37
      if (empty($types)) {
38
        $types = t('Webform-enabled piece of content');
39
        $types_message = t('Webform is currently not enabled on any content types.') . ' ' . t('Visit the <a href="!url">Webform settings</a> page and enable Webform on at least one content type.', array('!url' => url('admin/config/content/webform')));
40
      }
41
      else {
42
        $types_message = t('Optional: Enable Webform on multiple types by visiting the <a href="!url">Webform settings</a> page.', array('!url' => url('admin/config/content/webform')));
43
      }
44
      $output = t("<p>This module lets you create forms or questionnaires and define their content. Submissions from these forms are stored in the database and optionally also sent by e-mail to a predefined address.</p>
45
      <p>Here is how to create one:</p>
46
      <ul>
47
        <li>!webform-types-message</li>
48
        <li>Go to <a href=\"!create-content\">Create content</a> and add a !types piece of content.</li>
49
        <li>After saving the new content, you will be redirected to the main field list of the form that will be created. Add the fields you would like on your form.</li>
50
        <li>Once finished adding fields, you may want to send e-mails to administrators or back to the user who filled out the form. Click on the <em>Emails</em> sub-tab underneath the <em>Webform</em> tab on the piece of content.</li>
51
        <li>Finally, visit the <em>Form settings</em> sub-tab under the <em>Webform</em> tab to configure remaining configurations options for your form.
52
          <ul>
53
          <li>Add a confirmation message and/or redirect URL that is to be displayed after successful submission.</li>
54
          <li>Set a submission limit.</li>
55
          <li>Determine which roles may submit the form.</li>
56
          <li>Advanced configuration options such as allowing drafts or show users a message indicating how they can edit their submissions.</li>
57
          </ul>
58
        </li>
59
        <li>Your form is now ready for viewing. After receiving submissions, you can check the results users have submitted by visiting the <em>Results</em> tab on the piece of content.</li>
60
      </ul>
61
      <p>Help on adding and configuring the components will be shown after you add your first component.</p>
62
      ", array('!webform-types-message' => $types_message, '!create-content' => url('node/add'), '!types' => $types));
63
      break;
64
    case 'node/%/submission/%/resend':
65
      $output .= '<p>' . t('This form may be used to resend e-mails configured for this webform. Check the e-mails that need to be sent and click <em>Resend e-mails</em> to send these e-mails again.') . '</p>';
66
      break;
67
  }
68

    
69
  return $output;
70
}
71

    
72
/**
73
 * Implements hook_menu().
74
 */
75
function webform_menu() {
76
  $items = array();
77

    
78
  // Submissions listing.
79
  $items['admin/content/webform'] = array(
80
    'title' => 'Webforms',
81
    'page callback' => 'webform_admin_content',
82
    'access callback' => 'user_access',
83
    'access arguments' => array('access all webform results'),
84
    'description' => 'View and edit all the available webforms on your site.',
85
    'file' => 'includes/webform.admin.inc',
86
    'type' => MENU_LOCAL_TASK,
87
  );
88

    
89
  // Admin Settings.
90
  $items['admin/config/content/webform'] = array(
91
    'title' => 'Webform settings',
92
    'page callback' => 'drupal_get_form',
93
    'page arguments' => array('webform_admin_settings'),
94
    'access callback' => 'user_access',
95
    'access arguments' => array('administer site configuration'),
96
    'description' => 'Global configuration of webform functionality.',
97
    'file' => 'includes/webform.admin.inc',
98
    'type' => MENU_NORMAL_ITEM,
99
  );
100

    
101
  // Node page tabs.
102
  $items['node/%webform_menu/done'] = array(
103
    'title' => 'Webform confirmation',
104
    'page callback' => '_webform_confirmation',
105
    'page arguments' => array(1),
106
    'access callback' => 'node_access',
107
    'access arguments' => array('view', 1),
108
    'type' => MENU_CALLBACK,
109
  );
110
  $items['node/%webform_menu/webform'] = array(
111
    'title' => 'Webform',
112
    'page callback' => 'webform_components_page',
113
    'page arguments' => array(1),
114
    'access callback' => 'node_access',
115
    'access arguments' => array('update', 1),
116
    'file' => 'includes/webform.components.inc',
117
    'weight' => 1,
118
    'type' => MENU_LOCAL_TASK,
119
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
120
  );
121
  $items['node/%webform_menu/webform/components'] = array(
122
    'title' => 'Form components',
123
    'page callback' => 'webform_components_page',
124
    'page arguments' => array(1),
125
    'access callback' => 'node_access',
126
    'access arguments' => array('update', 1),
127
    'file' => 'includes/webform.components.inc',
128
    'weight' => 0,
129
    'type' => MENU_DEFAULT_LOCAL_TASK,
130
  );
131
  $items['node/%webform_menu/webform/configure'] = array(
132
    'title' => 'Form settings',
133
    'page callback' => 'drupal_get_form',
134
    'page arguments' => array('webform_configure_form', 1),
135
    'access callback' => 'node_access',
136
    'access arguments' => array('update', 1),
137
    'file' => 'includes/webform.pages.inc',
138
    'weight' => 2,
139
    'type' => MENU_LOCAL_TASK,
140
  );
141

    
142
  // Node e-mail forms.
143
  $items['node/%webform_menu/webform/emails'] = array(
144
    'title' => 'E-mails',
145
    'page callback' => 'drupal_get_form',
146
    'page arguments' => array('webform_emails_form', 1),
147
    'access callback' => 'node_access',
148
    'access arguments' => array('update', 1),
149
    'file' => 'includes/webform.emails.inc',
150
    'weight' => 1,
151
    'type' => MENU_LOCAL_TASK,
152
  );
153
  $items['node/%webform_menu/webform/emails/%webform_menu_email'] = array(
154
    'title' => 'Edit e-mail settings',
155
    'load arguments' => array(1),
156
    'page arguments' => array('webform_email_edit_form', 1, 4),
157
    'access callback' => 'node_access',
158
    'access arguments' => array('update', 1),
159
    'file' => 'includes/webform.emails.inc',
160
    'type' => MENU_LOCAL_TASK,
161
  );
162
  $items['node/%webform_menu/webform/emails/%webform_menu_email/delete'] = array(
163
    'title' => 'Delete e-mail settings',
164
    'load arguments' => array(1),
165
    'page arguments' => array('webform_email_delete_form', 1, 4),
166
    'access callback' => 'node_access',
167
    'access arguments' => array('update', 1),
168
    'type' => MENU_LOCAL_TASK,
169
  );
170

    
171
  // Node component forms.
172
  $items['node/%webform_menu/webform/components/%webform_menu_component'] = array(
173
    'load arguments' => array(1, 5),
174
    'page callback' => 'drupal_get_form',
175
    'page arguments' => array('webform_component_edit_form', 1, 4, FALSE),
176
    'access callback' => 'node_access',
177
    'access arguments' => array('update', 1),
178
    'file' => 'includes/webform.components.inc',
179
    'type' => MENU_LOCAL_TASK,
180
  );
181
  $items['node/%webform_menu/webform/components/%webform_menu_component/clone'] = array(
182
    'load arguments' => array(1, 5),
183
    'page callback' => 'drupal_get_form',
184
    'page arguments' => array('webform_component_edit_form', 1, 4, TRUE),
185
    'access callback' => 'node_access',
186
    'access arguments' => array('update', 1),
187
    'file' => 'includes/webform.components.inc',
188
    'type' => MENU_LOCAL_TASK,
189
  );
190
  $items['node/%webform_menu/webform/components/%webform_menu_component/delete'] = array(
191
    'load arguments' => array(1, 5),
192
    'page callback' => 'drupal_get_form',
193
    'page arguments' => array('webform_component_delete_form', 1, 4),
194
    'access callback' => 'node_access',
195
    'access arguments' => array('update', 1),
196
    'file' => 'includes/webform.components.inc',
197
    'type' => MENU_LOCAL_TASK,
198
  );
199

    
200
  // AJAX callback for loading select list options.
201
  $items['webform/ajax/options/%webform_menu'] = array(
202
    'load arguments' => array(3),
203
    'page callback' => 'webform_select_options_ajax',
204
    'access callback' => 'node_access',
205
    'access arguments' => array('update', 3),
206
    'file' => 'components/select.inc',
207
    'type' => MENU_CALLBACK,
208
  );
209

    
210
  // Node webform results.
211
  $items['node/%webform_menu/webform-results'] = array(
212
    'title' => 'Results',
213
    'page callback' => 'webform_results_submissions',
214
    'page arguments' => array(1, FALSE, '50'),
215
    'access callback' => 'webform_results_access',
216
    'access arguments' => array(1),
217
    'file' => 'includes/webform.report.inc',
218
    'weight' => 2,
219
    'type' => MENU_LOCAL_TASK,
220
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
221
  );
222
  $items['node/%webform_menu/webform-results/submissions'] = array(
223
    'title' => 'Submissions',
224
    'page callback' => 'webform_results_submissions',
225
    'page arguments' => array(1, FALSE, '50'),
226
    'access callback' => 'webform_results_access',
227
    'access arguments' => array(1),
228
    'file' => 'includes/webform.report.inc',
229
    'weight' => 4,
230
    'type' => MENU_DEFAULT_LOCAL_TASK,
231
  );
232
  $items['node/%webform_menu/webform-results/analysis'] = array(
233
    'title' => 'Analysis',
234
    'page callback' => 'webform_results_analysis',
235
    'page arguments' => array(1),
236
    'access callback' => 'webform_results_access',
237
    'access arguments' => array(1),
238
    'file' => 'includes/webform.report.inc',
239
    'weight' => 5,
240
    'type' => MENU_LOCAL_TASK,
241
  );
242
  $items['node/%webform_menu/webform-results/analysis/%webform_menu_component'] = array(
243
    'title' => 'Analysis',
244
    'load arguments' => array(1, 4),
245
    'page callback' => 'webform_results_analysis',
246
    'page arguments' => array(1, array(), 4),
247
    'access callback' => 'webform_results_access',
248
    'access arguments' => array(1),
249
    'file' => 'includes/webform.report.inc',
250
    'type' => MENU_CALLBACK,
251
  );
252
  $items['node/%webform_menu/webform-results/table'] = array(
253
    'title' => 'Table',
254
    'page callback' => 'webform_results_table',
255
    'page arguments' => array(1, '50'),
256
    'access callback' => 'webform_results_access',
257
    'access arguments' => array(1),
258
    'file' => 'includes/webform.report.inc',
259
    'weight' => 6,
260
    'type' => MENU_LOCAL_TASK,
261
  );
262
  $items['node/%webform_menu/webform-results/download'] = array(
263
    'title' => 'Download',
264
    'page callback' => 'drupal_get_form',
265
    'page arguments' => array('webform_results_download_form', 1),
266
    'access callback' => 'webform_results_access',
267
    'access arguments' => array(1),
268
    'file' => 'includes/webform.report.inc',
269
    'weight' => 7,
270
    'type' => MENU_LOCAL_TASK,
271
  );
272
  $items['node/%webform_menu/webform-results/clear'] = array(
273
    'title' => 'Clear',
274
    'page callback' => 'drupal_get_form',
275
    'page arguments' => array('webform_results_clear_form', 1),
276
    'access callback' => 'webform_results_clear_access',
277
    'access arguments' => array(1),
278
    'file' => 'includes/webform.report.inc',
279
    'weight' => 8,
280
    'type' => MENU_LOCAL_TASK,
281
  );
282

    
283
  // Node submissions.
284
  $items['node/%webform_menu/submissions'] = array(
285
    'title' => 'Submissions',
286
    'page callback' => 'webform_results_submissions',
287
    'page arguments' => array(1, TRUE, '50'),
288
    'access callback' => 'webform_submission_access',
289
    'access arguments' => array(1, NULL, 'list'),
290
    'file' => 'includes/webform.report.inc',
291
    'type' => MENU_CALLBACK,
292
  );
293
  $items['node/%webform_menu/submission/%webform_menu_submission'] = array(
294
    'title' => 'Webform submission',
295
    'load arguments' => array(1),
296
    'page callback' => 'webform_submission_page',
297
    'page arguments' => array(1, 3, 'html'),
298
    'title callback' => 'webform_submission_title',
299
    'title arguments' => array(1, 3),
300
    'access callback' => 'webform_submission_access',
301
    'access arguments' => array(1, 3, 'view'),
302
    'file' => 'includes/webform.submissions.inc',
303
    'type' => MENU_CALLBACK,
304
  );
305
  $items['node/%webform_menu/submission/%webform_menu_submission/view'] = array(
306
    'title' => 'View',
307
    'load arguments' => array(1),
308
    'page callback' => 'webform_submission_page',
309
    'page arguments' => array(1, 3, 'html'),
310
    'access callback' => 'webform_submission_access',
311
    'access arguments' => array(1, 3, 'view'),
312
    'weight' => 0,
313
    'file' => 'includes/webform.submissions.inc',
314
    'type' => MENU_DEFAULT_LOCAL_TASK,
315
  );
316
  $items['node/%webform_menu/submission/%webform_menu_submission/edit'] = array(
317
    'title' => 'Edit',
318
    'load arguments' => array(1),
319
    'page callback' => 'webform_submission_page',
320
    'page arguments' => array(1, 3, 'form'),
321
    'access callback' => 'webform_submission_access',
322
    'access arguments' => array(1, 3, 'edit'),
323
    'weight' => 1,
324
    'file' => 'includes/webform.submissions.inc',
325
    'type' => MENU_LOCAL_TASK,
326
  );
327
  $items['node/%webform_menu/submission/%webform_menu_submission/delete'] = array(
328
    'title' => 'Delete',
329
    'load arguments' => array(1),
330
    'page callback' => 'drupal_get_form',
331
    'page arguments' => array('webform_submission_delete_form', 1, 3),
332
    'access callback' => 'webform_submission_access',
333
    'access arguments' => array(1, 3, 'delete'),
334
    'weight' => 2,
335
    'file' => 'includes/webform.submissions.inc',
336
    'type' => MENU_LOCAL_TASK,
337
  );
338
  $items['node/%webform_menu/submission/%webform_menu_submission/resend'] = array(
339
    'title' => 'Resend e-mails',
340
    'load arguments' => array(1),
341
    'page callback' => 'drupal_get_form',
342
    'page arguments' => array('webform_submission_resend', 1, 3),
343
    'access callback' => 'webform_results_access',
344
    'access arguments' => array(1),
345
    'file' => 'includes/webform.submissions.inc',
346
    'type' => MENU_CALLBACK,
347
  );
348

    
349
  return $items;
350
}
351

    
352
/**
353
 * Menu loader callback. Load a webform node if the given nid is a webform.
354
 */
355
function webform_menu_load($nid) {
356
  if (!is_numeric($nid)) {
357
    return FALSE;
358
  }
359
  $node = node_load($nid);
360
  if (!isset($node->type) || !in_array($node->type, webform_variable_get('webform_node_types'))) {
361
    return FALSE;
362
  }
363
  return $node;
364
}
365

    
366
/**
367
 * Menu loader callback. Load a webform submission if the given sid is a valid.
368
 */
369
function webform_menu_submission_load($sid, $nid) {
370
  module_load_include('inc', 'webform', 'includes/webform.submissions');
371
  $submission = webform_get_submission($nid, $sid);
372
  return empty($submission) ? FALSE : $submission;
373
}
374

    
375
/**
376
 * Menu loader callback. Load a webform component if the given cid is a valid.
377
 */
378
function webform_menu_component_load($cid, $nid, $type) {
379
  module_load_include('inc', 'webform', 'includes/webform.components');
380
  if ($cid == 'new') {
381
    $components = webform_components();
382
    $component = in_array($type, array_keys($components)) ? array('type' => $type, 'nid' => $nid, 'name' => $_GET['name'], 'mandatory' => $_GET['mandatory'], 'pid' => $_GET['pid'], 'weight' => $_GET['weight']) : FALSE;
383
  }
384
  else {
385
    $node = node_load($nid);
386
    $component = isset($node->webform['components'][$cid]) ? $node->webform['components'][$cid] : FALSE;
387
  }
388
  if ($component) {
389
    webform_component_defaults($component);
390
  }
391
  return $component;
392
}
393

    
394

    
395
/**
396
 * Menu loader callback. Load a webform e-mail if the given eid is a valid.
397
 */
398
function webform_menu_email_load($eid, $nid) {
399
  module_load_include('inc', 'webform', 'includes/webform.emails');
400
  $node = node_load($nid);
401
  $email = webform_email_load($eid, $nid);
402
  if ($eid == 'new') {
403
    if (isset($_GET['option']) && isset($_GET['email'])) {
404
      $type = $_GET['option'];
405
      if ($type == 'custom') {
406
        $email['email'] = $_GET['email'];
407
      }
408
      elseif ($type == 'component' && isset($node->webform['components'][$_GET['email']])) {
409
        $email['email'] = $_GET['email'];
410
      }
411
    }
412
  }
413

    
414
  return $email;
415
}
416

    
417
function webform_submission_access($node, $submission, $op = 'view', $account = NULL) {
418
  global $user;
419
  $account = isset($account) ? $account : $user;
420

    
421
  $access_all = user_access('access all webform results', $account);
422
  $access_own_submission = isset($submission) && user_access('access own webform submissions', $account) && (($account->uid && $account->uid == $submission->uid) || isset($_SESSION['webform_submission'][$submission->sid]));
423
  $access_node_submissions = user_access('access own webform results', $account) && $account->uid == $node->uid;
424

    
425
  $general_access = $access_all || $access_own_submission || $access_node_submissions;
426

    
427
  // Disable the page cache for anonymous users in this access callback,
428
  // otherwise the "Access denied" page gets cached.
429
  if (!$account->uid && user_access('access own webform submissions', $account)) {
430
    webform_disable_page_cache();
431
  }
432

    
433
  $module_access = count(array_filter(module_invoke_all('webform_submission_access', $node, $submission, $op, $account))) > 0;
434

    
435
  switch ($op) {
436
    case 'view':
437
      return $module_access || $general_access;
438
    case 'edit':
439
      return $module_access || ($general_access && (user_access('edit all webform submissions', $account) || (user_access('edit own webform submissions', $account) && $account->uid == $submission->uid)));
440
    case 'delete':
441
      return $module_access || ($general_access && (user_access('delete all webform submissions', $account) || (user_access('delete own webform submissions', $account) && $account->uid == $submission->uid)));
442
    case 'list':
443
      return $module_access || user_access('access all webform results', $account) || (user_access('access own webform submissions', $account) && ($account->uid || isset($_SESSION['webform_submission']))) || (user_access('access own webform results', $account) && $account->uid == $node->uid);
444
  }
445
}
446

    
447
/**
448
 * Menu access callback. Ensure a user both access and node 'view' permission.
449
 */
450
function webform_results_access($node, $account = NULL) {
451
  global $user;
452
  $account = isset($account) ? $account : $user;
453

    
454
  $module_access = count(array_filter(module_invoke_all('webform_results_access', $node, $account))) > 0;
455

    
456
  return node_access('view', $node, $account) && ($module_access || user_access('access all webform results', $account) || (user_access('access own webform results', $account) && $account->uid == $node->uid));
457
}
458

    
459
function webform_results_clear_access($node, $account = NULL) {
460
  global $user;
461
  $account = isset($account) ? $account : $user;
462

    
463
  $module_access = count(array_filter(module_invoke_all('webform_results_clear_access', $node, $account))) > 0;
464

    
465
  return webform_results_access($node, $account) && ($module_access || user_access('delete all webform submissions', $account));
466
}
467

    
468
/**
469
 * Implements hook_admin_paths().
470
 */
471
function webform_admin_paths() {
472
  if (variable_get('node_admin_theme')) {
473
    return array(
474
      'node/*/webform' => TRUE,
475
      'node/*/webform/*' => TRUE,
476
      'node/*/webform-results' => TRUE,
477
      'node/*/webform-results/*' => TRUE,
478
      'node/*/submission/*' => TRUE,
479
    );
480
  }
481
}
482

    
483
/**
484
 * Implements hook_perm().
485
 */
486
function webform_permission() {
487
  return array(
488
    'access all webform results' => array(
489
      'title' => t('Access all webform results'),
490
      'description' => t('Grants access to the "Results" tab on all webform content. Generally an administrative permission.'),
491
    ),
492
    'access own webform results' => array(
493
      'title' => t('Access own webform results'),
494
      'description' => t('Grants access to the "Results" tab to the author of webform content they have created.'),
495
    ),
496
    'edit all webform submissions' => array(
497
      'title' => t('Edit all webform submissions'),
498
      'description' => t('Allows editing of any webform submission by any user. Generally an administrative permission.'),
499
    ),
500
    'delete all webform submissions' => array(
501
      'title' => t('Delete all webform submissions'),
502
      'description' => t('Allows deleting of any webform submission by any user. Generally an administrative permission.'),
503
    ),
504
    'access own webform submissions' => array(
505
      'title' => t('Access own webform submissions'),
506
    ),
507
    'edit own webform submissions' => array(
508
      'title' => t('Edit own webform submissions'),
509
    ),
510
    'delete own webform submissions' => array(
511
      'title' => t('Delete own webform submissions'),
512
    ),
513
  );
514
}
515

    
516
/**
517
 * Implements hook_theme().
518
 */
519
function webform_theme() {
520
  $theme = array(
521
    // webform.module.
522
    'webform_view' => array(
523
      'render element' => 'webform',
524
    ),
525
    'webform_view_messages' => array(
526
      'variables' => array('node' => NULL, 'teaser' => NULL, 'page' => NULL, 'submission_count' => NULL, 'user_limit_exceeded' => NULL, 'total_limit_exceeded' => NULL, 'allowed_roles' => NULL, 'closed' => NULL, 'cached' => NULL),
527
    ),
528
    'webform_form' => array(
529
      'render element' => 'form',
530
      'template' => 'templates/webform-form',
531
      'pattern' => 'webform_form_[0-9]+',
532
    ),
533
    'webform_confirmation' => array(
534
      'variables' => array('node' => NULL, 'sid' => NULL),
535
      'template' => 'templates/webform-confirmation',
536
      'pattern' => 'webform_confirmation_[0-9]+',
537
    ),
538
    'webform_element' => array(
539
      'render element' => 'element',
540
    ),
541
    'webform_element_text' => array(
542
      'render element' => 'element',
543
    ),
544
    'webform_inline_radio' => array(
545
      'render element' => 'element',
546
    ),
547
    'webform_mail_message' => array(
548
      'variables' => array('node' => NULL, 'submission' => NULL, 'email' => NULL),
549
      'template' => 'templates/webform-mail',
550
      'pattern' => 'webform_mail(_[0-9]+)?',
551
    ),
552
    'webform_mail_headers' => array(
553
      'variables' => array('node' => NULL, 'submission' => NULL, 'email' => NULL),
554
      'pattern' => 'webform_mail_headers_[0-9]+',
555
    ),
556
    'webform_token_help' => array(
557
      'variables' => array('groups' => array()),
558
    ),
559
    // webform.admin.inc.
560
    'webform_admin_settings' => array(
561
      'render element' => 'form',
562
      'file' => 'includes/webform.admin.inc',
563
    ),
564
    'webform_admin_content' => array(
565
      'variables' => array('nodes' => NULL),
566
      'file' => 'includes/webform.admin.inc',
567
    ),
568
    // webform.emails.inc.
569
    'webform_emails_form' => array(
570
      'render element' => 'form',
571
      'file' => 'includes/webform.emails.inc',
572
    ),
573
    'webform_email_add_form' => array(
574
      'render element' => 'form',
575
      'file' => 'includes/webform.emails.inc',
576
    ),
577
    'webform_email_edit_form' => array(
578
      'render element' => 'form',
579
      'file' => 'includes/webform.emails.inc',
580
    ),
581
    // webform.components.inc.
582
    'webform_components_page' => array(
583
      'variables' => array('node' => NULL, 'form' => NULL),
584
      'file' => 'includes/webform.components.inc',
585
    ),
586
    'webform_components_form' => array(
587
      'render element' => 'form',
588
      'file' => 'includes/webform.components.inc',
589
    ),
590
    'webform_component_select' => array(
591
      'render element' => 'element',
592
      'file' => 'includes/webform.components.inc',
593
    ),
594
    // webform.pages.inc.
595
    'webform_advanced_redirection_form' => array(
596
      'render element' => 'form',
597
      'file' => 'includes/webform.pages.inc',
598
    ),
599
    'webform_advanced_submit_limit_form' => array(
600
      'render element' => 'form',
601
      'file' => 'includes/webform.pages.inc',
602
    ),
603
    'webform_advanced_total_submit_limit_form' => array(
604
      'render element' => 'form',
605
      'file' => 'includes/webform.pages.inc',
606
    ),
607
    // webform.report.inc.
608
    'webform_results_per_page' => array(
609
      'variables' => array('total_count' => NULL, 'pager_count' => NULL),
610
      'file' => 'includes/webform.report.inc',
611
    ),
612
    'webform_results_submissions_header' => array(
613
      'variables' => array('node' => NULL),
614
      'file' => 'includes/webform.report.inc',
615
    ),
616
    'webform_results_submissions' => array(
617
      'render element' => 'element',
618
      'template' => 'templates/webform-results-submissions',
619
      'file' => 'includes/webform.report.inc',
620
    ),
621
    'webform_results_table_header' => array(
622
      'variables' => array('node' => NULL),
623
      'file' => 'includes/webform.report.inc',
624
    ),
625
    'webform_results_table' => array(
626
      'variables' => array('node' => NULL, 'components' => NULL, 'submissions' => NULL, 'node' => NULL, 'total_count' => NULL, 'pager_count' => NULL),
627
      'file' => 'includes/webform.report.inc',
628
    ),
629
    'webform_results_download_range' => array(
630
      'render element' => 'element',
631
      'file' => 'includes/webform.report.inc',
632
    ),
633
    'webform_results_download_select_format' => array(
634
      'render element' => 'element',
635
      'file' => 'includes/webform.report.inc',
636
    ),
637
    'webform_results_analysis' => array(
638
      'variables' => array('node' => NULL, 'data' => NULL, 'sids' => array(), 'component' => NULL),
639
      'file' => 'includes/webform.report.inc',
640
    ),
641
    // webform.submissions.inc
642
    'webform_submission' => array(
643
      'render element' => 'renderable',
644
      'template' => 'templates/webform-submission',
645
      'pattern' => 'webform_submission_[0-9]+',
646
      'file' => 'includes/webform.submissions.inc',
647
    ),
648
    'webform_submission_page' => array(
649
      'variables' => array('node' => NULL, 'submission' => NULL, 'submission_content' => NULL, 'submission_navigation' => NULL, 'submission_information' => NULL, 'submission_actions' => NULL, 'mode' => NULL),
650
      'template' => 'templates/webform-submission-page',
651
      'file' => 'includes/webform.submissions.inc',
652
    ),
653
    'webform_submission_information' => array(
654
      'variables' => array('node' => NULL, 'submission' => NULL, 'mode' => 'display'),
655
      'template' => 'templates/webform-submission-information',
656
      'file' => 'includes/webform.submissions.inc',
657
    ),
658
    'webform_submission_navigation' => array(
659
      'variables' => array('node' => NULL, 'submission' => NULL, 'mode' => NULL),
660
      'template' => 'templates/webform-submission-navigation',
661
      'file' => 'includes/webform.submissions.inc',
662
    ),
663
    'webform_submission_resend' => array(
664
      'render element' => 'form',
665
      'file' => 'includes/webform.submissions.inc',
666
    ),
667
  );
668

    
669
  // Theme functions in all components.
670
  $components = webform_components(TRUE);
671
  foreach ($components as $type => $component) {
672
    if ($theme_additions = webform_component_invoke($type, 'theme')) {
673
      $theme = array_merge($theme, $theme_additions);
674
    }
675
  }
676
  return $theme;
677
}
678

    
679
/**
680
 * Implements hook_library().
681
 */
682
function webform_library() {
683
  $module_path = drupal_get_path('module', 'webform');
684

    
685
  // Webform administration.
686
  $libraries['admin'] = array(
687
    'title' => 'Webform: Administration',
688
    'website' => 'http://drupal.org/project/webform',
689
    'version' => '1.0',
690
    'js' => array(
691
      $module_path . '/js/webform-admin.js' => array('group' => JS_DEFAULT),
692
    ),
693
    'css' => array(
694
      $module_path . '/css/webform-admin.css' => array('group' => CSS_DEFAULT, 'weight' => 1),
695
    ),
696
  );
697

    
698
  return $libraries;
699
}
700

    
701
/**
702
 * Implements hook_element_info().
703
 */
704
function webform_element_info() {
705
  // A few of our components need to be defined here because Drupal does not
706
  // provide these components natively. Because this hook fires on every page
707
  // load (even on non-webform pages), we don't put this in the component .inc
708
  // files because of the unnecessary loading that it would require.
709
  $elements['webform_time'] = array('#input' => 'TRUE');
710
  $elements['webform_grid'] = array('#input' => 'TRUE');
711

    
712
  $elements['webform_email'] = array(
713
    '#input' => TRUE,
714
    '#theme' => 'webform_email',
715
    '#size' => 60,
716
  );
717
  $elements['webform_number'] = array(
718
    '#input' => TRUE,
719
    '#theme' => 'webform_number',
720
    '#min' => NULL,
721
    '#max' => NULL,
722
    '#step' => NULL,
723
  );
724

    
725
  return $elements;
726
}
727

    
728
/**
729
 * Implements hook_webform_component_info().
730
 */
731
function webform_webform_component_info() {
732
  $component_info = array(
733
    'date' => array(
734
      'label' => t('Date'),
735
      'description' => t('Presents month, day, and year fields.'),
736
      'features' => array(
737
        'conditional' => FALSE,
738
      ),
739
      'file' => 'components/date.inc',
740
    ),
741
    'email' => array(
742
      'label' => t('E-mail'),
743
      'description' => t('A special textfield that accepts e-mail addresses.'),
744
      'file' => 'components/email.inc',
745
      'features' => array(
746
        'email_address' => TRUE,
747
        'spam_analysis' => TRUE,
748
      ),
749
    ),
750
    'fieldset' => array(
751
      'label' => t('Fieldset'),
752
      'description' => t('Fieldsets allow you to organize multiple fields into groups.'),
753
      'features' => array(
754
        'csv' => FALSE,
755
        'default_value' => FALSE,
756
        'required' => FALSE,
757
        'conditional' => FALSE,
758
        'group' => TRUE,
759
        'title_inline' => FALSE,
760
      ),
761
      'file' => 'components/fieldset.inc',
762
    ),
763
    'grid' => array(
764
      'label' => t('Grid'),
765
      'description' => t('Allows creation of grid questions, denoted by radio buttons.'),
766
      'features' => array(
767
        'conditional' => FALSE,
768
        'default_value' => FALSE,
769
        'title_inline' => FALSE,
770
      ),
771
      'file' => 'components/grid.inc',
772
    ),
773
    'hidden' => array(
774
      'label' => t('Hidden'),
775
      'description' => t('A field which is not visible to the user, but is recorded with the submission.'),
776
      'file' => 'components/hidden.inc',
777
      'features' => array(
778
        'required' => FALSE,
779
        'description' => FALSE,
780
        'email_address' => TRUE,
781
        'email_name' => TRUE,
782
        'title_display' => FALSE,
783
        'private' => FALSE,
784
      ),
785
    ),
786
    'markup' => array(
787
      'label' => t('Markup'),
788
      'description' => t('Displays text as HTML in the form; does not render a field.'),
789
      'features' => array(
790
        'csv' => FALSE,
791
        'default_value' => FALSE,
792
        'description' => FALSE,
793
        'email' => FALSE,
794
        'required' => FALSE,
795
        'conditional' => FALSE,
796
        'title_display' => FALSE,
797
        'private' => FALSE,
798
      ),
799
      'file' => 'components/markup.inc',
800
    ),
801
    'number' => array(
802
      'label' => t('Number'),
803
      'description' => t('A numeric input field (either as textfield or select list).'),
804
      'features' => array(
805
      ),
806
      'file' => 'components/number.inc',
807
    ),
808
    'pagebreak' => array(
809
      'label' => t('Page break'),
810
      'description' => t('Organize forms into multiple pages.'),
811
      'features' => array(
812
        'csv' => FALSE,
813
        'default_value' => FALSE,
814
        'description' => FALSE,
815
        'private' => FALSE,
816
        'required' => FALSE,
817
        'title_display' => FALSE,
818
      ),
819
      'file' => 'components/pagebreak.inc',
820
    ),
821
    'select' => array(
822
      'label' => t('Select options'),
823
      'description' => t('Allows creation of checkboxes, radio buttons, or select menus.'),
824
      'file' => 'components/select.inc',
825
      'features' => array(
826
        'default_value' => FALSE,
827
        'email_address' => TRUE,
828
        'email_name' => TRUE,
829
      ),
830
    ),
831
    'textarea' => array(
832
      'label' => t('Textarea'),
833
      'description' => t('A large text area that allows for multiple lines of input.'),
834
      'file' => 'components/textarea.inc',
835
      'features' => array(
836
        'spam_analysis' => TRUE,
837
        'title_inline' => FALSE,
838
      ),
839
    ),
840
    'textfield' => array(
841
      'label' => t('Textfield'),
842
      'description' => t('Basic textfield type.'),
843
      'file' => 'components/textfield.inc',
844
      'features' => array(
845
        'email_name' => TRUE,
846
        'spam_analysis' => TRUE,
847
      ),
848
    ),
849
    'time' => array(
850
      'label' => t('Time'),
851
      'description' => t('Presents the user with hour and minute fields. Optional am/pm fields.'),
852
      'features' => array(
853
        'conditional' => FALSE,
854
      ),
855
      'file' => 'components/time.inc',
856
    ),
857
  );
858

    
859
  if (module_exists('file')) {
860
    $component_info['file'] = array(
861
      'label' => t('File'),
862
      'description' => t('Allow users to upload files of configurable types.'),
863
      'features' => array(
864
        'conditional' => FALSE,
865
        'default_value' => FALSE,
866
        'attachment' => TRUE,
867
      ),
868
      'file' => 'components/file.inc',
869
    );
870
  }
871

    
872
  return $component_info;
873
}
874

    
875
/**
876
 * Implements hook_forms().
877
 *
878
 * All webform_client_form forms share the same form handler
879
 */
880
function webform_forms($form_id) {
881
  $forms = array();
882
  if (strpos($form_id, 'webform_client_form_') === 0) {
883
    $forms[$form_id]['callback'] = 'webform_client_form';
884
  }
885
  return $forms;
886
}
887

    
888
/**
889
 * Implements hook_webform_select_options_info().
890
 */
891
function webform_webform_select_options_info() {
892
  module_load_include('inc', 'webform', 'includes/webform.options');
893
  return _webform_options_info();
894
}
895

    
896
/**
897
 * Implements hook_webform_webform_submission_actions().
898
 */
899
function webform_webform_submission_actions($node, $submission) {
900
  $actions = array();
901
  $destination = drupal_get_destination();
902

    
903
  if (module_exists('print_pdf') && user_access('access PDF version')) {
904
    $actions['printpdf'] = array(
905
      'title' => t('Download PDF'),
906
      'href' => 'printpdf/' . $node->nid . '/submission/' . $submission->sid,
907
      'query' => $destination,
908
    );
909
  }
910

    
911
  if (module_exists('print') && user_access('access print')) {
912
    $actions['print'] = array(
913
      'title' => t('Print'),
914
      'href' => 'print/' . $node->nid . '/submission/' . $submission->sid,
915
    );
916
  }
917

    
918
  if (webform_results_access($node) && count($node->webform['emails'])) {
919
    $actions['resend'] = array(
920
      'title' => t('Resend e-mails'),
921
      'href' => 'node/' . $node->nid . '/submission/' . $submission->sid . '/resend',
922
      'query' => drupal_get_destination(),
923
    );
924
  }
925

    
926
  return $actions;
927
}
928

    
929
/**
930
 * Implements hook_webform_submission_update().
931
 *
932
 * We implement our own hook here to facilitate the File component, which needs
933
 * to clean up manage file usage records and delete files from submissions that
934
 * have been edited if necessary.
935
 */
936
function webform_webform_submission_presave($node, &$submission) {
937
  // Check if there are any file components in this submission and if any of
938
  // them currently contain files.
939
  $has_file_components = FALSE;
940
  $new_fids = array();
941
  $old_fids = array();
942

    
943
  foreach ($node->webform['components'] as $cid => $component) {
944
    if ($component['type'] == 'file') {
945
      $has_file_components = TRUE;
946
      if (!empty($submission->data[$cid]['value'])) {
947
        foreach ($submission->data[$cid]['value'] as $key => $value) {
948
          if (empty($value)) {
949
            unset($submission->data[$cid]['value'][$key]);
950
          }
951
        }
952
        $new_fids = array_merge($new_fids, $submission->data[$cid]['value']);
953
      }
954
    }
955
  }
956

    
957
  if ($has_file_components) {
958
    // If we're updating a submission, build a list of previous files.
959
    if (isset($submission->sid)) {
960
      $old_submission = webform_get_submission($node->nid, $submission->sid, TRUE);
961

    
962
      foreach ($node->webform['components'] as $cid => $component) {
963
        if ($component['type'] == 'file') {
964
          if (!empty($old_submission->data[$cid]['value'])) {
965
            $old_fids = array_merge($old_fids, $old_submission->data[$cid]['value']);
966
          }
967
        }
968
      }
969
    }
970

    
971
    // Save the list of added or removed files so we can add usage in
972
    // hook_webform_submission_insert() or _update().
973
    $submission->file_usage = array(
974
      // Diff the old against new to determine what files were deleted.
975
      'deleted_fids' => array_diff($old_fids, $new_fids),
976
      // Diff the new files against old to determine new uploads.
977
      'added_fids' => array_diff($new_fids, $old_fids)
978
    );
979
  }
980
}
981

    
982
/**
983
 * Implements hook_webform_submission_insert().
984
 */
985
function webform_webform_submission_insert($node, $submission) {
986
  if (isset($submission->file_usage)) {
987
    webform_component_include('file');
988
    webform_file_usage_adjust($submission);
989
  }
990
}
991

    
992
/**
993
 * Implements hook_webform_submission_update().
994
 */
995
function webform_webform_submission_update($node, $submission) {
996
  if (isset($submission->file_usage)) {
997
    webform_component_include('file');
998
    webform_file_usage_adjust($submission);
999
  }
1000
}
1001

    
1002
/**
1003
 * Implements hook_webform_submission_render_alter().
1004
 */
1005
function webform_webform_submission_render_alter(&$renderable) {
1006
  // If displaying a submission to end-users who are viewing their own
1007
  // submissions (and not through an e-mail), do not show hidden values.
1008
  // This needs to be implemented at the level of the entire submission, since
1009
  // individual components do not get contextual information about where they
1010
  // are being displayed.
1011
  $node = $renderable['#node'];
1012
  $is_admin = webform_results_access($node);
1013
  if (empty($renderable['#email']) && !$is_admin) {
1014
    // Find and hide the display of all hidden components.
1015
    foreach ($node->webform['components'] as $cid => $component) {
1016
      if ($component['type'] == 'hidden') {
1017
        $parents = webform_component_parent_keys($node, $component);
1018
        $element = &$renderable;
1019
        foreach ($parents as $pid) {
1020
          $element = &$element[$pid];
1021
        }
1022
        $element['#access'] = FALSE;
1023
      }
1024
    }
1025
  }
1026
}
1027

    
1028
/**
1029
 * Implements hook_file_download().
1030
 *
1031
 * Only allow users with view webform submissions to download files.
1032
 */
1033
function webform_file_download($uri) {
1034
  module_load_include('inc', 'webform', 'includes/webform.submissions');
1035

    
1036
  // Determine whether this file was a webform upload.
1037
  $row = db_query("SELECT fu.id as sid, f.fid FROM {file_managed} f LEFT JOIN {file_usage} fu ON f.fid = fu.fid AND fu.module = :webform AND fu.type = :submission WHERE f.uri = :uri", array('uri' => $uri, ':webform' => 'webform', ':submission' => 'submission'))->fetchObject();
1038
  if ($row) {
1039
    $file = file_load($row->fid);
1040
  }
1041
  if (!empty($row->sid)) {
1042
    $submissions = webform_get_submissions(array('sid' => $row->sid));
1043
    $submission = reset($submissions);
1044
  }
1045

    
1046
  // Grant access based on access to the submission.
1047
  if (!empty($submission)) {
1048
    $node = node_load($submission->nid);
1049
    if (webform_submission_access($node, $submission)) {
1050
      return file_get_content_headers($file);
1051
    }
1052
  }
1053
  // Grant access to files uploaded by a user before the submission is saved.
1054
  elseif (!empty($file) && !empty($_SESSION['webform_files'][$file->fid])) {
1055
    return file_get_content_headers($file);
1056
  }
1057
}
1058

    
1059
/**
1060
 * Implements hook_node_type().
1061
 *
1062
 * Not a real hook in Drupal 7. Re-used for consistency with the D6 version.
1063
 */
1064
function webform_node_type($op, $info) {
1065
  $webform_types = webform_variable_get('webform_node_types');
1066
  $affected_type = isset($info->old_type) ? $info->old_type : $info->type;
1067
  $key = array_search($affected_type, $webform_types);
1068
  if ($key !== FALSE) {
1069
    if ($op == 'update') {
1070
      $webform_types[$key] = $info->type;
1071
    }
1072
    if ($op == 'delete') {
1073
      unset($webform_types[$key]);
1074
    }
1075
    variable_set('webform_node_types', $webform_types);
1076
  }
1077
}
1078

    
1079
/**
1080
 * Implements hook_node_type_update().
1081
 */
1082
function webform_node_type_update($info) {
1083
  webform_node_type('update', $info);
1084
}
1085

    
1086
/**
1087
 * Implements hook_node_type_delete().
1088
 */
1089
function webform_node_type_delete($info) {
1090
  webform_node_type('delete', $info);
1091
}
1092

    
1093
/**
1094
 * Implements hook_node_insert().
1095
 */
1096
function webform_node_insert($node) {
1097
  if (!in_array($node->type, webform_variable_get('webform_node_types'))) {
1098
    return;
1099
  }
1100

    
1101
  // If added directly through node_save(), set defaults for the node.
1102
  if (!isset($node->webform)) {
1103
    $node->webform = webform_node_defaults();
1104
  }
1105

    
1106
  // Do not make an entry if this node does not have any Webform settings.
1107
  if ($node->webform == webform_node_defaults() && !in_array($node->type, webform_variable_get('webform_node_types_primary'))) {
1108
    return;
1109
  }
1110

    
1111
  module_load_include('inc', 'webform', 'includes/webform.components');
1112
  module_load_include('inc', 'webform', 'includes/webform.emails');
1113

    
1114
  // Insert the webform.
1115
  $node->webform['nid'] = $node->nid;
1116
  $node->webform['record_exists'] = (bool) drupal_write_record('webform', $node->webform);
1117

    
1118
  // Insert the components into the database. Used with clone.module.
1119
  if (isset($node->webform['components']) && !empty($node->webform['components'])) {
1120
    foreach ($node->webform['components'] as $cid => $component) {
1121
      $component['nid'] = $node->nid; // Required for clone.module.
1122
      webform_component_insert($component);
1123
    }
1124
  }
1125

    
1126
  // Insert emails. Also used with clone.module.
1127
  if (isset($node->webform['emails']) && !empty($node->webform['emails'])) {
1128
    foreach ($node->webform['emails'] as $eid => $email) {
1129
      $email['nid'] = $node->nid;
1130
      webform_email_insert($email);
1131
    }
1132
  }
1133

    
1134
  // Set the per-role submission access control.
1135
  foreach (array_filter($node->webform['roles']) as $rid) {
1136
    db_insert('webform_roles')->fields(array('nid' => $node->nid, 'rid' => $rid))->execute();
1137
  }
1138

    
1139
  // Flush the block cache if creating a block.
1140
  if ($node->webform['block']) {
1141
    block_flush_caches();
1142
  }
1143
}
1144

    
1145
/**
1146
 * Implements hook_node_update().
1147
 */
1148
function webform_node_update($node) {
1149
  if (!in_array($node->type, webform_variable_get('webform_node_types'))) {
1150
    return;
1151
  }
1152

    
1153
  // Check if this node needs a webform record at all. If it matches the
1154
  // defaults, any existing record will be deleted.
1155
  webform_check_record($node);
1156

    
1157
  // If a webform row doesn't even exist, we can assume it needs to be inserted.
1158
  // If the the webform matches the defaults, no row will be inserted.
1159
  if (!$node->webform['record_exists']) {
1160
    webform_node_insert($node);
1161
    return;
1162
  }
1163

    
1164
  // Update the webform entry.
1165
  $node->webform['nid'] = $node->nid;
1166
  drupal_write_record('webform', $node->webform, array('nid'));
1167

    
1168
  // Compare the webform components and don't do anything if it's not needed.
1169
  // The internal cache needs to be reset here so that the cached node entity
1170
  // does not get loaded and invalidate the comparisons.
1171
  $original = node_load($node->nid, NULL, TRUE);
1172

    
1173
  if ($original->webform['components'] != $node->webform['components']) {
1174
    module_load_include('inc', 'webform', 'includes/webform.components');
1175

    
1176
    $original_cids = array_keys($original->webform['components']);
1177
    $current_cids = array_keys($node->webform['components']);
1178

    
1179
    $all_cids = array_unique(array_merge($original_cids, $current_cids));
1180
    $deleted_cids = array_diff($original_cids, $current_cids);
1181
    $inserted_cids = array_diff($current_cids, $original_cids);
1182

    
1183
    foreach ($all_cids as $cid) {
1184
      if (in_array($cid, $inserted_cids)) {
1185
        webform_component_insert($node->webform['components'][$cid]);
1186
      }
1187
      elseif (in_array($cid, $deleted_cids)) {
1188
        webform_component_delete($node, $original->webform['components'][$cid]);
1189
      }
1190
      elseif ($node->webform['components'][$cid] != $original->webform['components'][$cid]) {
1191
        $node->webform['components'][$cid]['nid'] = $node->nid;
1192
        webform_component_update($node->webform['components'][$cid]);
1193
      }
1194
    }
1195
  }
1196

    
1197
  // Compare the webform e-mails and don't do anything if it's not needed.
1198
  if ($original->webform['emails'] != $node->webform['emails']) {
1199
    module_load_include('inc', 'webform', 'includes/webform.emails');
1200

    
1201
    $original_eids = array_keys($original->webform['emails']);
1202
    $current_eids = array_keys($node->webform['emails']);
1203

    
1204
    $all_eids = array_unique(array_merge($original_eids, $current_eids));
1205
    $deleted_eids = array_diff($original_eids, $current_eids);
1206
    $inserted_eids = array_diff($current_eids, $original_eids);
1207

    
1208
    foreach ($all_eids as $eid) {
1209
      if (in_array($eid, $inserted_eids)) {
1210
        webform_email_insert($node->webform['emails'][$eid]);
1211
      }
1212
      elseif (in_array($eid, $deleted_eids)) {
1213
        webform_email_delete($node, $original->webform['emails'][$eid]);
1214
      }
1215
      elseif ($node->webform['emails'][$eid] != $original->webform['emails'][$eid]) {
1216
        $node->webform['emails'][$eid]['nid'] = $node->nid;
1217
        webform_email_update($node->webform['emails'][$eid]);
1218
      }
1219
    }
1220
  }
1221

    
1222
  // Just delete and re-insert roles if they've changed.
1223
  if ($original->webform['roles'] != $node->webform['roles']) {
1224
    db_delete('webform_roles')->condition('nid', $node->nid)->execute();
1225
    foreach (array_filter($node->webform['roles']) as $rid) {
1226
      db_insert('webform_roles')->fields(array('nid' => $node->nid, 'rid' => $rid))->execute();
1227
    }
1228
  }
1229

    
1230
  // Flush the block cache if block settings have been changed.
1231
  if ($node->webform['block'] != $original->webform['block']) {
1232
    block_flush_caches();
1233
  }
1234
}
1235

    
1236
/**
1237
 * Implements hook_delete().
1238
 */
1239
function webform_node_delete($node) {
1240
  if (!in_array($node->type, webform_variable_get('webform_node_types'))) {
1241
    return;
1242
  }
1243

    
1244
  // Allow components clean up extra data, such as uploaded files.
1245
  module_load_include('inc', 'webform', 'includes/webform.components');
1246
  foreach ($node->webform['components'] as $cid => $component) {
1247
    webform_component_delete($node, $component);
1248
  }
1249

    
1250
  // Remove any trace of webform data from the database.
1251
  db_delete('webform')->condition('nid', $node->nid)->execute();
1252
  db_delete('webform_component')->condition('nid', $node->nid)->execute();
1253
  db_delete('webform_emails')->condition('nid', $node->nid)->execute();
1254
  db_delete('webform_roles')->condition('nid', $node->nid)->execute();
1255
  db_delete('webform_submissions')->condition('nid', $node->nid)->execute();
1256
  db_delete('webform_submitted_data')->condition('nid', $node->nid)->execute();
1257
  db_delete('webform_last_download')->condition('nid', $node->nid)->execute();
1258
}
1259

    
1260
/**
1261
 * Default settings for a newly created webform node.
1262
 */
1263
function webform_node_defaults() {
1264
  $defaults = array(
1265
    'confirmation' => '',
1266
    'confirmation_format' => NULL,
1267
    'redirect_url' => '<confirmation>',
1268
    'teaser' => '0',
1269
    'block' => '0',
1270
    'allow_draft' => '0',
1271
    'auto_save' => '0',
1272
    'submit_notice' => '1',
1273
    'submit_text' => '',
1274
    'submit_limit' => '-1',
1275
    'submit_interval' => '-1',
1276
    'total_submit_limit' => '-1',
1277
    'total_submit_interval' => '-1',
1278
    'status' => '1',
1279
    'record_exists' => FALSE,
1280
    'roles' => array('1', '2'),
1281
    'emails' => array(),
1282
    'components' => array(),
1283
  );
1284
  drupal_alter('webform_node_defaults', $defaults);
1285
  return $defaults;
1286
}
1287

    
1288
/**
1289
 * Implements hook_node_prepare().
1290
 */
1291
function webform_node_prepare($node) {
1292
  $webform_types = webform_variable_get('webform_node_types');
1293
  if (in_array($node->type, $webform_types) && !isset($node->webform)) {
1294
    $node->webform = webform_node_defaults();
1295
  }
1296
}
1297

    
1298

    
1299
/**
1300
 * Implements hook_node_load().
1301
 */
1302
function webform_node_load($nodes, $types) {
1303
  // Quick check to see if we need to do anything at all for these nodes.
1304
  $webform_types = webform_variable_get('webform_node_types');
1305
  if (count(array_intersect($types, $webform_types)) == 0) {
1306
    return;
1307
  }
1308

    
1309
  module_load_include('inc', 'webform', 'includes/webform.components');
1310

    
1311
  // Select all webforms that match these node IDs.
1312
  $result = db_select('webform')
1313
    ->fields('webform')
1314
    ->condition('nid', array_keys($nodes), 'IN')
1315
    ->execute()
1316
    ->fetchAllAssoc('nid', PDO::FETCH_ASSOC);
1317

    
1318
  foreach ($result as $nid => $webform) {
1319
    // Load the basic information for each node.
1320
    $nodes[$nid]->webform = $webform;
1321
    $nodes[$nid]->webform['record_exists'] = TRUE;
1322
  }
1323

    
1324
  // Load the components, emails, and defaults for all webform-enabled nodes.
1325
  // TODO: Increase efficiency here by pulling in all information all at once
1326
  // instead of individual queries.
1327
  foreach ($nodes as $nid => $node) {
1328
    if (!in_array($node->type, $webform_types)) {
1329
      continue;
1330
    }
1331

    
1332
    // If a webform record doesn't exist, just return the defaults.
1333
    if (!isset($nodes[$nid]->webform)) {
1334
      $nodes[$nid]->webform = webform_node_defaults();
1335
      continue;
1336
    }
1337

    
1338
    $nodes[$nid]->webform['roles'] = db_select('webform_roles')
1339
      ->fields('webform_roles', array('rid'))
1340
      ->condition('nid', $nid)
1341
      ->execute()
1342
      ->fetchCol();
1343
    $nodes[$nid]->webform['emails'] = db_select('webform_emails')
1344
      ->fields('webform_emails')
1345
      ->condition('nid', $nid)
1346
      ->execute()
1347
      ->fetchAllAssoc('eid', PDO::FETCH_ASSOC);
1348

    
1349
    // Unserialize the exclude component list for e-mails.
1350
    foreach ($nodes[$nid]->webform['emails'] as $eid => $email) {
1351
      $nodes[$nid]->webform['emails'][$eid]['excluded_components'] = array_filter(explode(',', $email['excluded_components']));
1352
      if (variable_get('webform_format_override', 0)) {
1353
        $nodes[$nid]->webform['emails'][$eid]['html'] = variable_get('webform_default_format', 0);
1354
      }
1355
    }
1356

    
1357
    // Load components for each node.
1358
    $nodes[$nid]->webform['components'] = db_select('webform_component')
1359
      ->fields('webform_component')
1360
      ->condition('nid', $nid)
1361
      ->orderBy('weight')
1362
      ->orderBy('name')
1363
      ->execute()
1364
      ->fetchAllAssoc('cid', PDO::FETCH_ASSOC);
1365

    
1366
    // Do a little cleanup on each component.
1367
    foreach ($nodes[$nid]->webform['components'] as $cid => $component) {
1368
      $nodes[$nid]->webform['components'][$cid]['nid'] = $nid;
1369
      $nodes[$nid]->webform['components'][$cid]['extra'] = unserialize($component['extra']);
1370
      webform_component_defaults($nodes[$nid]->webform['components'][$cid]);
1371
    }
1372

    
1373
    // Organize the components into a fieldset-based order.
1374
    if (!empty($nodes[$nid]->webform['components'])) {
1375
      $component_tree = array();
1376
      $page_count = 1;
1377
      _webform_components_tree_build($nodes[$nid]->webform['components'], $component_tree, 0, $page_count);
1378
      $nodes[$nid]->webform['components'] = _webform_components_tree_flatten($component_tree['children']);
1379
    }
1380
  }
1381
}
1382

    
1383
/**
1384
 * Implements hook_form_alter().
1385
 */
1386
function webform_form_alter(&$form, $form_state, $form_id) {
1387
  $matches = array();
1388
  if (isset($form['#node']->type) && $form_id == $form['#node']->type . '_node_form' && in_array($form['#node']->type, webform_variable_get('webform_node_types'))) {
1389
    $node = $form['#node'];
1390
    // Preserve all Webform options currently set on the node.
1391
    $form['webform'] = array(
1392
      '#type' => 'value',
1393
      '#value' => $node->webform,
1394
    );
1395

    
1396
    // If a new node, redirect the user to the components form after save.
1397
    if (empty($node->nid) && in_array($node->type, webform_variable_get('webform_node_types_primary'))) {
1398
      $form['actions']['submit']['#submit'][] = 'webform_form_submit';
1399
    }
1400
  }
1401
}
1402

    
1403
/**
1404
 * Submit handler for the webform node form.
1405
 *
1406
 * Redirect the user to the components form on new node inserts. Note that this
1407
 * fires after the hook_submit() function above.
1408
 */
1409
function webform_form_submit($form, &$form_state) {
1410
  drupal_set_message(t('The new webform %title has been created. Add new fields to your webform with the form below.', array('%title' => $form_state['values']['title'])));
1411
  $form_state['redirect'] = 'node/' . $form_state['nid'] . '/webform/components';
1412
}
1413

    
1414
/**
1415
 * Implements hook_node_view().
1416
 */
1417
function webform_node_view($node, $view_mode) {
1418
  global $user;
1419

    
1420
  if (!in_array($node->type, webform_variable_get('webform_node_types'))) {
1421
    return;
1422
  }
1423

    
1424
  // Set teaser and page variables a la Drupal 6.
1425
  $teaser = $view_mode == 'teaser';
1426
  $page = arg(0) == 'node' && arg(1) == $node->nid;
1427

    
1428
  // If empty, a teaser, or a new node (during preview) do not display.
1429
  if (empty($node->webform['components']) || ($teaser && !$node->webform['teaser']) || empty($node->nid)) {
1430
    return;
1431
  }
1432

    
1433
  // Do not include the form in the search index if indexing is disabled.
1434
  if (module_exists('search') && $view_mode == 'search_index' && !variable_get('webform_search_index', 1)) {
1435
    return;
1436
  }
1437

    
1438
  $info = array();
1439
  $submission = array();
1440
  $submission_count = 0;
1441
  $enabled = TRUE;
1442
  $logging_in = FALSE;
1443
  $total_limit_exceeded = FALSE;
1444
  $user_limit_exceeded = FALSE;
1445
  $closed = FALSE;
1446
  $allowed_roles = array();
1447

    
1448
  // If a teaser, tell the form to load subsequent pages on the node page.
1449
  if ($teaser && !isset($node->webform['action'])) {
1450
    $query = array_diff_key($_GET, array('q' => ''));
1451
    $node->webform['action'] = url('node/' . $node->nid, array('query' => $query));
1452
  }
1453

    
1454
  // When logging in using a form on the same page as a webform node, suppress
1455
  // output messages so that they don't show up after the user has logged in.
1456
  // See http://drupal.org/node/239343.
1457
  if (isset($_POST['op']) && isset($_POST['name']) && isset($_POST['pass'])) {
1458
    $logging_in = TRUE;
1459
  }
1460

    
1461
  if ($node->webform['status'] == 0) {
1462
    $closed = TRUE;
1463
    $enabled = FALSE;
1464
  }
1465
  else {
1466
    // Check if the user's role can submit this webform.
1467
    if (variable_get('webform_submission_access_control', 1)) {
1468
      foreach ($node->webform['roles'] as $rid) {
1469
        $allowed_roles[$rid] = isset($user->roles[$rid]) ? TRUE : FALSE;
1470
      }
1471
      if (array_search(TRUE, $allowed_roles) === FALSE && $user->uid != 1) {
1472
        $enabled = FALSE;
1473
      }
1474
    }
1475
    else {
1476
      // If not using Webform submission access control, allow for all roles.
1477
      $allowed_roles = array_keys(user_roles());
1478
    }
1479
  }
1480

    
1481
  // Get a count of previous submissions by this user. Note that the
1482
  // webform_submission_access() function may disable the page cache for
1483
  // anonymous users if they are allowed to edit their own submissions!
1484
  if ($page && webform_submission_access($node, NULL, 'list')) {
1485
    module_load_include('inc', 'webform', 'includes/webform.submissions');
1486
    $submission_count = webform_get_submission_count($node->nid, $user->uid);
1487
  }
1488

    
1489
  // Check if this page is cached or not.
1490
  $cached = $user->uid == 0 && (variable_get('cache', 0) || drupal_page_is_cacheable() === FALSE);
1491

    
1492
  // Check if the user can add another submission.
1493
  if ($node->webform['submit_limit'] != -1) { // -1: Submissions are never throttled.
1494
    module_load_include('inc', 'webform', 'includes/webform.submissions');
1495

    
1496
    // Disable the form if the limit is exceeded and page cache is not active.
1497
    if (($user_limit_exceeded = _webform_submission_user_limit_check($node)) && !$cached) {
1498
      $enabled = FALSE;
1499
    }
1500
  }
1501

    
1502
  // Check if the user can add another submission if there is a limit on total
1503
  // submissions.
1504
  if ($node->webform['total_submit_limit'] != -1) { // -1: Submissions are never throttled.
1505
    module_load_include('inc', 'webform', 'includes/webform.submissions');
1506

    
1507
    // Disable the form if the limit is exceeded and page cache is not active.
1508
    if (($total_limit_exceeded = _webform_submission_total_limit_check($node)) && !$cached) {
1509
      $enabled = FALSE;
1510
    }
1511
  }
1512

    
1513
  // Check if this user has a draft for this webform.
1514
  $is_draft = FALSE;
1515
  if (($node->webform['allow_draft'] || $node->webform['auto_save']) && $user->uid != 0) {
1516
    // Draft found - display form with draft data for further editing.
1517
    if ($draft_sid = _webform_fetch_draft_sid($node->nid, $user->uid)) {
1518
      module_load_include('inc', 'webform', 'includes/webform.submissions');
1519
      $submission = webform_get_submission($node->nid, $draft_sid);
1520
      $enabled = TRUE;
1521
      $is_draft = TRUE;
1522
    }
1523
  }
1524

    
1525
  // Render the form and generate the output.
1526
  $form = !empty($node->webform['components']) ? drupal_get_form('webform_client_form_' . $node->nid, $node, $submission, $is_draft) : '';
1527

    
1528
  // Remove the surrounding <form> tag if this is a preview.
1529
  if (!empty($node->in_preview)) {
1530
    $form['#type'] = 'markup';
1531
  }
1532

    
1533
  // Print out messages for the webform.
1534
  if (empty($node->in_preview) && !isset($node->webform_block) && !$logging_in) {
1535
    theme('webform_view_messages', array('node' => $node, 'teaser' => $teaser, 'page' => $page, 'submission_count' => $submission_count, 'user_limit_exceeded' => $user_limit_exceeded, 'total_limit_exceeded' => $total_limit_exceeded, 'allowed_roles' => $allowed_roles, 'closed' => $closed, 'cached' => $cached));
1536
  }
1537

    
1538
  // Add the output to the node.
1539
  $node->content['webform'] = array(
1540
    '#theme' => 'webform_view',
1541
    '#node' => $node,
1542
    '#teaser' => $teaser,
1543
    '#page' => $page,
1544
    '#form' => $form,
1545
    '#enabled' => $enabled,
1546
    '#weight' => 10,
1547
  );
1548
}
1549

    
1550
/**
1551
 * Output the Webform into the node content.
1552
 *
1553
 * @param $node
1554
 *   The webform node object.
1555
 * @param $teaser
1556
 *   If this webform is being displayed as the teaser view of the node.
1557
 * @param $page
1558
 *   If this webform node is being viewed as the main content of the page.
1559
 * @param $form
1560
 *   The rendered form.
1561
 * @param $enabled
1562
 *   If the form allowed to be completed by the current user.
1563
 */
1564
function theme_webform_view($variables) {
1565
  // Only show the form if this user is allowed access.
1566
  if ($variables['webform']['#enabled']) {
1567
    return drupal_render($variables['webform']['#form']);
1568
  }
1569
}
1570

    
1571
/**
1572
 * Display a message to a user if they are not allowed to fill out a form.
1573
 *
1574
 * @param $node
1575
 *   The webform node object.
1576
 * @param $teaser
1577
 *   If this webform is being displayed as the teaser view of the node.
1578
 * @param $page
1579
 *   If this webform node is being viewed as the main content of the page.
1580
 * @param $submission_count
1581
 *   The number of submissions this user has already submitted. Not calculated
1582
 *   for anonymous users.
1583
 * @param $user_limit_exceeded
1584
 *   Boolean value if the submission limit for this user has been exceeded.
1585
 * @param $total_limit_exceeded
1586
 *   Boolean value if the total submission limit has been exceeded.
1587
 * @param $allowed_roles
1588
 *   A list of user roles that are allowed to submit this webform.
1589
 * @param $closed
1590
 *   Boolean value if submissions are closed.
1591
 */
1592
function theme_webform_view_messages($variables) {
1593
  global $user;
1594

    
1595
  $node = $variables['node'];
1596
  $teaser = $variables['teaser'];
1597
  $page = $variables['page'];
1598
  $submission_count = $variables['submission_count'];
1599
  $user_limit_exceeded = $variables['user_limit_exceeded'];
1600
  $total_limit_exceeded = $variables['total_limit_exceeded'];
1601
  $allowed_roles = $variables['allowed_roles'];
1602
  $closed = $variables['closed'];
1603
  $cached = $variables['cached'];
1604

    
1605
  $type = 'status';
1606

    
1607
  if ($closed) {
1608
    $message = t('Submissions for this form are closed.');
1609
  }
1610
  // If open and not allowed to submit the form, give an explanation.
1611
  elseif (array_search(TRUE, $allowed_roles) === FALSE && $user->uid != 1) {
1612
    if (empty($allowed_roles)) {
1613
      // No roles are allowed to submit the form.
1614
      $message = t('Submissions for this form are closed.');
1615
    }
1616
    elseif (isset($allowed_roles[2])) {
1617
      // The "authenticated user" role is allowed to submit and the user is currently logged-out.
1618
      $login = url('user/login', array('query' => drupal_get_destination()));
1619
      $register = url('user/register', array('query' => drupal_get_destination()));
1620
      if (variable_get('user_register', 1) == 0) {
1621
        $message = t('You must <a href="!login">login</a> to view this form.', array('!login' => $login));
1622
      }
1623
      else {
1624
        $message = t('You must <a href="!login">login</a> or <a href="!register">register</a> to view this form.', array('!login' => $login, '!register' => $register));
1625
      }
1626
    }
1627
    else {
1628
      // The user must be some other role to submit.
1629
      $message = t('You do not have permission to view this form.');
1630
      $type = 'error';
1631
    }
1632
  }
1633

    
1634
  // If the user has exceeded the limit of submissions, explain the limit.
1635
  elseif ($user_limit_exceeded && !$cached) {
1636
    if ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] > 1) {
1637
      $message = t('You have submitted this form the maximum number of times (@count).', array('@count' => $node->webform['submit_limit']));
1638
    }
1639
    elseif ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] == 1) {
1640
      $message = t('You have already submitted this form.');
1641
    }
1642
    else {
1643
      $message = t('You may not submit another entry at this time.');
1644
    }
1645
    $type = 'error';
1646
  }
1647
  elseif ($total_limit_exceeded && !$cached) {
1648
    if ($node->webform['total_submit_interval'] == -1 && $node->webform['total_submit_limit'] > 1) {
1649
      $message = t('This form has received the maximum number of entries.');
1650
    }
1651
    else {
1652
      $message = t('You may not submit another entry at this time.');
1653
    }
1654
  }
1655

    
1656
  // If the user has submitted before, give them a link to their submissions.
1657
  if ($submission_count > 0 && $node->webform['submit_notice'] == 1 && !$cached) {
1658
    if (empty($message)) {
1659
      $message = t('You have already submitted this form.') . ' ' . t('<a href="!url">View your previous submissions</a>.', array('!url' => url('node/' . $node->nid . '/submissions')));
1660
    }
1661
    else {
1662
      $message .= ' ' . t('<a href="!url">View your previous submissions</a>.', array('!url' => url('node/' . $node->nid . '/submissions')));
1663
    }
1664
  }
1665

    
1666
  if ($page && isset($message)) {
1667
    drupal_set_message($message, $type, FALSE);
1668
  }
1669
}
1670

    
1671
/**
1672
 * Implements hook_mail().
1673
 */
1674
function webform_mail($key, &$message, $params) {
1675
  $message['headers'] = array_merge($message['headers'], $params['headers']);
1676
  $message['subject'] = $params['subject'];
1677
  $message['body'][] = $params['message'];
1678
}
1679

    
1680
/**
1681
 * Implements hook_block_info().
1682
 */
1683
function webform_block_info() {
1684
  $blocks = array();
1685
  $webform_node_types = webform_variable_get('webform_node_types');
1686
  if (!empty($webform_node_types)) {
1687
    $query = db_select('webform', 'w')->fields('w')->fields('n', array('title'));
1688
    $query->leftJoin('node', 'n', 'w.nid = n.nid');
1689
    $query->condition('w.block', 1);
1690
    $query->condition('n.type', $webform_node_types, 'IN');
1691
    $result = $query->execute();
1692
    foreach ($result as $data) {
1693
      $blocks['client-block-' . $data->nid] = array(
1694
        'info' => t('Webform: !title', array('!title' => $data->title)),
1695
        'cache' => DRUPAL_NO_CACHE,
1696
      );
1697
    }
1698
  }
1699
  return $blocks;
1700
}
1701

    
1702
/**
1703
 * Implements hook_block_view().
1704
 */
1705
function webform_block_view($delta = '') {
1706
  global $user;
1707

    
1708
  // Load the block-specific configuration settings.
1709
  $webform_blocks = variable_get('webform_blocks', array());
1710
  $settings = isset($webform_blocks[$delta]) ? $webform_blocks[$delta] : array();
1711
  $settings += array(
1712
    'display' => 'form',
1713
    'pages_block' => 0,
1714
  );
1715

    
1716
  // Get the node ID from delta.
1717
  $nid = drupal_substr($delta, strrpos($delta, '-') + 1);
1718

    
1719
  // Load node in current language.
1720
  if (module_exists('translation')) {
1721
    global $language;
1722
    if (($translations = translation_node_get_translations($nid)) && (isset($translations[$language->language]))) {
1723
      $nid = $translations[$language->language]->nid;
1724
    }
1725
  }
1726

    
1727
  // The webform node to display in the block.
1728
  $node = node_load($nid);
1729

    
1730
  // Return if user has no access to the webform node.
1731
  if (!node_access('view', $node)) {
1732
    return;
1733
  }
1734

    
1735
  // This is a webform node block.
1736
  $node->webform_block = TRUE;
1737

    
1738
  // Use the node title for the block title.
1739
  $subject = $node->title;
1740

    
1741
  // If not displaying pages in the block, set the #action property on the form.
1742
  if ($settings['pages_block']) {
1743
    $node->webform['action'] = FALSE;
1744
  }
1745
  else {
1746
    $query = array_diff_key($_GET, array('q' => ''));
1747
    $node->webform['action'] = url('node/' . $node->nid, array('query' => $query));
1748
  }
1749

    
1750
  // Generate the content of the block based on display settings.
1751
  if ($settings['display'] == 'form') {
1752
    webform_node_view($node, 'full');
1753
    $content = isset($node->content['webform']) ? $node->content['webform'] : array();
1754
  }
1755
  else {
1756
    $teaser = ($settings['display'] == 'teaser') ? 'teaser' : 'full';
1757
    $content = node_view($node, $teaser);
1758
  }
1759

    
1760
  // Add contextual links for the webform node if they aren't already there.
1761
  if (!isset($content['#contextual_links']['node'])) {
1762
    $content['#contextual_links']['node'] = array('node', array($node->nid));
1763
  }
1764

    
1765
  // Create the block.
1766
  // Note that we render the content immediately here rather than passing back
1767
  // a renderable so that if the block is empty it is hidden.
1768
  $block = array(
1769
    'subject' => $subject,
1770
    'content' => drupal_render($content),
1771
  );
1772
  return $block;
1773
}
1774

    
1775
/**
1776
 * Implements hook_block_configure().
1777
 */
1778
function webform_block_configure($delta = '') {
1779
  // Load the block-specific configuration settings.
1780
  $webform_blocks = variable_get('webform_blocks', array());
1781
  $settings = isset($webform_blocks[$delta]) ? $webform_blocks[$delta] : array();
1782
  $settings += array(
1783
    'display' => 'form',
1784
    'pages_block' => 0,
1785
  );
1786

    
1787
  $form = array();
1788
  $form['display'] = array(
1789
    '#type' => 'radios',
1790
    '#title' => t('Display mode'),
1791
    '#default_value' => $settings['display'],
1792
    '#options' => array(
1793
      'form' => t('Form only'),
1794
      'full' => t('Full node'),
1795
      'teaser' => t('Teaser'),
1796
    ),
1797
    '#description' => t('The display mode determines how much of the webform to show within the block.'),
1798
  );
1799

    
1800
  $form['pages_block'] = array(
1801
    '#type' => 'checkbox',
1802
    '#title' => t('Show all webform pages in block'),
1803
    '#default_value' => $settings['pages_block'],
1804
    '#description' => t('By default multi-page webforms redirect to the node page for all pages after the first one. If checked, all pages will be shown in the block instead.'),
1805
  );
1806

    
1807
  return $form;
1808
}
1809

    
1810
/**
1811
 * Implements hook_block_save().
1812
 */
1813
function webform_block_save($delta = '', $edit = array()) {
1814
  // Load the previously defined block-specific configuration settings.
1815
  $settings = variable_get('webform_blocks', array());
1816
  // Build the settings array.
1817
  $new_settings[$delta] = array(
1818
    'display' => $edit['display'],
1819
    'pages_block' => $edit['pages_block'],
1820
  );
1821
  // We store settings for multiple blocks in just one variable
1822
  // so we merge the existing settings with the new ones before save.
1823
  variable_set('webform_blocks', array_merge($settings, $new_settings));
1824
}
1825

    
1826
/**
1827
 * Client form generation function. If this is displaying an existing
1828
 * submission, pass in the $submission variable with the contents of the
1829
 * submission to be displayed.
1830
 *
1831
 * @param $form
1832
 *   The current form array (always empty).
1833
 * @param $form_state
1834
 *   The current form values of a submission, used in multipage webforms.
1835
 * @param $node
1836
 *   The current webform node.
1837
 * @param $submission
1838
 *   An object containing information about the form submission if we're
1839
 *   displaying a result.
1840
 * @param $is_draft
1841
 *   Optional. Set to TRUE if displaying a draft.
1842
 * @param $filter
1843
 *   Whether or not to filter the contents of descriptions and values when
1844
 *   building the form. Values need to be unfiltered to be editable by
1845
 *   Form Builder.
1846
 */
1847
function webform_client_form($form, &$form_state, $node, $submission, $is_draft = FALSE, $filter = TRUE) {
1848
  global $user;
1849

    
1850
  // Attach necessary JavaScript and CSS.
1851
  $form['#attached'] = array(
1852
    'css' => array(drupal_get_path('module', 'webform') . '/css/webform.css'),
1853
    'js' => array(drupal_get_path('module', 'webform') . '/js/webform.js'),
1854
  );
1855
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.components');
1856
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.submissions');
1857

    
1858
  $form['#process'] = array(
1859
    'webform_client_form_includes',
1860
  );
1861

    
1862
  // If in a multi-step form, a submission ID may be specified in form state.
1863
  // Load this submission. This allows anonymous users to use auto-save.
1864
  if (empty($submission) && !empty($form_state['values']['details']['sid'])) {
1865
    $submission = webform_get_submission($node->nid, $form_state['values']['details']['sid']);
1866
    $is_draft = $submission->is_draft;
1867
  }
1868

    
1869
  // Bind arguments to $form to make them available in theming and form_alter.
1870
  $form['#node'] = $node;
1871
  $form['#submission'] = $submission;
1872
  $form['#is_draft'] = $is_draft;
1873
  $form['#filter'] = $filter;
1874

    
1875
  // Add a theme function for this form.
1876
  $form['#theme'] = array('webform_form_' . $node->nid, 'webform_form');
1877

    
1878
  // Add a css class for all client forms.
1879
  $form['#attributes'] = array('class' => array('webform-client-form'));
1880

    
1881
  // Set the encoding type (necessary for file uploads).
1882
  $form['#attributes']['enctype'] = 'multipart/form-data';
1883

    
1884
  // Sometimes when displaying a webform as a teaser or block, a custom action
1885
  // property is set to direct the user to the node page.
1886
  if (!empty($node->webform['action'])) {
1887
    $form['#action'] = $node->webform['action'];
1888
  }
1889

    
1890
  $form['#submit'] = array('webform_client_form_pages', 'webform_client_form_submit');
1891
  $form['#validate'] = array('webform_client_form_validate');
1892

    
1893
  if (is_array($node->webform['components']) && !empty($node->webform['components'])) {
1894
    // Prepare a new form array.
1895
    $form['submitted'] = array(
1896
      '#tree' => TRUE
1897
    );
1898
    $form['details'] = array(
1899
      '#tree' => TRUE,
1900
    );
1901

    
1902
    // Put the components into a tree structure.
1903
    if (!isset($form_state['storage']['component_tree'])) {
1904
      $form_state['webform']['component_tree'] = array();
1905
      $form_state['webform']['page_count'] = 1;
1906
      $form_state['webform']['page_num'] = 1;
1907
      _webform_components_tree_build($node->webform['components'], $form_state['webform']['component_tree'], 0, $form_state['webform']['page_count']);
1908
    }
1909
    else {
1910
      $form_state['webform']['component_tree'] = $form_state['storage']['component_tree'];
1911
      $form_state['webform']['page_count'] = $form_state['storage']['page_count'];
1912
      $form_state['webform']['page_num'] = $form_state['storage']['page_num'];
1913
    }
1914

    
1915
    // Shorten up our variable names.
1916
    $component_tree = $form_state['webform']['component_tree'];
1917
    $page_count = $form_state['webform']['page_count'];
1918
    $page_num = $form_state['webform']['page_num'];
1919

    
1920
    if ($page_count > 1) {
1921
      $next_page_labels = array();
1922
      $prev_page_labels = array();
1923
    }
1924

    
1925
    // Recursively add components to the form. The unfiltered version of the
1926
    // form (typically used in Form Builder), includes all components.
1927
    foreach ($component_tree['children'] as $cid => $component) {
1928
      $component_value = isset($form_state['values']['submitted'][$cid]) ? $form_state['values']['submitted'][$cid] : NULL;
1929
      if ($filter == FALSE || _webform_client_form_rule_check($node, $component, $page_num, $form_state)) {
1930
        if ($component['type'] == 'pagebreak') {
1931
          $next_page_labels[$component['page_num'] - 1] = !empty($component['extra']['next_page_label']) ? t($component['extra']['next_page_label']) : t('Next Page >');
1932
          $prev_page_labels[$component['page_num']] = !empty($component['extra']['prev_page_label']) ? t($component['extra']['prev_page_label']) : t('< Previous Page');
1933
        }
1934
        _webform_client_form_add_component($node, $component, $component_value, $form['submitted'], $form, $form_state, $submission, 'form', $page_num, $filter);
1935
      }
1936
    }
1937

    
1938
    // These form details help managing data upon submission.
1939
    $form['details']['nid'] = array(
1940
      '#type' => 'value',
1941
      '#value' => $node->nid,
1942
    );
1943
    $form['details']['sid'] = array(
1944
      '#type' => 'hidden',
1945
      '#value' => isset($submission->sid) ? $submission->sid : NULL,
1946
    );
1947
    $form['details']['uid'] = array(
1948
      '#type' => 'value',
1949
      '#value' => isset($submission->uid) ? $submission->uid : $user->uid,
1950
    );
1951
    $form['details']['page_num'] = array(
1952
      '#type'  => 'hidden',
1953
      '#value' => $page_num,
1954
    );
1955
    $form['details']['page_count'] = array(
1956
      '#type'  => 'hidden',
1957
      '#value' => $page_count,
1958
    );
1959
    $form['details']['finished'] = array(
1960
      '#type' => 'hidden',
1961
      '#value' => isset($submission->is_draft) ? (!$submission->is_draft) : 0,
1962
    );
1963

    
1964
    // Add buttons for pages, drafts, and submissions.
1965
    $form['actions'] = array(
1966
      '#type' => 'actions',
1967
      '#weight' => 1000,
1968
    );
1969

    
1970
    // Add the draft button.
1971
    if ($node->webform['allow_draft'] && (empty($submission) || $submission->is_draft) && $user->uid != 0) {
1972
      $form['actions']['draft'] = array(
1973
        '#type' => 'submit',
1974
        '#value' => t('Save Draft'),
1975
        '#weight' => -2,
1976
        '#validate' => array(),
1977
        '#attributes' => array('formnovalidate' => 'formnovalidate'),
1978
      );
1979
    }
1980

    
1981
    if ($page_count > 1) {
1982
      // Add the submit button(s).
1983
      if ($page_num > 1) {
1984
        $form['actions']['previous'] = array(
1985
          '#type' => 'submit',
1986
          '#value' => $prev_page_labels[$page_num],
1987
          '#weight' => 5,
1988
          '#validate' => array(),
1989
          '#attributes' => array('formnovalidate' => 'formnovalidate'),
1990
        );
1991
      }
1992
      if ($page_num == $page_count) {
1993
        $form['actions']['submit'] = array(
1994
          '#type' => 'submit',
1995
          '#value' => empty($node->webform['submit_text']) ? t('Submit') : t($node->webform['submit_text']),
1996
          '#weight' => 10,
1997
        );
1998
      }
1999
      elseif ($page_num < $page_count) {
2000
        $form['actions']['next'] = array(
2001
          '#type' => 'submit',
2002
          '#value' => $next_page_labels[$page_num],
2003
          '#weight' => 10,
2004
        );
2005
      }
2006
    }
2007
    else {
2008
      // Add the submit button.
2009
      $form['actions']['submit'] = array(
2010
        '#type' => 'submit',
2011
        '#value' => empty($node->webform['submit_text']) ? t('Submit') : t($node->webform['submit_text']),
2012
        '#weight' => 10,
2013
      );
2014
    }
2015
  }
2016

    
2017
  return $form;
2018
}
2019

    
2020
/**
2021
 * Process function for webform_client_form().
2022
 *
2023
 * Include all the enabled components for this form to ensure availability.
2024
 */
2025
function webform_client_form_includes($form, $form_state) {
2026
  $components = webform_components();
2027
  foreach ($components as $component_type => $component) {
2028
    webform_component_include($component_type);
2029
  }
2030
  return $form;
2031
}
2032

    
2033
/**
2034
 * Check if a component should be displayed on the current page.
2035
 */
2036
function _webform_client_form_rule_check($node, $component, $page_num, $form_state = NULL, $submission = NULL) {
2037
  $conditional_values = isset($component['extra']['conditional_values']) ? $component['extra']['conditional_values'] : NULL;
2038
  $conditional_component = isset($component['extra']['conditional_component']) && isset($node->webform['components'][$component['extra']['conditional_component']]) ? $node->webform['components'][$component['extra']['conditional_component']] : NULL;
2039
  $conditional_cid = $conditional_component['cid'];
2040

    
2041
  // Check the rules for this entire page. Note individual page breaks are
2042
  // checked down below in the individual component rule checks.
2043
  $show_page = TRUE;
2044
  if ($component['page_num'] > 1 && $component['type'] != 'pagebreak') {
2045
    foreach ($node->webform['components'] as $cid => $page_component) {
2046
      if ($page_component['type'] == 'pagebreak' && $page_component['page_num'] == $page_num) {
2047
        $show_page = _webform_client_form_rule_check($node, $page_component, $page_num, $form_state, $submission);
2048
        break;
2049
      }
2050
    }
2051
  }
2052

    
2053
  // Check any parents' visibility rules.
2054
  $show_parent = $show_page;
2055
  if ($show_parent && $component['pid'] && isset($node->webform['components'][$component['pid']])) {
2056
    $parent_component = $node->webform['components'][$component['pid']];
2057
    $show_parent = _webform_client_form_rule_check($node, $parent_component, $page_num, $form_state, $submission);
2058
  }
2059

    
2060
  // Check the individual component rules.
2061
  $show_component = $show_parent;
2062
  if ($show_component && ($page_num == 0 || $component['page_num'] == $page_num) && $conditional_component && strlen(trim($conditional_values))) {
2063
    $input_values = array();
2064
    if (isset($form_state)) {
2065
      $input_value = isset($form_state['values']['submitted'][$conditional_cid]) ? $form_state['values']['submitted'][$conditional_cid] : NULL;
2066
      $input_values = is_array($input_value) ? $input_value : array($input_value);
2067
    }
2068
    elseif (isset($submission)) {
2069
      $input_values = isset($submission->data[$conditional_cid]['value']) ? $submission->data[$conditional_cid]['value'] : array();
2070
    }
2071

    
2072
    $test_values = array_map('trim', explode("\n", $conditional_values));
2073
    if (empty($input_values) && !empty($test_values)) {
2074
      $show_component = FALSE;
2075
    }
2076
    else {
2077
      foreach ($input_values as $input_value) {
2078
        if ($show_component = in_array($input_value, $test_values)) {
2079
          break;
2080
        }
2081
      }
2082
    }
2083

    
2084
    if ($component['extra']['conditional_operator'] == '!=') {
2085
      $show_component = !$show_component;
2086
    }
2087
  }
2088

    
2089
  // Private component?
2090
  if ($component['extra']['private']) {
2091
    $show_component = webform_results_access($node);
2092
  }
2093

    
2094
  return $show_component;
2095
}
2096

    
2097
/**
2098
 * Add a component to a renderable array. Called recursively for fieldsets.
2099
 *
2100
 * This function assists in the building of the client form, as well as the
2101
 * display of results, and the text of e-mails.
2102
 *
2103
 * @param $component
2104
 *   The component to be added to the form.
2105
 * @param $component_value
2106
 *   The components current value if known.
2107
 * @param $parent_fieldset
2108
 *   The fieldset to which this element will be added.
2109
 * @param $form
2110
 *   The entire form array.
2111
 * @param $form_state
2112
 *   The form state.
2113
 * @param $submission
2114
 *   The Webform submission as retrieved from the database.
2115
 * @param $format
2116
 *   The format the form should be displayed as. May be one of the following:
2117
 *   - form: Show as an editable form.
2118
 *   - html: Show as HTML results.
2119
 *   - text: Show as plain text.
2120
 * @param $filter
2121
 *   Whether the form element properties should be filtered. Only set to FALSE
2122
 *   if needing the raw properties for editing.
2123
 *
2124
 * @see webform_client_form()
2125
 * @see webform_submission_render()
2126
 */
2127
function _webform_client_form_add_component($node, $component, $component_value, &$parent_fieldset, &$form, $form_state, $submission, $format = 'form', $page_num = 0, $filter = TRUE) {
2128
  $cid = $component['cid'];
2129

    
2130
  // Load with submission information if necessary.
2131
  if ($format != 'form') {
2132
    // This component is display only.
2133
    $data = empty($submission->data[$cid]['value']) ? NULL : $submission->data[$cid]['value'];
2134
    if ($display_element = webform_component_invoke($component['type'], 'display', $component, $data, $format)) {
2135
      // Ensure the component is added as a property.
2136
      $display_element['#webform_component'] = $component;
2137

    
2138
      // Allow modules to modify a "display only" webform component.
2139
      drupal_alter('webform_component_display', $display_element, $component);
2140

    
2141
      // The form_builder() function usually adds #parents and #id for us, but
2142
      // because these are not marked for #input, we need to add them manually.
2143
      if (!isset($display_element['#parents'])) {
2144
        $parents = isset($parent_fieldset['#parents']) ? $parent_fieldset['#parents'] : array('submitted');
2145
        $parents[] = $component['form_key'];
2146
        $display_element['#parents'] = $parents;
2147
      }
2148
      if (!isset($display_element['#id'])) {
2149
        $display_element['#id'] = drupal_clean_css_identifier('edit-' . implode('-', $display_element['#parents']));
2150
      }
2151

    
2152
      // Add the element into the proper parent in the display.
2153
      $parent_fieldset[$component['form_key']] = $display_element;
2154
    }
2155
  }
2156
  // Show the component only on its form page, or if building an unfiltered
2157
  // version of the form (such as for Form Builder).
2158
  elseif ($component['page_num'] == $page_num || $filter == FALSE) {
2159
    // Add this user-defined field to the form (with all the values that are always available).
2160
    $data = isset($submission->data[$cid]['value']) ? $submission->data[$cid]['value'] : NULL;
2161
    if ($element = webform_component_invoke($component['type'], 'render', $component, $data, $filter)) {
2162
      // Ensure the component is added as a property.
2163
      $element['#webform_component'] = $component;
2164

    
2165
      // The 'private' option is in most components, but it's not a real
2166
      // property. Add it for Form Builder compatibility.
2167
      if (webform_component_feature($component['type'], 'private')) {
2168
        $element['#webform_private'] = $component['extra']['private'];
2169
      }
2170

    
2171
      // Allow modules to modify a webform component that is going to be render in a form.
2172
      drupal_alter('webform_component_render', $element, $component);
2173

    
2174
      // Add the element into the proper parent in the form.
2175
      $parent_fieldset[$component['form_key']] = $element;
2176

    
2177
      // Override the value if one already exists in the form state.
2178
      if (isset($component_value)) {
2179
        $parent_fieldset[$component['form_key']]['#default_value'] = $component_value;
2180
        if (is_array($component_value)) {
2181
          foreach ($component_value as $key => $value) {
2182
            if (isset($parent_fieldset[$component['form_key']][$key])) {
2183
              $parent_fieldset[$component['form_key']][$key]['#default_value'] = $value;
2184
            }
2185
          }
2186
        }
2187
      }
2188
    }
2189
    else {
2190
      drupal_set_message(t('The webform component @type is not able to be displayed', array('@type' => $component['type'])));
2191
    }
2192
  }
2193

    
2194
  // Disable validation initially on all elements. We manually validate
2195
  // all webform elements in webform_client_form_validate().
2196
  if (isset($parent_fieldset[$component['form_key']])) {
2197
    $parent_fieldset[$component['form_key']]['#validated'] = TRUE;
2198
    $parent_fieldset[$component['form_key']]['#webform_validated'] = FALSE;
2199
  }
2200

    
2201
  if (isset($component['children']) && is_array($component['children'])) {
2202
    foreach ($component['children'] as $scid => $subcomponent) {
2203
      $subcomponent_value = isset($form_state['values']['submitted'][$scid]) ? $form_state['values']['submitted'][$scid] : NULL;
2204
      if (_webform_client_form_rule_check($node, $subcomponent, $page_num, $form_state, $submission)) {
2205
        _webform_client_form_add_component($node, $subcomponent, $subcomponent_value, $parent_fieldset[$component['form_key']], $form, $form_state, $submission, $format, $page_num, $filter);
2206
      }
2207
    }
2208
  }
2209
}
2210

    
2211
function webform_client_form_validate($form, &$form_state) {
2212
  $node = node_load($form_state['values']['details']['nid']);
2213
  $finished = $form_state['values']['details']['finished'];
2214

    
2215
  // Check that the submissions have not exceeded the total submission limit.
2216
  if ($node->webform['total_submit_limit'] != -1) {
2217
    module_load_include('inc', 'webform', 'includes/webform.submissions');
2218
    // Check if the total number of entries was reached before the user submitted
2219
    // the form.
2220
    if (!$finished && $total_limit_exceeded = _webform_submission_total_limit_check($node)) {
2221
      // Show the user the limit has exceeded.
2222
      theme('webform_view_messages', array('node' => $node, 'teaser' => 0, 'page' => 1, 'submission_count' => 0, 'total_limit_exceeded' => $total_limit_exceeded, 'allowed_roles' => array_keys(user_roles()), 'closed' => FALSE, 'cached' => FALSE));
2223
      form_set_error('', NULL);
2224
      return;
2225
    }
2226
  }
2227

    
2228
  // Check that the user has not exceeded the submission limit.
2229
  // This usually will only apply to anonymous users when the page cache is
2230
  // enabled, because they may submit the form even if they do not have access.
2231
  if ($node->webform['submit_limit'] != -1) { // -1: Submissions are never throttled.
2232
    module_load_include('inc', 'webform', 'includes/webform.submissions');
2233

    
2234
    if (!$finished && $user_limit_exceeded = _webform_submission_user_limit_check($node)) {
2235
      // Assume that webform_view_messages will print out the necessary message,
2236
      // then stop the processing of the form with an empty form error.
2237
      theme('webform_view_messages', array('node' => $node, 'teaser' => 0, 'page' => 1, 'submission_count' => 0, 'user_limit_exceeded' => $user_limit_exceeded, 'allowed_roles' => array_keys(user_roles()), 'closed' => FALSE, 'cached' => FALSE));
2238
      form_set_error('', NULL);
2239
      return;
2240
    }
2241
  }
2242

    
2243
  // Run all #element_validate and #required checks. These are skipped initially
2244
  // by setting #validated = TRUE on all components when they are added.
2245
  _webform_client_form_validate($form, $form_state);
2246
}
2247

    
2248
/**
2249
 * Recursive validation function to trigger normal Drupal validation.
2250
 *
2251
 * This function imitates _form_validate in Drupal's form.inc, only it sets
2252
 * a different property to ensure that validation has occurred.
2253
 */
2254
function _webform_client_form_validate($elements, &$form_state, $first_run = TRUE) {
2255
  static $form;
2256
  if ($first_run) {
2257
    $form = $elements;
2258
  }
2259

    
2260
  // Recurse through all children.
2261
  foreach (element_children($elements) as $key) {
2262
    if (isset($elements[$key]) && $elements[$key]) {
2263
      _webform_client_form_validate($elements[$key], $form_state, FALSE);
2264
    }
2265
  }
2266
  // Validate the current input.
2267
  if (isset($elements['#webform_validated']) && $elements['#webform_validated'] == FALSE) {
2268
    if (isset($elements['#needs_validation'])) {
2269
      // Make sure a value is passed when the field is required.
2270
      // A simple call to empty() will not cut it here as some fields, like
2271
      // checkboxes, can return a valid value of '0'. Instead, check the
2272
      // length if it's a string, and the item count if it's an array. For
2273
      // radios, FALSE means that no value was submitted, so check that too.
2274
      if ($elements['#required'] && (!count($elements['#value']) || (is_string($elements['#value']) && strlen(trim($elements['#value'])) == 0) || $elements['#value'] === FALSE)) {
2275
        form_error($elements, t('!name field is required.', array('!name' => $elements['#title'])));
2276
      }
2277

    
2278
      // Verify that the value is not longer than #maxlength.
2279
      if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
2280
        form_error($elements, t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => drupal_strlen($elements['#value']))));
2281
      }
2282

    
2283
      if (isset($elements['#options']) && isset($elements['#value'])) {
2284
        if ($elements['#type'] == 'select') {
2285
          $options = form_options_flatten($elements['#options']);
2286
        }
2287
        else {
2288
          $options = $elements['#options'];
2289
        }
2290
        if (is_array($elements['#value'])) {
2291
          $value = $elements['#type'] == 'checkboxes' ? array_keys(array_filter($elements['#value'])) : $elements['#value'];
2292
          foreach ($value as $v) {
2293
            if (!isset($options[$v])) {
2294
              form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
2295
              watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
2296
            }
2297
          }
2298
        }
2299
        elseif ($elements['#value'] !== '' && !isset($options[$elements['#value']])) {
2300
          form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
2301
          watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
2302
        }
2303
      }
2304
    }
2305

    
2306
    // Call any element-specific validators. These must act on the element
2307
    // #value data.
2308
    if (isset($elements['#element_validate'])) {
2309
      foreach ($elements['#element_validate'] as $function) {
2310
        if (function_exists($function))  {
2311
          $function($elements, $form_state, $form);
2312
        }
2313
      }
2314
    }
2315
    $elements['#webform_validated'] = TRUE;
2316
  }
2317
}
2318

    
2319
/**
2320
 * Handle the processing of pages and conditional logic.
2321
 */
2322
function webform_client_form_pages($form, &$form_state) {
2323
  $node = node_load($form_state['values']['details']['nid']);
2324

    
2325
  // Multistep forms may not have any components on the first page.
2326
  if (!isset($form_state['values']['submitted'])) {
2327
    $form_state['values']['submitted'] = array();
2328
  }
2329

    
2330
  // Move special settings to storage.
2331
  if (isset($form_state['webform']['component_tree'])) {
2332
    $form_state['storage']['component_tree'] = $form_state['webform']['component_tree'];
2333
    $form_state['storage']['page_count'] = $form_state['webform']['page_count'];
2334
    $form_state['storage']['page_num'] = $form_state['webform']['page_num'];
2335
  }
2336

    
2337
  // Perform post processing by components.
2338
  _webform_client_form_submit_process($node, $form_state['values']['submitted']);
2339

    
2340
  // Flatten trees within the submission.
2341
  $form_state['values']['submitted_tree'] = $form_state['values']['submitted'];
2342
  $form_state['values']['submitted'] = _webform_client_form_submit_flatten($node, $form_state['values']['submitted']);
2343

    
2344
  // Assume the form is completed unless the page logic says otherwise.
2345
  $form_state['webform_completed'] = TRUE;
2346

    
2347
  // Check for a multi-page form that is not yet complete.
2348
  $submit_op = !empty($form['actions']['submit']['#value']) ? $form['actions']['submit']['#value'] : t('Submit');
2349
  $draft_op = !empty($form['actions']['draft']['#value']) ? $form['actions']['draft']['#value'] : t('Save Draft');
2350
  if (!in_array($form_state['values']['op'], array($submit_op, $draft_op))) {
2351
    // Store values from the current page in the form state storage.
2352
    if (is_array($form_state['values']['submitted'])) {
2353
      foreach ($form_state['values']['submitted'] as $key => $val) {
2354
        $form_state['storage']['submitted'][$key] = $val;
2355
      }
2356
    }
2357

    
2358
    // Update form state values with those from storage.
2359
    if (isset($form_state['storage']['submitted'])) {
2360
      foreach ($form_state['storage']['submitted'] as $key => $val) {
2361
        $form_state['values']['submitted'][$key] = $val;
2362
      }
2363
    }
2364

    
2365
    // Set the page number.
2366
    if (!isset($form_state['storage']['page_num'])) {
2367
      $form_state['storage']['page_num'] = 1;
2368
    }
2369
    if (end($form_state['clicked_button']['#parents']) == 'next') {
2370
      $direction = 1;
2371
    }
2372
    else {
2373
      $direction = 0;
2374
    }
2375

    
2376
    // If the next page has no components that need to be displayed, skip it.
2377
    if (isset($direction)) {
2378
      $components = $direction ? $node->webform['components'] : array_reverse($node->webform['components'], TRUE);
2379
      $last_component = end($node->webform['components']);
2380
      foreach ($components as $component) {
2381
        if ($component['type'] == 'pagebreak' && (
2382
            $direction == 1 && $component['page_num'] > $form_state['storage']['page_num'] ||
2383
            $direction == 0 && $component['page_num'] <= $form_state['storage']['page_num'])) {
2384
          $previous_pagebreak = $component;
2385
          continue;
2386
        }
2387
        if (isset($previous_pagebreak)) {
2388
          $page_num = $previous_pagebreak['page_num'] + $direction - 1;
2389
          // If we've found an component on this page, advance to that page.
2390
          if ($component['page_num'] == $page_num && _webform_client_form_rule_check($node, $component, $page_num, $form_state)) {
2391
            $form_state['storage']['page_num'] = $page_num;
2392
            break;
2393
          }
2394
          // If we've gotten to the end of the form without finding any more
2395
          // components, set the page number more than the max, ending the form.
2396
          elseif ($direction && $component['cid'] == $last_component['cid']) {
2397
            $form_state['storage']['page_num'] = $page_num + 1;
2398
          }
2399
        }
2400
      }
2401
    }
2402

    
2403
    // The form is done if the page number is greater than the page count.
2404
    $form_state['webform_completed'] = $form_state['storage']['page_num'] > $form_state['storage']['page_count'];
2405
  }
2406

    
2407
  // Merge any stored submission data for multistep forms.
2408
  if (isset($form_state['storage']['submitted'])) {
2409
    $original_values = is_array($form_state['values']['submitted']) ? $form_state['values']['submitted'] : array();
2410
    unset($form_state['values']['submitted']);
2411

    
2412
    foreach ($form_state['storage']['submitted'] as $key => $val) {
2413
      $form_state['values']['submitted'][$key] = $val;
2414
    }
2415
    foreach ($original_values as $key => $val) {
2416
      $form_state['values']['submitted'][$key] = $val;
2417
    }
2418

    
2419
    // Remove the variable so it doesn't show up in the additional processing.
2420
    unset($original_values);
2421
  }
2422

    
2423
  // Inform the submit handlers that a draft will be saved.
2424
  $form_state['save_draft'] = $form_state['values']['op'] == $draft_op || ($node->webform['auto_save'] && !$form_state['webform_completed']);
2425

    
2426
  // Determine what we need to do on the next page.
2427
  if (!empty($form_state['save_draft']) || !$form_state['webform_completed']) {
2428
    // Rebuild the form and display the current (on drafts) or next page.
2429
    $form_state['rebuild'] = TRUE;
2430
  }
2431
  else {
2432
    // Remove the form state storage now that we're done with the pages.
2433
    $form_state['rebuild'] = FALSE;
2434
    unset($form_state['storage']);
2435
  }
2436
}
2437

    
2438
/**
2439
 * Submit handler for saving the form values and sending e-mails.
2440
 */
2441
function webform_client_form_submit($form, &$form_state) {
2442
  module_load_include('inc', 'webform', 'includes/webform.submissions');
2443
  module_load_include('inc', 'webform', 'includes/webform.components');
2444
  global $user;
2445

    
2446
  if (empty($form_state['save_draft']) && empty($form_state['webform_completed'])) {
2447
    return;
2448
  }
2449

    
2450
  $node = $form['#node'];
2451
  $sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;
2452

    
2453
  // Check if user is submitting as a draft.
2454
  $is_draft = (int) !empty($form_state['save_draft']);
2455

    
2456
  if (!$sid) {
2457
    // Create a new submission object.
2458
    $submission = (object) array(
2459
      'nid' => $node->nid,
2460
      'uid' => $form_state['values']['details']['uid'],
2461
      'submitted' => REQUEST_TIME,
2462
      'remote_addr' => ip_address(),
2463
      'is_draft' => $is_draft,
2464
      'data' => webform_submission_data($node, $form_state['values']['submitted']),
2465
    );
2466
  }
2467
  else {
2468
    // To maintain time and user information, load the existing submission.
2469
    $submission = webform_get_submission($node->webform['nid'], $sid);
2470
    $submission->is_draft = $is_draft;
2471

    
2472
    // Merge with new submission data. The + operator maintains numeric keys.
2473
    // This maintains existing data with just-submitted data when a user resumes
2474
    // a submission previously saved as a draft.
2475
    $new_data = webform_submission_data($node, $form_state['values']['submitted']);
2476
    $submission->data = $new_data + $submission->data;
2477
  }
2478

    
2479
  // If there is no data to be saved (such as on a multipage form with no fields
2480
  // on the first page), process no further. Submissions with no data cannot
2481
  // be loaded from the database as efficiently, so we don't save them at all.
2482
  if (empty($submission->data)) {
2483
    return;
2484
  }
2485

    
2486
  // Save the submission to the database.
2487
  if (!$sid) {
2488
    // No sid was found thus insert it in the dataabase.
2489
    $form_state['values']['details']['sid'] = $sid = webform_submission_insert($node, $submission);
2490
    $form_state['values']['details']['is_new'] = TRUE;
2491

    
2492
    // Set a cookie including the server's submission time.
2493
    // The cookie expires in the length of the interval plus a day to compensate for different timezones.
2494
    if (variable_get('webform_use_cookies', 0)) {
2495
      $cookie_name = 'webform-' . $node->nid;
2496
      $time = REQUEST_TIME;
2497
      $params = session_get_cookie_params();
2498
      setcookie($cookie_name . '[' . $time . ']', $time, $time + $node->webform['submit_interval'] + 86400, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
2499
    }
2500

    
2501
    // Save session information about this submission for anonymous users,
2502
    // allowing them to access or edit their submissions.
2503
    if (!$user->uid && user_access('access own webform submissions')) {
2504
      $_SESSION['webform_submission'][$form_state['values']['details']['sid']] = $node->nid;
2505
    }
2506
  }
2507
  else {
2508
    // Sid was found thus update the existing sid in the database.
2509
    webform_submission_update($node, $submission);
2510
    $form_state['values']['details']['is_new'] = FALSE;
2511
  }
2512

    
2513
  // Check if this form is sending an email.
2514
  if (!$is_draft && !$form_state['values']['details']['finished']) {
2515
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);
2516
    webform_submission_send_mail($node, $submission);
2517
  }
2518

    
2519
  // Strip out empty tags added by WYSIWYG editors if needed.
2520
  $confirmation = strlen(trim(strip_tags($node->webform['confirmation']))) ? $node->webform['confirmation'] : '';
2521

    
2522
  // Clean up the redirect URL and filter it for webform tokens.
2523
  $redirect_url = trim($node->webform['redirect_url']);
2524
  $redirect_url = _webform_filter_values($redirect_url, $node, $submission, NULL, FALSE, TRUE);
2525

    
2526

    
2527
  // Remove the domain name from the redirect.
2528
  $redirect_url = preg_replace('/^' . preg_quote($GLOBALS['base_url'], '/') . '\//', '', $redirect_url);
2529

    
2530
  // Check confirmation and redirect_url fields.
2531
  $message = NULL;
2532
  $redirect = NULL;
2533
  $external_url = FALSE;
2534
  if (isset($form['actions']['draft']['#value']) && $form_state['values']['op'] == $form['actions']['draft']['#value']) {
2535
    $message = t('Submission saved. You may return to this form later and it will restore the current values.');
2536
  }
2537
  elseif ($is_draft) {
2538
    $redirect = NULL;
2539
  }
2540
  elseif (!empty($form_state['values']['details']['finished'])) {
2541
    $message = t('Submission updated.');
2542
  }
2543
  elseif ($redirect_url == '<none>') {
2544
    $redirect = NULL;
2545
  }
2546
  elseif ($redirect_url == '<confirmation>') {
2547
    $redirect = array('node/' . $node->nid . '/done', array('query' => array('sid' => $sid)));
2548
  }
2549
  elseif (valid_url($redirect_url, TRUE)) {
2550
    $redirect = $redirect_url;
2551
    $external_url = TRUE;
2552
  }
2553
  elseif ($redirect_url && strpos($redirect_url, 'http') !== 0) {
2554
    $parts = drupal_parse_url($redirect_url);
2555
    $parts['query'] ? ($parts['query']['sid'] = $sid) : ($parts['query'] = array('sid' => $sid));
2556
    $query = $parts['query'];
2557
    $redirect = array($parts['path'], array('query' => $query, 'fragment' => $parts['fragment']));
2558
  }
2559

    
2560
  // Show a message if manually set.
2561
  if (isset($message)) {
2562
    drupal_set_message($message);
2563
  }
2564
  // If redirecting and we have a confirmation message, show it as a message.
2565
  elseif (!$is_draft && !$external_url && (!empty($redirect_url) && $redirect_url != '<confirmation>') && !empty($confirmation)) {
2566
    drupal_set_message(check_markup($confirmation, $node->webform['confirmation_format'], '', TRUE));
2567
  }
2568

    
2569
  $form_state['redirect'] = $redirect;
2570
}
2571

    
2572
/**
2573
 * Post processes the submission tree with any updates from components.
2574
 *
2575
 * @param $node
2576
 *   The full webform node.
2577
 * @param $form_values
2578
 *   The form values for the form.
2579
 * @param $types
2580
 *   Optional. Specific types to perform processing.
2581
 * @param $parent
2582
 *   Internal use. The current parent CID whose children are being processed.
2583
 */
2584
function _webform_client_form_submit_process($node, &$form_values, $types = NULL, $parent = 0) {
2585
  if (is_array($form_values)) {
2586
    foreach ($form_values as $form_key => $value) {
2587
      $cid = webform_get_cid($node, $form_key, $parent);
2588
      if (is_array($value) && isset($node->webform['components'][$cid]['type']) && webform_component_feature($node->webform['components'][$cid]['type'], 'group')) {
2589
        _webform_client_form_submit_process($node, $form_values[$form_key], $types, $cid);
2590
      }
2591

    
2592
      if (isset($node->webform['components'][$cid])) {
2593
        // Call the component process submission function.
2594
        $component = $node->webform['components'][$cid];
2595
        if ((!isset($types) || in_array($component['type'], $types)) && webform_component_implements($component['type'], 'submit')) {
2596
          $form_values[$component['form_key']] = webform_component_invoke($component['type'], 'submit', $component, $form_values[$component['form_key']]);
2597
        }
2598
      }
2599
    }
2600
  }
2601
}
2602

    
2603
/**
2604
 * Flattens a submitted form back into a single array representation (rather than nested fields)
2605
 */
2606
function _webform_client_form_submit_flatten($node, $fieldset, $parent = 0) {
2607
  $values = array();
2608

    
2609
  if (is_array($fieldset)) {
2610
    foreach ($fieldset as $form_key => $value) {
2611
      $cid = webform_get_cid($node, $form_key, $parent);
2612

    
2613
      if (is_array($value) && webform_component_feature($node->webform['components'][$cid]['type'], 'group')) {
2614
        $values += _webform_client_form_submit_flatten($node, $value, $cid);
2615
      }
2616
      else {
2617
        $values[$cid] = $value;
2618
      }
2619
    }
2620
  }
2621

    
2622
  return $values;
2623
}
2624

    
2625
/**
2626
 * Prints the confirmation message after a successful submission.
2627
 */
2628
function _webform_confirmation($node) {
2629
  drupal_set_title($node->title);
2630
  webform_set_breadcrumb($node);
2631
  $sid = isset($_GET['sid']) ? $_GET['sid'] : NULL;
2632
  return theme(array('webform_confirmation_' . $node->nid, 'webform_confirmation'), array('node' => $node, 'sid' => $sid));
2633
}
2634

    
2635
/**
2636
 * Prepare for theming of the webform form.
2637
 */
2638
function template_preprocess_webform_form(&$vars) {
2639
  if (isset($vars['form']['details']['nid']['#value'])) {
2640
    $vars['nid'] = $vars['form']['details']['nid']['#value'];
2641
  }
2642
  elseif (isset($vars['form']['submission']['#value'])) {
2643
    $vars['nid'] = $vars['form']['submission']['#value']->nid;
2644
  }
2645
}
2646

    
2647
/**
2648
 * Prepare for theming of the webform submission confirmation.
2649
 */
2650
function template_preprocess_webform_confirmation(&$vars) {
2651
  $confirmation = check_markup($vars['node']->webform['confirmation'], $vars['node']->webform['confirmation_format'], '', TRUE);
2652
  // Strip out empty tags added by WYSIWYG editors if needed.
2653
  $vars['confirmation_message'] = strlen(trim(strip_tags($confirmation))) ? $confirmation : '';
2654
}
2655

    
2656
/**
2657
 * Prepare to theme the contents of e-mails sent by webform.
2658
 */
2659
function template_preprocess_webform_mail_message(&$vars) {
2660
  global $user;
2661

    
2662
  $vars['user'] = $user;
2663
  $vars['ip_address'] = ip_address();
2664
}
2665

    
2666
/**
2667
 * A Form API #pre_render function. Sets display based on #title_display.
2668
 *
2669
 * This function is used regularly in D6 for all elements, but specifically for
2670
 * fieldsets in D7, which don't support #title_display natively.
2671
 */
2672
function webform_element_title_display($element) {
2673
  if (isset($element['#title_display']) && strcmp($element['#title_display'], 'none') === 0) {
2674
    $element['#title'] = NULL;
2675
  }
2676
  return $element;
2677
}
2678

    
2679
/**
2680
 * Replacement for theme_form_element().
2681
 */
2682
function theme_webform_element($variables) {
2683
  // Ensure defaults.
2684
  $variables['element'] += array(
2685
    '#title_display' => 'before',
2686
  );
2687

    
2688
  $element = $variables['element'];
2689

    
2690
  // All elements using this for display only are given the "display" type.
2691
  if (isset($element['#format']) && $element['#format'] == 'html') {
2692
    $type = 'display';
2693
  }
2694
  else {
2695
    $type = (isset($element['#type']) && !in_array($element['#type'], array('markup', 'textfield', 'webform_email', 'webform_number'))) ? $element['#type'] : $element['#webform_component']['type'];
2696
  }
2697

    
2698
  // Convert the parents array into a string, excluding the "submitted" wrapper.
2699
  $nested_level = $element['#parents'][0] == 'submitted' ? 1 : 0;
2700
  $parents = str_replace('_', '-', implode('--', array_slice($element['#parents'], $nested_level)));
2701

    
2702
  $wrapper_classes = array(
2703
   'form-item',
2704
   'webform-component',
2705
   'webform-component-' . $type,
2706
  );
2707
  if (isset($element['#title_display']) && strcmp($element['#title_display'], 'inline') === 0) {
2708
    $wrapper_classes[] = 'webform-container-inline';
2709
  }
2710
  $output = '<div class="' . implode(' ', $wrapper_classes) . '" id="webform-component-' . $parents . '">' . "\n";
2711

    
2712
  // If #title is not set, we don't display any label or required marker.
2713
  if (!isset($element['#title'])) {
2714
    $element['#title_display'] = 'none';
2715
  }
2716
  $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . _webform_filter_xss($element['#field_prefix']) . '</span> ' : '';
2717
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . _webform_filter_xss($element['#field_suffix']) . '</span>' : '';
2718

    
2719
  switch ($element['#title_display']) {
2720
    case 'inline':
2721
    case 'before':
2722
    case 'invisible':
2723
      $output .= ' ' . theme('form_element_label', $variables);
2724
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
2725
      break;
2726

    
2727
    case 'after':
2728
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
2729
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
2730
      break;
2731

    
2732
    case 'none':
2733
    case 'attribute':
2734
      // Output no label and no required marker, only the children.
2735
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
2736
      break;
2737
  }
2738

    
2739
  if (!empty($element['#description'])) {
2740
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
2741
  }
2742

    
2743
  $output .= "</div>\n";
2744

    
2745
  return $output;
2746
}
2747

    
2748
/**
2749
 * Output a form element in plain text format.
2750
 */
2751
function theme_webform_element_text($variables) {
2752
  $element = $variables['element'];
2753
  $value = $variables['element']['#children'];
2754

    
2755
  $output = '';
2756
  $is_group = webform_component_feature($element['#webform_component']['type'], 'group');
2757

    
2758
  // Output the element title.
2759
  if (isset($element['#title'])) {
2760
    if ($is_group) {
2761
      $output .= '--' . $element['#title'] . '--';
2762
    }
2763
    elseif (!in_array(drupal_substr($element['#title'], -1), array('?', ':', '!', '%', ';', '@'))) {
2764
      $output .= $element['#title'] . ':';
2765
    }
2766
    else {
2767
      $output .= $element['#title'];
2768
    }
2769
  }
2770

    
2771
  // Wrap long values at 65 characters, allowing for a few fieldset indents.
2772
  // It's common courtesy to wrap at 75 characters in e-mails.
2773
  if ($is_group && drupal_strlen($value) > 65) {
2774
    $value = wordwrap($value, 65, "\n");
2775
    $lines = explode("\n", $value);
2776
    foreach ($lines as $key => $line) {
2777
      $lines[$key] = '  ' . $line;
2778
    }
2779
    $value = implode("\n", $lines);
2780
  }
2781

    
2782
  // Add the value to the output. Add a newline before the response if needed.
2783
  $output .= (strpos($value, "\n") === FALSE ? ' ' : "\n") . $value;
2784

    
2785
  // Indent fieldsets.
2786
  if ($is_group) {
2787
    $lines = explode("\n", $output);
2788
    foreach ($lines as $number => $line) {
2789
      if (strlen($line)) {
2790
        $lines[$number] = '  ' . $line;
2791
      }
2792
    }
2793
    $output = implode("\n", $lines);
2794
    $output .= "\n";
2795
  }
2796

    
2797
  if ($output) {
2798
    $output .= "\n";
2799
  }
2800

    
2801
  return $output;
2802
}
2803

    
2804
/**
2805
 * Theme a radio button and another element together.
2806
 *
2807
 * This is used in the e-mail configuration to show a radio button and a text
2808
 * field or select list on the same line.
2809
 */
2810
function theme_webform_inline_radio($variables) {
2811
  $element = $variables['element'];
2812

    
2813
  // Add element's #type and #name as class to aid with JS/CSS selectors.
2814
  $class = array('form-item');
2815
  if (!empty($element['#type'])) {
2816
    $class[] = 'form-type-' . strtr($element['#type'], '_', '-');
2817
  }
2818
  if (!empty($element['#name'])) {
2819
    $class[] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
2820
  }
2821

    
2822
  // Add container-inline to all elements.
2823
  $class[] = 'webform-container-inline';
2824
  if (isset($element['#inline_element']) && isset($variables['element']['#title'])) {
2825
    $variables['element']['#title'] .= ': ';
2826
  }
2827

    
2828
  $output = '<div class="' . implode(' ', $class) . '">' . "\n";
2829
  $output .= ' ' . $element['#children'];
2830
  if (!empty($element['#title'])) {
2831
    $output .= ' ' . theme('form_element_label', $variables) . "\n";
2832
  }
2833
  if (isset($element['#inline_element'])) {
2834
    $output .= ' ' . $element['#inline_element'] . "\n";
2835
  }
2836

    
2837
  if (!empty($element['#description'])) {
2838
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
2839
  }
2840

    
2841
  $output .= "</div>\n";
2842

    
2843
  return $output;
2844
}
2845

    
2846
/**
2847
 * Theme the headers when sending an email from webform.
2848
 *
2849
 * @param $node
2850
 *   The complete node object for the webform.
2851
 * @param $submission
2852
 *   The webform submission of the user.
2853
 * @param $email
2854
 *   If you desire to make different e-mail headers depending on the recipient,
2855
 *   you can check the $email['email'] property to output different content.
2856
 *   This will be the ID of the component that is a conditional e-mail
2857
 *   recipient. For the normal e-mails, it will have the value of 'default'.
2858
 * @return
2859
 *   An array of headers to be used when sending a webform email. If headers
2860
 *   for "From", "To", or "Subject" are set, they will take precedence over
2861
 *   the values set in the webform configuration.
2862
 */
2863
function theme_webform_mail_headers($variables) {
2864
  $headers = array(
2865
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
2866
  );
2867
  return $headers;
2868
}
2869

    
2870
/**
2871
 * Check if current user has a draft of this webform, and return the sid.
2872
 */
2873
function _webform_fetch_draft_sid($nid, $uid) {
2874
  return db_select('webform_submissions')
2875
    ->fields('webform_submissions', array('sid'))
2876
    ->condition('nid', $nid)
2877
    ->condition('uid', $uid)
2878
    ->condition('is_draft', 1)
2879
    ->orderBy('submitted', 'DESC')
2880
    ->execute()
2881
    ->fetchField();
2882
}
2883

    
2884
/**
2885
 * Filters all special tokens provided by webform, such as %post and %profile.
2886
 *
2887
 * @param $string
2888
 *   The string to have its tokens replaced.
2889
 * @param $node
2890
 *   If replacing node-level tokens, the node for which tokens will be created.
2891
 * @param $submission
2892
 *   If replacing submission-level tokens, the submission for which tokens will
2893
 *   be created.
2894
 * @param $email
2895
 *   If replacing tokens within the context of an e-mail, the Webform e-mail
2896
 *   settings array.
2897
 * @param $strict
2898
 *   Boolean value indicating if the results should be run through check_plain.
2899
 *   This is used any time the values will be output as HTML, but not in
2900
 *   default values or e-mails.
2901
 * @param $allow_anonymous
2902
 *   Boolean value indicating if all tokens should be replaced for anonymous
2903
 *   users, even if they contain sensitive user information such as %session or
2904
 *   %ip_address. This is disabled by default to prevent user data from being
2905
 *   preserved in the anonymous page cache and should only be used in
2906
 *   non-cached situations, such as e-mails.
2907
 */
2908
function _webform_filter_values($string, $node = NULL, $submission = NULL, $email = NULL, $strict = TRUE, $allow_anonymous = FALSE) {
2909
  global $user;
2910
  $replacements = &drupal_static(__FUNCTION__);
2911

    
2912
  // Don't do any filtering if the string is empty.
2913
  if (strlen(trim($string)) == 0) {
2914
    return $string;
2915
  }
2916

    
2917
  // Setup default token replacements.
2918
  if (!isset($replacements)) {
2919
    $replacements['unsafe'] = array();
2920
    $replacements['safe']['%site'] = variable_get('site_name', 'drupal');
2921
    $replacements['safe']['%date'] = format_date(REQUEST_TIME, 'long');
2922
  }
2923

    
2924
  // Node replacements.
2925
  if (isset($node) && !array_key_exists('%nid', $replacements['safe'])) {
2926
    $replacements['safe']['%nid'] = $node->nid;
2927
    $replacements['safe']['%title'] = $node->title;
2928
  }
2929

    
2930
  // Determine the display format.
2931
  $format = isset($email['html']) && $email['html'] ? 'html' : 'text';
2932

    
2933
  // Submission replacements.
2934
  if (isset($submission) && (!isset($replacements['email'][$format]) || (isset($replacements['unsafe']['%sid']) && $replacements['unsafe']['%sid'] != $submission->sid))) {
2935
    module_load_include('inc', 'webform', 'includes/webform.components');
2936

    
2937
    // Set the submission ID.
2938
    $replacements['unsafe']['%sid'] = $submission->sid;
2939

    
2940
    // E-mails may be sent in two formats, keep tokens separate for each one.
2941
    $replacements['email'][$format] = array();
2942

    
2943
    // Populate token values for each component.
2944
    foreach ($submission->data as $cid => $value) {
2945
      $component = $node->webform['components'][$cid];
2946

    
2947
      // Find by form key.
2948
      $parents = webform_component_parent_keys($node, $component);
2949
      $form_key = implode('][', $parents);
2950
      $display_element = webform_component_invoke($component['type'], 'display', $component, $value['value'], $format);
2951

    
2952
      // Ensure the component is added as a property.
2953
      $display_element['#webform_component'] = $component;
2954

    
2955
      if (empty($display_element['#parents'])) {
2956
        $display_element['#parents'] = array_merge(array('submitted'), $parents);
2957
      }
2958
      if (empty($display_element['#id'])) {
2959
        $display_element['#id'] = drupal_html_id('edit-' . implode('-', $display_element['#parents']));
2960
      }
2961
      $replacements['email'][$format]['%email[' . $form_key . ']'] = render($display_element);
2962
      $display_element['#theme_wrappers'] = array(); // Remove label and wrappers.
2963
      $replacements['email'][$format]['%value[' . $form_key . ']'] = render($display_element);
2964
    }
2965

    
2966
    // Provide blanks for components in the webform but not in the submission.
2967
    $missing_components = array_diff_key($node->webform['components'], $submission->data);
2968
    foreach ($missing_components as $component) {
2969
      $parents = webform_component_parent_keys($node, $component);
2970
      $form_key = implode('][', $parents);
2971
      $replacements['email'][$format]['%email[' . $form_key . ']'] = '';
2972
      $replacements['email'][$format]['%value[' . $form_key . ']'] = '';
2973
    }
2974

    
2975
    // Submission edit URL.
2976
    $replacements['unsafe']['%submission_url'] = url('node/' . $node->nid . '/submission/' . $submission->sid, array('absolute' => TRUE));
2977
  }
2978

    
2979
  // Token for the entire form tree for e-mails.
2980
  if (isset($submission) && isset($email)) {
2981
    $replacements['email'][$format]['%email_values'] = webform_submission_render($node, $submission, $email, $format);
2982
  }
2983

    
2984
  // Provide a list of candidates for token replacement.
2985
  $special_tokens = array(
2986
    'safe' => array(
2987
      '%get' => $_GET,
2988
      '%post' => $_POST,
2989
    ),
2990
    'unsafe' => array(
2991
      '%cookie' => isset($_COOKIE) ? $_COOKIE : array(),
2992
      '%session' => isset($_SESSION) ? $_SESSION : array(),
2993
      '%request' => $_REQUEST,
2994
      '%server' => $_SERVER,
2995
      '%profile' => (array) $user,
2996
    ),
2997
  );
2998

    
2999
  // Replacements of global variable tokens.
3000
  if (!isset($replacements['specials_set'])) {
3001
    $replacements['specials_set'] = TRUE;
3002

    
3003
    // Load profile information if available.
3004
    if ($user->uid) {
3005
      $account = user_load($user->uid);
3006
      $special_tokens['unsafe']['%profile'] = (array) $account;
3007
    }
3008

    
3009
    // User replacements.
3010
    if (!array_key_exists('%uid', $replacements['unsafe'])) {
3011
      $replacements['unsafe']['%uid'] = !empty($user->uid) ? $user->uid : '';
3012
      $replacements['unsafe']['%username'] = isset($user->name) ? $user->name : '';
3013
      $replacements['unsafe']['%useremail'] = isset($user->mail) ? $user->mail : '';
3014
      $replacements['unsafe']['%ip_address'] = ip_address();
3015
    }
3016

    
3017
    // Populate the replacements array with special variables.
3018
    foreach ($special_tokens as $safe_state => $tokens) {
3019
      foreach ($tokens as $token => $variable) {
3020
        // Safety check in case $_POST or some other global has been removed
3021
        // by a naughty module, in which case $variable may be NULL.
3022
        if (!is_array($variable)) {
3023
          continue;
3024
        }
3025

    
3026
        foreach ($variable as $key => $value) {
3027
          // This special case for profile module dates.
3028
          if ($token == '%profile' && is_array($value) && isset($value['year'])) {
3029
            $replacement = webform_strtodate(webform_date_format(), $value['month'] . '/' . $value['day'] . '/' . $value['year'], 'UTC');
3030
          }
3031
          else {
3032
            // Checking for complex types (arrays and objects) fails here with
3033
            // incomplete objects (see http://php.net/is_object), so we check
3034
            // for simple types instead.
3035
            $replacement = (is_string($value) || is_bool($value) || is_numeric($value)) ? $value : '';
3036
          }
3037
          $replacements[$safe_state][$token . '[' . $key . ']'] = $replacement;
3038
        }
3039
      }
3040
    }
3041
  }
3042

    
3043
  // Make a copy of the replacements so we don't affect the static version.
3044
  $safe_replacements = $replacements['safe'];
3045

    
3046
  // Restrict replacements for anonymous users. Not all tokens can be used
3047
  // because they may expose session or other private data to other users when
3048
  // anonymous page caching is enabled.
3049
  if ($user->uid || $allow_anonymous) {
3050
    $safe_replacements += $replacements['unsafe'];
3051
    if (isset($replacements['email'][$format])) {
3052
      $safe_replacements += $replacements['email'][$format];
3053
    }
3054
  }
3055
  else {
3056
    foreach ($replacements['unsafe'] as $key => $value) {
3057
      $safe_replacements[$key] = '';
3058
    }
3059
  }
3060

    
3061
  $find = array_keys($safe_replacements);
3062
  $replace = array_values($safe_replacements);
3063
  $string = str_replace($find, $replace, $string);
3064

    
3065
  // Clean up any unused tokens.
3066
  foreach ($special_tokens as $safe_state => $tokens) {
3067
    foreach (array_keys($tokens) as $token) {
3068
      $string = preg_replace('/\\' . $token . '\[\w+\]/', '', $string);
3069
    }
3070
  }
3071

    
3072
  return $strict ? _webform_filter_xss($string) : $string;
3073
}
3074

    
3075
/**
3076
 * Filters all special tokens provided by webform, and allows basic layout in descriptions.
3077
 */
3078
function _webform_filter_descriptions($string, $node = NULL, $submission = NULL) {
3079
  return strlen($string) == 0 ? '' : _webform_filter_xss(_webform_filter_values($string, $node, $submission, NULL, FALSE));
3080
}
3081

    
3082
/**
3083
 * Filter labels for display by running through XSS checks.
3084
 */
3085
function _webform_filter_xss($string) {
3086
  static $allowed_tags;
3087
  $allowed_tags = isset($allowed_tags) ? $allowed_tags : webform_variable_get('webform_allowed_tags');
3088
  return filter_xss($string, $allowed_tags);
3089
}
3090

    
3091

    
3092
/**
3093
 * Utility function to ensure that a webform record exists in the database.
3094
 *
3095
 * @param $node
3096
 *   The node object to check if a database entry exists.
3097
 * @return
3098
 *   This function should always return TRUE if no errors were encountered,
3099
 *   ensuring that a webform table row has been created. Will return FALSE if
3100
 *   a record does not exist and a new one could not be created.
3101
 */
3102
function webform_ensure_record(&$node) {
3103
  if (!$node->webform['record_exists']) {
3104
    // Even though webform_node_insert() would set this property to TRUE,
3105
    // we set record_exists to trigger a difference from the defaults.
3106
    $node->webform['record_exists'] = TRUE;
3107
    webform_node_insert($node);
3108
  }
3109
  return $node->webform['record_exists'];
3110
}
3111

    
3112
/**
3113
 * Utility function to check if a webform record is necessary in the database.
3114
 *
3115
 * If the node is no longer using any webform settings, this function will
3116
 * delete the settings from the webform table. Note that this function will NOT
3117
 * delete rows from the webform table if the node-type is exclusively used for
3118
 * webforms (per the "webform_node_types_primary" variable).
3119
 *
3120
 * @param $node
3121
 *   The node object to check if a database entry is still required.
3122
 * @return
3123
 *   Returns TRUE if the webform still has a record in the database. Returns
3124
 *   FALSE if the webform does not have a record or if the previously existing
3125
 *   record was just deleted.
3126
 */
3127
function webform_check_record(&$node) {
3128
  $webform = $node->webform;
3129
  $webform['record_exists'] = FALSE;
3130
  unset($webform['nid']);
3131

    
3132
  // Don't include empty values in the comparison, this makes it so modules that
3133
  // extend Webform with empty defaults won't affect cleanup of rows.
3134
  $webform = array_filter($webform);
3135
  $defaults = array_filter(webform_node_defaults());
3136
  if ($webform == $defaults && !in_array($node->type, webform_variable_get('webform_node_types_primary'))) {
3137
    webform_node_delete($node);
3138
    $node->webform = webform_node_defaults();
3139
  }
3140
  return $node->webform['record_exists'];
3141
}
3142

    
3143
/**
3144
 * Given a form_key and a list of form_key parents, determine the cid.
3145
 *
3146
 * @param $node
3147
 *   A fully loaded node object.
3148
 * @param $form_key
3149
 *   The form key for which we're finding a cid.
3150
 * @param $parent
3151
 *   The cid of the parent component.
3152
 */
3153
function webform_get_cid(&$node, $form_key, $pid) {
3154
  foreach ($node->webform['components'] as $cid => $component) {
3155
    if ($component['form_key'] == $form_key && $component['pid'] == $pid) {
3156
      return $cid;
3157
    }
3158
  }
3159
}
3160

    
3161
/**
3162
 * Retreive a Drupal variable with the appropriate default value.
3163
 */
3164
function webform_variable_get($variable) {
3165
  switch ($variable) {
3166
    case 'webform_allowed_tags':
3167
      $result = variable_get('webform_allowed_tags', array('a', 'em', 'strong', 'code', 'img'));
3168
      break;
3169
    case 'webform_default_from_name':
3170
      $result = variable_get('webform_default_from_name', variable_get('site_name', ''));
3171
      break;
3172
    case 'webform_default_from_address':
3173
      $result = variable_get('webform_default_from_address', variable_get('site_mail', ini_get('sendmail_from')));
3174
      break;
3175
    case 'webform_default_subject':
3176
      $result = variable_get('webform_default_subject', t('Form submission from: %title'));
3177
      break;
3178
    case 'webform_node_types':
3179
      $result = variable_get('webform_node_types', array('webform'));
3180
      break;
3181
    case 'webform_node_types_primary':
3182
      $result = variable_get('webform_node_types_primary', array('webform'));
3183
      break;
3184
  }
3185
  return $result;
3186
}
3187

    
3188
function theme_webform_token_help($variables) {
3189
  $groups = $variables['groups'];
3190
  $groups = empty($groups) ? array('basic', 'node', 'special') : $groups;
3191

    
3192
  static $tokens = array();
3193

    
3194
  if (empty($tokens)) {
3195
    $tokens['basic'] = array(
3196
      'title' => t('Basic tokens'),
3197
      'tokens' => array(
3198
        '%username' => t('The name of the user if logged in. Blank for anonymous users.'),
3199
        '%useremail' => t('The e-mail address of the user if logged in. Blank for anonymous users.'),
3200
        '%ip_address' => t('The IP address of the user.'),
3201
        '%site' => t('The name of the site (i.e. %site_name)', array('%site_name' => variable_get('site_name', ''))),
3202
        '%date' => t('The current date, formatted according to the site settings.'),
3203
      ),
3204
    );
3205

    
3206
    $tokens['node'] = array(
3207
      'title' => t('Node tokens'),
3208
      'tokens' => array(
3209
        '%nid' => t('The node ID.'),
3210
        '%title' => t('The node title.'),
3211
      ),
3212
    );
3213

    
3214
    $tokens['special'] = array(
3215
      'title' => t('Special tokens'),
3216
      'tokens' => array(
3217
        '%profile[' . t('key') . ']' => t('Any user profile field or value, such as %profile[name] or %profile[profile_first_name]'),
3218
        '%get[' . t('key') . ']' => t('Tokens may be populated from the URL by creating URLs of the form http://example.com/my-form?foo=bar. Using the token %get[foo] would print "bar".'),
3219
        '%post[' . t('key') . ']' => t('Tokens may also be populated from POST values that are submitted by forms.'),
3220
      ),
3221
      'description' => t('In addition to %get and %post, the following super tokens may be used, though only with logged-in users: %server, %cookie, and %request. For example %server[HTTP_USER_AGENT] or %session[id].'),
3222
    );
3223

    
3224
    $tokens['email'] = array(
3225
      'title' => t('E-mail tokens'),
3226
      'tokens' => array(
3227
        '%email_values' => t('All included components in a hierarchical structure.'),
3228
        '%email[' . t('key') . '] ' => t('A formatted value and field label. Elements may be accessed such as <em>%email[fieldset_a][key_b]</em>. Do not include quotes.'),
3229
        '%submission_url' => t('The URL for viewing the completed submission.'),
3230
      ),
3231
    );
3232

    
3233
    $tokens['submission'] = array(
3234
      'title' => t('Submission tokens'),
3235
      'tokens' => array(
3236
        '%sid' => t('The unique submission ID.'),
3237
        '%value[key]' => t('A value without additional formatting. Elements may be accessed such as <em>%value[fieldset_a][key_b]</em>. Do not include quotes.'),
3238
      ),
3239
    );
3240
  }
3241

    
3242
  $output = '';
3243
  $output .= '<p>' . t('You may use special tokens in this field that will be replaced with dynamic values.') . '</p>';
3244

    
3245
  foreach ($tokens as $group_name => $group) {
3246
    if (!is_array($groups) || in_array($group_name, $groups)) {
3247
      $items = array();
3248
      foreach ($group['tokens'] as $token => $token_description) {
3249
        $items[] = $token . ' - ' . $token_description;
3250
      }
3251
      $output .= theme('item_list', array('items' => $items, 'title' => $group['title']));
3252
      $output .= isset($group['description']) ? '<p>' . $group['description']  . '</p>' : '';
3253
    }
3254
  }
3255

    
3256
  $fieldset = array(
3257
    '#title' => t('Token values'),
3258
    '#type' => 'fieldset',
3259
    '#collapsible' => TRUE,
3260
    '#collapsed' => TRUE,
3261
    '#children' => '<div>' . $output . '</div>',
3262
    '#attributes' => array('class' => array('collapsible', 'collapsed')),
3263
  );
3264
  return theme('fieldset', array('element' => $fieldset));
3265
}
3266

    
3267
function _webform_safe_name($name) {
3268
  $new = trim($name);
3269

    
3270
  // If transliteration is available, use it to convert names to ASCII.
3271
  if (function_exists('transliteration_get')) {
3272
    $new = transliteration_get($new, '');
3273
    $new = str_replace(array(' ', '-', '/'), array('_', '_', '_'), $new);
3274
  }
3275
  else {
3276
    $new = str_replace(
3277
      array(' ', '-', '/', '€', 'ƒ', 'Š', 'Ž', 'š', 'ž', 'Ÿ', '¢', '¥', 'µ', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Œ',  'œ',  'Æ',  'Ð',  'Þ',  'ß',  'æ',  'ð',  'þ'),
3278
      array('_', '_', '_', 'E', 'f', 'S', 'Z', 's', 'z', 'Y', 'c', 'Y', 'u', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'),
3279
      $new);
3280
  }
3281

    
3282
  $new = drupal_strtolower($new);
3283
  $new = preg_replace('/[^a-z0-9_]/', '', $new);
3284
  return $new;
3285
}
3286

    
3287
/**
3288
 * Given an email address and a name, format an e-mail address.
3289
 *
3290
 * @param $address
3291
 *   The e-mail address.
3292
 * @param $name
3293
 *   The name to be used in the formatted address.
3294
 * @param $node
3295
 *   The webform node if replacements will be done.
3296
 * @param $submission
3297
 *   The webform submission values if replacements will be done.
3298
 * @param $encode
3299
 *   Encode the text for use in an e-mail.
3300
 * @param $single
3301
 *   Force a single value to be returned, even if a component expands to
3302
 *   multiple addresses. This is useful to ensure a single e-mail will be
3303
 *   returned for the "From" address.
3304
 * @param $format
3305
 *   The e-mail format, defaults to the site-wide setting. May be either "short"
3306
 *   or "long".
3307
 */
3308
function webform_format_email_address($address, $name, $node = NULL, $submission = NULL, $encode = TRUE, $single = TRUE, $format = NULL) {
3309
  if (!isset($format)) {
3310
    $format = variable_get('webform_email_address_format', 'long');
3311
  }
3312

    
3313
  if ($name == 'default') {
3314
    $name = webform_variable_get('webform_default_from_name');
3315
  }
3316
  elseif (is_numeric($name) && isset($node->webform['components'][$name])) {
3317
    if (isset($submission->data[$name]['value'])) {
3318
      $name = $submission->data[$name]['value'];
3319
    }
3320
    else {
3321
      $name = t('Value of !component', array('!component' => $node->webform['components'][$name]['name']));
3322
    }
3323
  }
3324

    
3325
  if ($address == 'default') {
3326
    $address = webform_variable_get('webform_default_from_address');
3327
  }
3328
  elseif (is_numeric($address) && isset($node->webform['components'][$address])) {
3329
    if (isset($submission->data[$address]['value'])) {
3330
      $values = $submission->data[$address]['value'];;
3331
      $address = array();
3332
      foreach ($values as $value) {
3333
        $address = array_merge($address, explode(',', $value));
3334
      }
3335
    }
3336
    else {
3337
      $address = t('Value of "!component"', array('!component' => $node->webform['components'][$address]['name']));
3338
    }
3339
  }
3340

    
3341
  // Convert arrays into a single value for From values.
3342
  if ($single) {
3343
    $address = is_array($address) ? reset($address) : $address;
3344
    $name = is_array($name) ? reset($name) : $name;
3345
  }
3346

    
3347
  // Address may be an array if a component value was used on checkboxes.
3348
  if (is_array($address)) {
3349
    foreach ($address as $key => $individual_address) {
3350
      $address[$key] = _webform_filter_values($individual_address, $node, $submission, NULL, FALSE, TRUE);
3351
    }
3352
  }
3353
  else {
3354
    $address = _webform_filter_values($address, $node, $submission, NULL, FALSE, TRUE);
3355
  }
3356

    
3357
  if ($format == 'long' && !empty($name)) {
3358
    $name = _webform_filter_values($name, $node, $submission, NULL, FALSE, TRUE);
3359
    if ($encode) {
3360
      $name = mime_header_encode($name);
3361
    }
3362
    return '"' . $name . '" <' . $address . '>';
3363
  }
3364
  else {
3365
    return $address;
3366
  }
3367
}
3368

    
3369
/**
3370
 * Given an email subject, format it with any needed replacements.
3371
 */
3372
function webform_format_email_subject($subject, $node = NULL, $submission = NULL) {
3373
  if ($subject == 'default') {
3374
    $subject = webform_variable_get('webform_default_subject');
3375
  }
3376
  elseif (is_numeric($subject) && isset($node->webform['components'][$subject])) {
3377
    $component = $node->webform['components'][$subject];
3378
    if (isset($submission->data[$subject]['value'])) {
3379
      $display_function = '_webform_display_' . $component['type'];
3380
      $value = $submission->data[$subject]['value'];
3381

    
3382
      // Convert the value to a clean text representation if possible.
3383
      if (function_exists($display_function)) {
3384
        $display = $display_function($component, $value, 'text');
3385
        $display['#theme_wrappers'] = array();
3386
        $display['#webform_component'] = $component;
3387
        $subject = str_replace("\n", ' ', drupal_render($display));
3388
      }
3389
      else {
3390
        $subject = $value;
3391
      }
3392
    }
3393
    else {
3394
      $subject = t('Value of "!component"', array('!component' => $component['name']));
3395
    }
3396
  }
3397

    
3398
  // Convert arrays to strings (may happen if checkboxes are used as the value).
3399
  if (is_array($subject)) {
3400
    $subject = reset($subject);
3401
  }
3402

    
3403
  return _webform_filter_values($subject, $node, $submission, NULL, FALSE, TRUE);
3404
}
3405

    
3406
/**
3407
 * Convert an array of components into a tree
3408
 */
3409
function _webform_components_tree_build($src, &$tree, $parent, &$page_count) {
3410
  foreach ($src as $cid => $component) {
3411
    if ($component['pid'] == $parent) {
3412
      _webform_components_tree_build($src, $component, $cid, $page_count);
3413
      if ($component['type'] == 'pagebreak') {
3414
        $page_count++;
3415
      }
3416
      $tree['children'][$cid] = $component;
3417
      $tree['children'][$cid]['page_num'] = $page_count;
3418
    }
3419
  }
3420
  return $tree;
3421
}
3422

    
3423
/**
3424
 * Flatten a component tree into a flat list.
3425
 */
3426
function _webform_components_tree_flatten($tree) {
3427
  $components = array();
3428
  foreach ($tree as $cid => $component) {
3429
    if (isset($component['children'])) {
3430
      unset($component['children']);
3431
      $components[$cid] = $component;
3432
      // array_merge() can't be used here because the keys are numeric.
3433
      $children = _webform_components_tree_flatten($tree[$cid]['children']);
3434
      foreach ($children as $ccid => $ccomponent) {
3435
        $components[$ccid] = $ccomponent;
3436
      }
3437
    }
3438
    else {
3439
      $components[$cid] = $component;
3440
    }
3441
  }
3442
  return $components;
3443
}
3444

    
3445
/**
3446
 * Helper for the uasort in webform_tree_sort()
3447
 */
3448
function _webform_components_sort($a, $b) {
3449
  if ($a['weight'] == $b['weight']) {
3450
    return strcasecmp($a['name'], $b['name']);
3451
  }
3452
  return ($a['weight'] < $b['weight']) ? -1 : 1;
3453
}
3454

    
3455
/**
3456
 * Sort each level of a component tree by weight and name
3457
 */
3458
function _webform_components_tree_sort($tree) {
3459
  if (isset($tree['children']) && is_array($tree['children'])) {
3460
    $children = array();
3461
    uasort($tree['children'], '_webform_components_sort');
3462
    foreach ($tree['children'] as $cid => $component) {
3463
      $children[$cid] = _webform_components_tree_sort($component);
3464
    }
3465
    $tree['children'] = $children;
3466
  }
3467
  return $tree;
3468
}
3469

    
3470
/**
3471
 * Get a list of all available component definitions.
3472
 */
3473
function webform_components($include_disabled = FALSE, $reset = FALSE) {
3474
  static $components, $disabled;
3475

    
3476
  if (!isset($components) || $reset) {
3477
    $components = array();
3478
    $disabled = array_flip(variable_get('webform_disabled_components', array()));
3479
    foreach (module_implements('webform_component_info') as $module) {
3480
      $module_components = module_invoke($module, 'webform_component_info');
3481
      foreach ($module_components as $type => $info) {
3482
        $module_components[$type]['module'] = $module;
3483
        $module_components[$type]['enabled'] = !array_key_exists($type, $disabled);
3484
      }
3485
      $components += $module_components;
3486
    }
3487
    drupal_alter('webform_component_info', $components);
3488
    ksort($components);
3489
  }
3490

    
3491
  return $include_disabled ? $components : array_diff_key($components, $disabled);
3492
}
3493

    
3494
/**
3495
 * Build a list of components suitable for use as select list options.
3496
 */
3497
function webform_component_options($include_disabled = FALSE) {
3498
  $component_info = webform_components($include_disabled);
3499
  $options = array();
3500
  foreach ($component_info as $type => $info) {
3501
    $options[$type] = $info['label'];
3502
  }
3503
  return $options;
3504
}
3505

    
3506
/**
3507
 * Load a component file into memory.
3508
 *
3509
 * @param $component_type
3510
 *   The string machine name of a component.
3511
 */
3512
function webform_component_include($component_type) {
3513
  static $included = array();
3514

    
3515
  // No need to load components that have already been added once.
3516
  if (!isset($included[$component_type])) {
3517
    $components = webform_components(TRUE);
3518
    $included[$component_type] = TRUE;
3519

    
3520
    if (($info = $components[$component_type]) && isset($info['file'])) {
3521
      $pathinfo = pathinfo($info['file']);
3522
      $basename = basename($pathinfo['basename'], '.' . $pathinfo['extension']);
3523
      $path = (!empty($pathinfo['dirname']) ? $pathinfo['dirname'] . '/' : '') . $basename;
3524
      module_load_include($pathinfo['extension'], $info['module'], $path);
3525
    }
3526
  }
3527
}
3528

    
3529
/**
3530
 * Invoke a component callback.
3531
 *
3532
 * @param $type
3533
 *   The component type as a string.
3534
 * @param $callback
3535
 *   The callback to execute.
3536
 * @param ...
3537
 *   Any additional parameters required by the $callback.
3538
 */
3539
function webform_component_invoke($type, $callback) {
3540
  $args = func_get_args();
3541
  $type = array_shift($args);
3542
  $callback = array_shift($args);
3543
  $function = '_webform_' . $callback . '_' . $type;
3544
  webform_component_include($type);
3545
  if (function_exists($function)) {
3546
    return call_user_func_array($function, $args);
3547
  }
3548
}
3549

    
3550
/**
3551
 * Check if a component implements a particular hook.
3552
 *
3553
 * @param $type
3554
 *   The component type as a string.
3555
 * @param $callback
3556
 *   The callback to check.
3557
 */
3558
function webform_component_implements($type, $callback) {
3559
  $function = '_webform_' . $callback . '_' . $type;
3560
  webform_component_include($type);
3561
  return function_exists($function);
3562
}
3563

    
3564
/**
3565
 * Disable the Drupal page cache.
3566
 */
3567
function webform_disable_page_cache() {
3568
  drupal_page_is_cacheable(FALSE);
3569
}
3570

    
3571
/**
3572
 * Set the necessary breadcrumb for the page we are on.
3573
 */
3574
function webform_set_breadcrumb($node, $submission = NULL) {
3575
  $breadcrumb = drupal_get_breadcrumb();
3576

    
3577
  if (isset($node)) {
3578
    $webform_breadcrumb = array();
3579
    $webform_breadcrumb[] = empty($breadcrumb) ? l(t('Home'), '<front>') : array_shift($breadcrumb);
3580
    $webform_breadcrumb[] = l($node->title, 'node/' . $node->nid);
3581
    if (isset($submission)) {
3582
      $last_link = array_shift($breadcrumb);
3583
      if (webform_results_access($node)) {
3584
        $webform_breadcrumb[] = l(t('Webform results'), 'node/' . $node->nid . '/webform-results');
3585
      }
3586
      elseif (user_access('access own webform results')) {
3587
        $webform_breadcrumb[] = l(t('Submissions'), 'node/' . $node->nid . '/submissions');
3588
      }
3589
      if (isset($last_link)) {
3590
        $webform_breadcrumb[] = $last_link;
3591
      }
3592
    }
3593
    $breadcrumb = $webform_breadcrumb;
3594
  }
3595

    
3596
  drupal_set_breadcrumb($breadcrumb);
3597
}
3598

    
3599
/**
3600
 * Convert an ISO 8601 date or time into an array.
3601
 *
3602
 * This converts full format dates or times. Either a date or time may be
3603
 * provided, in which case only those portions will be returned. Dashes and
3604
 * colons must be used, never implied.
3605
 *
3606
 * Formats:
3607
 * Dates: YYYY-MM-DD
3608
 * Times: HH:MM:SS
3609
 * Datetimes: YYYY-MM-DDTHH:MM:SS
3610
 *
3611
 * @param $string
3612
 *   An ISO 8601 date, time, or datetime.
3613
 * @param $type
3614
 *   If wanting only specific fields back, specify either "date" or "time".
3615
 *   Leaving empty will return an array with both date and time keys, even if
3616
 *   some are empty. Returns an array with the following keys:
3617
 *   - year
3618
 *   - month
3619
 *   - day
3620
 *   - hour (in 24hr notation)
3621
 *   - minute
3622
 *   - second
3623
 */
3624
function webform_date_array($string, $type = NULL) {
3625
  $pattern = '/((\d{4}?)-(\d{2}?)-(\d{2}?))?(T?(\d{2}?):(\d{2}?):(\d{2}?))?/';
3626
  $matches = array();
3627
  preg_match($pattern, $string, $matches);
3628
  $matches += array_fill(0, 9, '');
3629

    
3630
  $return = array();
3631

    
3632
  // Check for a date string.
3633
  if ($type == 'date' || !isset($type)) {
3634
    $return['year'] = $matches[2] !== '' ? (int) $matches[2] : '';
3635
    $return['month'] = $matches[3] !== '' ? (int) $matches[3] : '';
3636
    $return['day'] = $matches[4] !== '' ? (int) $matches[4] : '';
3637
  }
3638

    
3639
  // Check for a time string.
3640
  if ($type == 'time' || !isset($type)) {
3641
    $return['hour'] = $matches[6] !== '' ? (int) $matches[6] : '';
3642
    $return['minute'] = $matches[7] !== '' ? (int) $matches[7] : '';
3643
    $return['second'] = $matches[8] !== '' ? (int) $matches[8] : '';
3644
  }
3645

    
3646
  return $return;
3647
}
3648

    
3649
/**
3650
 * Convert an array of a date or time into an ISO 8601 compatible string.
3651
 *
3652
 * @param $array
3653
 *   The array to convert to a date or time string.
3654
 * @param $type
3655
 *   If wanting a specific string format back specify either "date" or "time".
3656
 *   Otherwise a full ISO 8601 date and time string will be returned.
3657
 */
3658
function webform_date_string($array, $type = NULL) {
3659
  $string = '';
3660

    
3661
  if ($type == 'date' || !isset($type)) {
3662
    $string .= empty($array['year']) ? '0000' : sprintf('%04d', $array['year']);
3663
    $string .= '-';
3664
    $string .= empty($array['month']) ? '00' : sprintf('%02d', $array['month']);
3665
    $string .= '-';
3666
    $string .= empty($array['day']) ? '00' : sprintf('%02d', $array['day']);
3667
  }
3668

    
3669
  if (!isset($type)) {
3670
    $string .= 'T';
3671
  }
3672

    
3673
  if ($type == 'time' || !isset($type)) {
3674
    $string .= empty($array['hour']) ? '00' :  sprintf('%02d', $array['hour']);
3675
    $string .= ':';
3676
    $string .= empty($array['minute']) ? '00' :  sprintf('%02d', $array['minute']);
3677
    $string .= ':';
3678
    $string .= empty($array['second']) ? '00' :  sprintf('%02d', $array['second']);
3679
  }
3680

    
3681
  return $string;
3682
}
3683

    
3684
/**
3685
 * Get a date format according to the site settings.
3686
 *
3687
 * @param $size
3688
 *   A choice of 'short', 'medium', or 'long' date formats.
3689
 */
3690
function webform_date_format($size = 'medium') {
3691
    // Format date according to site's given format.
3692
    $format = variable_get('date_format_' . $size, 'D, m/d/Y - H:i');
3693
    $time = 'aABgGhHisueIOPTZ';
3694
    $day_of_week = 'Dlw';
3695
    $special = ',-: ';
3696
    $date_format = trim($format, $time . $day_of_week . $special);
3697

    
3698
    // Ensure that a day, month, and year value are present. Use a default
3699
    // format if all the values are not found.
3700
    if (!preg_match('/[dj]/', $date_format) || !preg_match('/[FmMn]/', $date_format) || !preg_match('/[oYy]/', $date_format)) {
3701
      $date_format = 'm/d/Y';
3702
    }
3703

    
3704
    return $date_format;
3705
}
3706

    
3707
/**
3708
 * Return a date in the desired format taking into consideration user timezones.
3709
 */
3710
function webform_strtodate($format, $string, $timezone_name = NULL) {
3711
  global $user;
3712

    
3713
  // Adjust the time based on the user or site timezone.
3714
  if (variable_get('configurable_timezones', 1) && $timezone_name == 'user' && $user->uid) {
3715
    $timezone_name = isset($GLOBALS['user']->timezone) ? $GLOBALS['user']->timezone : 'UTC';
3716
  }
3717
  // If the timezone is still empty or not set, use the site timezone.
3718
  if (empty($timezone_name) || $timezone_name == 'user') {
3719
    $timezone_name = variable_get('date_default_timezone', 'UTC');
3720
  }
3721

    
3722
  if (!empty($timezone_name) && class_exists('DateTimeZone')) {
3723
    // Suppress errors if encountered during string conversion. Exceptions are
3724
    // only supported for DateTime in PHP 5.3 and higher.
3725
    try {
3726
      @$timezone = new DateTimeZone($timezone_name);
3727
      @$datetime = new DateTime($string, $timezone);
3728
      return @$datetime->format($format);
3729
    }
3730
    catch (Exception $e) {
3731
      return '';
3732
    }
3733
  }
3734
  else {
3735
    return date($format, strtotime($string));
3736
  }
3737
}
3738

    
3739
/**
3740
 * Get a timestamp in GMT time, ensuring timezone accuracy.
3741
 */
3742
function webform_strtotime($date) {
3743
  $current_tz = date_default_timezone_get();
3744
  date_default_timezone_set('UTC');
3745
  $timestamp = strtotime($date);
3746
  date_default_timezone_set($current_tz);
3747
  return $timestamp;
3748
}
3749

    
3750
/**
3751
 * Wrapper function for i18n_string() if i18nstrings enabled.
3752
 */
3753
function webform_tt($name, $string, $langcode = NULL, $update = FALSE) {
3754
  if (function_exists('i18n_string')) {
3755
    $options = array(
3756
      'langcode' => $langcode,
3757
      'update' => $update,
3758
    );
3759
    return i18n_string($name, $string, $options);
3760
  }
3761
  else {
3762
    return $string;
3763
  }
3764
}
3765

    
3766
/**
3767
 * Check if any available HTML mail handlers are available for Webform to use.
3768
 */
3769
function webform_email_html_capable() {
3770
  // TODO: Right now we only support MIME Mail and HTML Mail. Support others
3771
  // if available through a hook?
3772
  if (module_exists('mimemail')) {
3773
    $mail_systems = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
3774
    $enable = (!isset($mail_systems['webform']) || $mail_systems['webform'] == 'MimeMailSystem') ? 'MimeMailSystem' : FALSE;
3775
  }
3776
  elseif (module_exists('htmlmail')) {
3777
    $mail_systems = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
3778
    $enable = (!isset($mail_systems['webform']) || $mail_systems['webform'] == 'HTMLMailSystem') ? 'HTMLMailSystem' : FALSE;
3779
  }
3780
  if (!empty($enable)) {
3781
    // We assume that if a solution exists even if it's not specified we should
3782
    // use it. Webform will specify if e-mails sent with the system are plain-
3783
    // text or not when sending each e-mail.
3784
    $GLOBALS['conf']['mail_system']['webform'] = $enable;
3785
    return TRUE;
3786
  }
3787
  return FALSE;
3788
}
3789

    
3790
/**
3791
 * Implements hook_views_api().
3792
 */
3793
function webform_views_api() {
3794
  return array(
3795
    'api' => 2.0,
3796
    'path' => drupal_get_path('module', 'webform') . '/views',
3797
  );
3798
}
3799

    
3800
/**
3801
 * Implements hook_field_extra_fields().
3802
 */
3803
function webform_field_extra_fields() {
3804
  $extra = array();
3805
  foreach (webform_variable_get('webform_node_types') as $type) {
3806
    $extra['node'][$type]['display']['webform'] = array(
3807
      'label' => t('Webform'),
3808
      'description' => t('Webform client form.'),
3809
      'weight' => 10,
3810
    );
3811
  }
3812
  return $extra;
3813
}
3814

    
3815
/**
3816
 * Implements hook_mollom_form_list().
3817
 */
3818
function webform_mollom_form_list() {
3819
  $forms = array();
3820
  $webform_types = webform_variable_get('webform_node_types');
3821
  if (empty($webform_types)) {
3822
    return $forms;
3823
  }
3824

    
3825
  $query = db_select('webform', 'w');
3826
  $query->innerJoin('node', 'n', 'n.nid = w.nid');
3827
  $query->fields('n', array('nid', 'title'));
3828
  $query->condition('n.type', $webform_types, 'IN');
3829
  $result = $query->execute();
3830

    
3831
  foreach ($result as $node) {
3832
    $form_id = 'webform_client_form_' . $node->nid;
3833
    $forms[$form_id] = array(
3834
      'title' => t('@name form', array('@name' => $node->title)),
3835
      'entity' => 'webform',
3836
      'delete form' => 'webform_submission_delete_form',
3837
    );
3838
  }
3839
  return $forms;
3840
}
3841

    
3842
/**
3843
 * Implements hook_mollom_form_info().
3844
 */
3845
function webform_mollom_form_info($form_id) {
3846
  module_load_include('inc', 'webform', 'includes/webform.components');
3847

    
3848
  $nid = drupal_substr($form_id, 20);
3849
  $node = node_load($nid);
3850
  $form_info = array(
3851
    'title' => t('@name form', array('@name' => $node->title)),
3852
    'mode' => MOLLOM_MODE_ANALYSIS,
3853
    'bypass access' => array('edit all webform submissions', 'edit any webform content'),
3854
    'entity' => 'webform',
3855
    'elements' => array(),
3856
    'mapping' => array(
3857
      'post_id' => 'details][sid',
3858
      'author_id' => 'details][uid',
3859
    ),
3860
  );
3861
  // Add components as elements.
3862
  // These components can be enabled for textual analysis (when not using a
3863
  // CAPTCHA-only protection) in Mollom's form configuration.
3864
  foreach ($node->webform['components'] as $cid => $component) {
3865
    if (webform_component_feature($component['type'], 'spam_analysis')) {
3866
      $parents = implode('][', webform_component_parent_keys($node, $component));
3867
      $form_info['elements']['submitted][' . $parents] = check_plain(t($component['name']));
3868
    }
3869
  }
3870
  // Assign field mappings based on webform configuration.
3871
  // Since multiple emails can be configured, we iterate over all and take
3872
  // over the assigned component for the field mapping in any email, unless
3873
  // we already assigned one. We are not interested in administratively
3874
  // configured static strings, only user-submitted values.
3875
  foreach ($node->webform['emails'] as $email) {
3876
    // Subject (post_title).
3877
    if (!isset($form_info['mapping']['post_title'])) {
3878
      $cid = $email['subject'];
3879
      if (is_numeric($cid)) {
3880
        $parents = implode('][', webform_component_parent_keys($node, $node->webform['components'][$cid]));
3881
        $form_info['mapping']['post_title'] = 'submitted][' . $parents;
3882
      }
3883
    }
3884
    // From name (author_name).
3885
    if (!isset($form_info['mapping']['author_name'])) {
3886
      $cid = $email['from_name'];
3887
      if (is_numeric($cid)) {
3888
        $parents = implode('][', webform_component_parent_keys($node, $node->webform['components'][$cid]));
3889
        $form_info['mapping']['author_name'] = 'submitted][' . $parents;
3890
      }
3891
    }
3892
    // From address (author_mail).
3893
    if (!isset($form_info['mapping']['author_mail'])) {
3894
      $cid = $email['from_address'];
3895
      if (is_numeric($cid)) {
3896
        $parents = implode('][', webform_component_parent_keys($node, $node->webform['components'][$cid]));
3897
        $form_info['mapping']['author_mail'] = 'submitted][' . $parents;
3898
      }
3899
    }
3900
  }
3901

    
3902
  return $form_info;
3903
}