Projet

Général

Profil

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

root / drupal7 / sites / all / modules / webform / webform.module @ 4cfd8be6

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
    'load arguments' => array(1),
155
    'page arguments' => array('webform_email_edit_form', 1, 4),
156
    'access callback' => 'node_access',
157
    'access arguments' => array('update', 1),
158
    'file' => 'includes/webform.emails.inc',
159
    'type' => MENU_CALLBACK,
160
  );
161
  $items['node/%webform_menu/webform/emails/%webform_menu_email/delete'] = array(
162
    'load arguments' => array(1),
163
    'page arguments' => array('webform_email_delete_form', 1, 4),
164
    'access callback' => 'node_access',
165
    'access arguments' => array('update', 1),
166
    'type' => MENU_CALLBACK,
167
  );
168

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

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

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

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

    
347
  return $items;
348
}
349

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

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

    
373
/**
374
 * Menu loader callback. Load a webform component if the given cid is a valid.
375
 */
376
function webform_menu_component_load($cid, $nid, $type) {
377
  module_load_include('inc', 'webform', 'includes/webform.components');
378
  if ($cid == 'new') {
379
    $components = webform_components();
380
    $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;
381
  }
382
  else {
383
    $node = node_load($nid);
384
    $component = isset($node->webform['components'][$cid]) ? $node->webform['components'][$cid] : FALSE;
385
  }
386
  if ($component) {
387
    webform_component_defaults($component);
388
  }
389
  return $component;
390
}
391

    
392

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

    
412
  return $email;
413
}
414

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

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

    
423
  $general_access = $access_all || $access_own_submission || $access_node_submissions;
424

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

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

    
433
  switch ($op) {
434
    case 'view':
435
      return $module_access || $general_access;
436
    case 'edit':
437
      return $module_access || ($general_access && (user_access('edit all webform submissions', $account) || (user_access('edit own webform submissions', $account) && $account->uid == $submission->uid)));
438
    case 'delete':
439
      return $module_access || ($general_access && (user_access('delete all webform submissions', $account) || (user_access('delete own webform submissions', $account) && $account->uid == $submission->uid)));
440
    case 'list':
441
      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);
442
  }
443
}
444

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

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

    
454
  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));
455
}
456

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

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

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

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

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

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

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

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

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

    
696
  return $libraries;
697
}
698

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

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

    
723
  return $elements;
724
}
725

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

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

    
870
  return $component_info;
871
}
872

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

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

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

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

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

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

    
924
  return $actions;
925
}
926

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

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

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

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

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

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

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

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

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

    
1035
  // Determine whether this file was a webform upload.
1036
  $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();
1037
  if ($row) {
1038
    $file = file_load($row->fid);
1039
  }
1040
  if (!empty($row->sid)) {
1041
    $submissions = webform_get_submissions(array('sid' => $row->sid));
1042
    $submission = reset($submissions);
1043
  }
1044

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1297

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1402
/**
1403
 * Submit handler for the webform node form.
1404
 *
1405
 * Redirect the user to the components form on new node inserts. Note that this
1406
 * fires after the hook_submit() function above.
1407
 */
1408
function webform_form_submit($form, &$form_state) {
1409
  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'])));
1410
  $form_state['redirect'] = 'node/' . $form_state['nid'] . '/webform/components';
1411
}
1412

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1532
  // Print out messages for the webform.
1533
  if (empty($node->in_preview) && !isset($node->webform_block) && !$logging_in) {
1534
    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));
1535
  }
1536

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

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

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

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

    
1604
  $type = 'status';
1605

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1737

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

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

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

    
1762
  // Create the block, using the node title for the block title.
1763
  // Note that we render the content immediately here rather than passing back
1764
  // a renderable so that if the block is empty it is hidden.
1765
  $block = array(
1766
    'subject' => check_plain($node->title),
1767
    'content' => drupal_render($content),
1768
  );
1769
  return $block;
1770
}
1771

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

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

    
1797
  $form['pages_block'] = array(
1798
    '#type' => 'checkbox',
1799
    '#title' => t('Show all webform pages in block'),
1800
    '#default_value' => $settings['pages_block'],
1801
    '#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.'),
1802
  );
1803

    
1804
  return $form;
1805
}
1806

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

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

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

    
1855
  $form['#process'] = array(
1856
    'webform_client_form_includes',
1857
  );
1858

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

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

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

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

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

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

    
1887
  $form['#submit'] = array('webform_client_form_pages', 'webform_client_form_submit');
1888
  $form['#validate'] = array('webform_client_form_validate');
1889

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

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

    
1912
    // Shorten up our variable names.
1913
    $component_tree = $form_state['webform']['component_tree'];
1914
    $page_count = $form_state['webform']['page_count'];
1915
    $page_num = $form_state['webform']['page_num'];
1916

    
1917
    if ($page_count > 1) {
1918
      $next_page_labels = array();
1919
      $prev_page_labels = array();
1920
    }
1921

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

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

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

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

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

    
2014
  return $form;
2015
}
2016

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

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

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

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

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

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

    
2081
    if ($component['extra']['conditional_operator'] == '!=') {
2082
      $show_component = !$show_component;
2083
    }
2084
  }
2085

    
2086
  return $show_component;
2087
}
2088

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

    
2123
  // Load with submission information if necessary.
2124
  if ($format != 'form') {
2125
    // This component is display only.
2126
    $data = empty($submission->data[$cid]['value']) ? NULL : $submission->data[$cid]['value'];
2127
    if ($display_element = webform_component_invoke($component['type'], 'display', $component, $data, $format)) {
2128
      // Set access based on the private property.
2129
      $element['#access'] = $component_access;
2130

    
2131
      // Ensure the component is added as a property.
2132
      $display_element['#webform_component'] = $component;
2133

    
2134
      // Allow modules to modify a "display only" webform component.
2135
      drupal_alter('webform_component_display', $display_element, $component);
2136

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

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

    
2161
      // Ensure the component is added as a property.
2162
      $element['#webform_component'] = $component;
2163

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

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

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

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

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

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

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

    
2214
  // Check that the submissions have not exceeded the total submission limit.
2215
  if ($node->webform['total_submit_limit'] != -1) {
2216
    module_load_include('inc', 'webform', 'includes/webform.submissions');
2217
    // Check if the total number of entries was reached before the user submitted
2218
    // the form.
2219
    if (!$finished && $total_limit_exceeded = _webform_submission_total_limit_check($node)) {
2220
      // Show the user the limit has exceeded.
2221
      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));
2222
      form_set_error('', NULL);
2223
      return;
2224
    }
2225
  }
2226

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

    
2233
    if (!$finished && $user_limit_exceeded = _webform_submission_user_limit_check($node)) {
2234
      // Assume that webform_view_messages will print out the necessary message,
2235
      // then stop the processing of the form with an empty form error.
2236
      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));
2237
      form_set_error('', NULL);
2238
      return;
2239
    }
2240
  }
2241

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

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

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

    
2277
      // Verify that the value is not longer than #maxlength.
2278
      if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
2279
        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']))));
2280
      }
2281

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2525

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

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

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

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

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

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

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

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

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

    
2621
  return $values;
2622
}
2623

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

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

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

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

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

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

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

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

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

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

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

    
2711
  // If #title_display is none, set it to invisible instead - none only used if
2712
  // we have no title at all to use.
2713
  if ($element['#title_display'] == 'none') {
2714
    $variables['element']['#title_display'] = 'invisible';
2715
    $element['#title_display'] = 'invisible';
2716
  }
2717
  // If #title is not set, we don't display any label or required marker.
2718
  if (!isset($element['#title'])) {
2719
    $element['#title_display'] = 'none';
2720
  }
2721
  $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . _webform_filter_xss($element['#field_prefix']) . '</span> ' : '';
2722
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . _webform_filter_xss($element['#field_suffix']) . '</span>' : '';
2723

    
2724
  switch ($element['#title_display']) {
2725
    case 'inline':
2726
    case 'before':
2727
    case 'invisible':
2728
      $output .= ' ' . theme('form_element_label', $variables);
2729
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
2730
      break;
2731

    
2732
    case 'after':
2733
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
2734
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
2735
      break;
2736

    
2737
    case 'none':
2738
    case 'attribute':
2739
      // Output no label and no required marker, only the children.
2740
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
2741
      break;
2742
  }
2743

    
2744
  if (!empty($element['#description'])) {
2745
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
2746
  }
2747

    
2748
  $output .= "</div>\n";
2749

    
2750
  return $output;
2751
}
2752

    
2753
/**
2754
 * Output a form element in plain text format.
2755
 */
2756
function theme_webform_element_text($variables) {
2757
  $element = $variables['element'];
2758
  $value = $variables['element']['#children'];
2759

    
2760
  $output = '';
2761
  $is_group = webform_component_feature($element['#webform_component']['type'], 'group');
2762

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

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

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

    
2790
  // Indent fieldsets.
2791
  if ($is_group) {
2792
    $lines = explode("\n", $output);
2793
    foreach ($lines as $number => $line) {
2794
      if (strlen($line)) {
2795
        $lines[$number] = '  ' . $line;
2796
      }
2797
    }
2798
    $output = implode("\n", $lines);
2799
    $output .= "\n";
2800
  }
2801

    
2802
  if ($output) {
2803
    $output .= "\n";
2804
  }
2805

    
2806
  return $output;
2807
}
2808

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

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

    
2827
  // Add container-inline to all elements.
2828
  $class[] = 'webform-container-inline';
2829
  if (isset($element['#inline_element']) && isset($variables['element']['#title'])) {
2830
    $variables['element']['#title'] .= ': ';
2831
  }
2832

    
2833
  $output = '<div class="' . implode(' ', $class) . '">' . "\n";
2834
  $output .= ' ' . $element['#children'];
2835
  if (!empty($element['#title'])) {
2836
    $output .= ' ' . theme('form_element_label', $variables) . "\n";
2837
  }
2838
  if (isset($element['#inline_element'])) {
2839
    $output .= ' ' . $element['#inline_element'] . "\n";
2840
  }
2841

    
2842
  if (!empty($element['#description'])) {
2843
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
2844
  }
2845

    
2846
  $output .= "</div>\n";
2847

    
2848
  return $output;
2849
}
2850

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

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

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

    
2917
  // Don't do any filtering if the string is empty.
2918
  if (strlen(trim($string)) == 0) {
2919
    return $string;
2920
  }
2921

    
2922
  // Setup default token replacements.
2923
  if (!isset($replacements)) {
2924
    $replacements['unsafe'] = array();
2925
    $replacements['safe']['%site'] = variable_get('site_name', 'drupal');
2926
    $replacements['safe']['%date'] = format_date(REQUEST_TIME, 'long');
2927
  }
2928

    
2929
  // Node replacements.
2930
  if (isset($node) && !array_key_exists('%nid', $replacements['safe'])) {
2931
    $replacements['safe']['%nid'] = $node->nid;
2932
    $replacements['safe']['%title'] = $node->title;
2933
  }
2934

    
2935
  // Determine the display format.
2936
  $format = isset($email['html']) && $email['html'] ? 'html' : 'text';
2937

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

    
2942
    // Set the submission ID.
2943
    $replacements['unsafe']['%sid'] = $submission->sid;
2944

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

    
2948
    // Populate token values for each component.
2949
    foreach ($submission->data as $cid => $value) {
2950
      $component = $node->webform['components'][$cid];
2951

    
2952
      // Find by form key.
2953
      $parents = webform_component_parent_keys($node, $component);
2954
      $form_key = implode('][', $parents);
2955
      $display_element = webform_component_invoke($component['type'], 'display', $component, $value['value'], $format);
2956

    
2957
      // Ensure the component is added as a property.
2958
      $display_element['#webform_component'] = $component;
2959

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

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

    
2980
    // Submission edit URL.
2981
    $replacements['unsafe']['%submission_url'] = url('node/' . $node->nid . '/submission/' . $submission->sid, array('absolute' => TRUE));
2982
  }
2983

    
2984
  // Token for the entire form tree for e-mails.
2985
  if (isset($submission) && isset($email)) {
2986
    $replacements['email'][$format]['%email_values'] = webform_submission_render($node, $submission, $email, $format);
2987
  }
2988

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

    
3004
  // Replacements of global variable tokens.
3005
  if (!isset($replacements['specials_set'])) {
3006
    $replacements['specials_set'] = TRUE;
3007

    
3008
    // Load profile information if available.
3009
    if ($user->uid) {
3010
      $account = user_load($user->uid);
3011
      $special_tokens['unsafe']['%profile'] = (array) $account;
3012
    }
3013

    
3014
    // User replacements.
3015
    if (!array_key_exists('%uid', $replacements['unsafe'])) {
3016
      $replacements['unsafe']['%uid'] = !empty($user->uid) ? $user->uid : '';
3017
      $replacements['unsafe']['%username'] = isset($user->name) ? $user->name : '';
3018
      $replacements['unsafe']['%useremail'] = isset($user->mail) ? $user->mail : '';
3019
      $replacements['unsafe']['%ip_address'] = ip_address();
3020
    }
3021

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

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

    
3048
  // Make a copy of the replacements so we don't affect the static version.
3049
  $safe_replacements = $replacements['safe'];
3050

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

    
3066
  $find = array_keys($safe_replacements);
3067
  $replace = array_values($safe_replacements);
3068
  $string = str_replace($find, $replace, $string);
3069

    
3070
  // Clean up any unused tokens.
3071
  foreach ($special_tokens as $safe_state => $tokens) {
3072
    foreach (array_keys($tokens) as $token) {
3073
      $string = preg_replace('/\\' . $token . '\[\w+\]/', '', $string);
3074
    }
3075
  }
3076

    
3077
  return $strict ? _webform_filter_xss($string) : $string;
3078
}
3079

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

    
3087
/**
3088
 * Filter labels for display by running through XSS checks.
3089
 */
3090
function _webform_filter_xss($string) {
3091
  static $allowed_tags;
3092
  $allowed_tags = isset($allowed_tags) ? $allowed_tags : webform_variable_get('webform_allowed_tags');
3093
  return filter_xss($string, $allowed_tags);
3094
}
3095

    
3096

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

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

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

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

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

    
3193
function theme_webform_token_help($variables) {
3194
  $groups = $variables['groups'];
3195
  $groups = empty($groups) ? array('basic', 'node', 'special') : $groups;
3196

    
3197
  static $tokens = array();
3198

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

    
3211
    $tokens['node'] = array(
3212
      'title' => t('Node tokens'),
3213
      'tokens' => array(
3214
        '%nid' => t('The node ID.'),
3215
        '%title' => t('The node title.'),
3216
      ),
3217
    );
3218

    
3219
    $tokens['special'] = array(
3220
      'title' => t('Special tokens'),
3221
      'tokens' => array(
3222
        '%profile[' . t('key') . ']' => t('Any user profile field or value, such as %profile[name] or %profile[profile_first_name]'),
3223
        '%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".'),
3224
        '%post[' . t('key') . ']' => t('Tokens may also be populated from POST values that are submitted by forms.'),
3225
      ),
3226
      '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].'),
3227
    );
3228

    
3229
    $tokens['email'] = array(
3230
      'title' => t('E-mail tokens'),
3231
      'tokens' => array(
3232
        '%email_values' => t('All included components in a hierarchical structure.'),
3233
        '%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.'),
3234
        '%submission_url' => t('The URL for viewing the completed submission.'),
3235
      ),
3236
    );
3237

    
3238
    $tokens['submission'] = array(
3239
      'title' => t('Submission tokens'),
3240
      'tokens' => array(
3241
        '%sid' => t('The unique submission ID.'),
3242
        '%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.'),
3243
      ),
3244
    );
3245
  }
3246

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

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

    
3261
  $fieldset = array(
3262
    '#title' => t('Token values'),
3263
    '#type' => 'fieldset',
3264
    '#collapsible' => TRUE,
3265
    '#collapsed' => TRUE,
3266
    '#children' => '<div>' . $output . '</div>',
3267
    '#attributes' => array('class' => array('collapsible', 'collapsed')),
3268
  );
3269
  return theme('fieldset', array('element' => $fieldset));
3270
}
3271

    
3272
function _webform_safe_name($name) {
3273
  $new = trim($name);
3274

    
3275
  // If transliteration is available, use it to convert names to ASCII.
3276
  if (function_exists('transliteration_get')) {
3277
    $new = transliteration_get($new, '');
3278
    $new = str_replace(array(' ', '-', '/'), array('_', '_', '_'), $new);
3279
  }
3280
  else {
3281
    $new = str_replace(
3282
      array(' ', '-', '/', '€', 'ƒ', 'Š', 'Ž', 'š', 'ž', 'Ÿ', '¢', '¥', 'µ', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Œ',  'œ',  'Æ',  'Ð',  'Þ',  'ß',  'æ',  'ð',  'þ'),
3283
      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'),
3284
      $new);
3285
  }
3286

    
3287
  $new = drupal_strtolower($new);
3288
  $new = preg_replace('/[^a-z0-9_]/', '', $new);
3289
  return $new;
3290
}
3291

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

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

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

    
3346
  // Convert arrays into a single value for From values.
3347
  if ($single) {
3348
    $address = is_array($address) ? reset($address) : $address;
3349
    $name = is_array($name) ? reset($name) : $name;
3350
  }
3351

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

    
3362
  if ($format == 'long' && !empty($name)) {
3363
    $name = _webform_filter_values($name, $node, $submission, NULL, FALSE, TRUE);
3364
    if ($encode) {
3365
      $name = mime_header_encode($name);
3366
    }
3367
    $name = trim($name);
3368
    return '"' . $name . '" <' . $address . '>';
3369
  }
3370
  else {
3371
    return $address;
3372
  }
3373
}
3374

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

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

    
3404
  // Convert arrays to strings (may happen if checkboxes are used as the value).
3405
  if (is_array($subject)) {
3406
    $subject = reset($subject);
3407
  }
3408

    
3409
  return _webform_filter_values($subject, $node, $submission, NULL, FALSE, TRUE);
3410
}
3411

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

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

    
3451
/**
3452
 * Helper for the uasort in webform_tree_sort()
3453
 */
3454
function _webform_components_sort($a, $b) {
3455
  if ($a['weight'] == $b['weight']) {
3456
    return strcasecmp($a['name'], $b['name']);
3457
  }
3458
  return ($a['weight'] < $b['weight']) ? -1 : 1;
3459
}
3460

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

    
3476
/**
3477
 * Get a list of all available component definitions.
3478
 */
3479
function webform_components($include_disabled = FALSE, $reset = FALSE) {
3480
  static $components, $disabled;
3481

    
3482
  if (!isset($components) || $reset) {
3483
    $components = array();
3484
    $disabled = array_flip(variable_get('webform_disabled_components', array()));
3485
    foreach (module_implements('webform_component_info') as $module) {
3486
      $module_components = module_invoke($module, 'webform_component_info');
3487
      foreach ($module_components as $type => $info) {
3488
        $module_components[$type]['module'] = $module;
3489
        $module_components[$type]['enabled'] = !array_key_exists($type, $disabled);
3490
      }
3491
      $components += $module_components;
3492
    }
3493
    drupal_alter('webform_component_info', $components);
3494
    ksort($components);
3495
  }
3496

    
3497
  return $include_disabled ? $components : array_diff_key($components, $disabled);
3498
}
3499

    
3500
/**
3501
 * Build a list of components suitable for use as select list options.
3502
 */
3503
function webform_component_options($include_disabled = FALSE) {
3504
  $component_info = webform_components($include_disabled);
3505
  $options = array();
3506
  foreach ($component_info as $type => $info) {
3507
    $options[$type] = $info['label'];
3508
  }
3509
  return $options;
3510
}
3511

    
3512
/**
3513
 * Load a component file into memory.
3514
 *
3515
 * @param $component_type
3516
 *   The string machine name of a component.
3517
 */
3518
function webform_component_include($component_type) {
3519
  static $included = array();
3520

    
3521
  // No need to load components that have already been added once.
3522
  if (!isset($included[$component_type])) {
3523
    $components = webform_components(TRUE);
3524
    $included[$component_type] = TRUE;
3525

    
3526
    if (($info = $components[$component_type]) && isset($info['file'])) {
3527
      $pathinfo = pathinfo($info['file']);
3528
      $basename = basename($pathinfo['basename'], '.' . $pathinfo['extension']);
3529
      $path = (!empty($pathinfo['dirname']) ? $pathinfo['dirname'] . '/' : '') . $basename;
3530
      module_load_include($pathinfo['extension'], $info['module'], $path);
3531
    }
3532
  }
3533
}
3534

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

    
3556
/**
3557
 * Check if a component implements a particular hook.
3558
 *
3559
 * @param $type
3560
 *   The component type as a string.
3561
 * @param $callback
3562
 *   The callback to check.
3563
 */
3564
function webform_component_implements($type, $callback) {
3565
  $function = '_webform_' . $callback . '_' . $type;
3566
  webform_component_include($type);
3567
  return function_exists($function);
3568
}
3569

    
3570
/**
3571
 * Disable the Drupal page cache.
3572
 */
3573
function webform_disable_page_cache() {
3574
  drupal_page_is_cacheable(FALSE);
3575
}
3576

    
3577
/**
3578
 * Set the necessary breadcrumb for the page we are on.
3579
 */
3580
function webform_set_breadcrumb($node, $submission = NULL) {
3581
  $breadcrumb = drupal_get_breadcrumb();
3582

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

    
3602
  drupal_set_breadcrumb($breadcrumb);
3603
}
3604

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

    
3636
  $return = array();
3637

    
3638
  // Check for a date string.
3639
  if ($type == 'date' || !isset($type)) {
3640
    $return['year'] = $matches[2] !== '' ? (int) $matches[2] : '';
3641
    $return['month'] = $matches[3] !== '' ? (int) $matches[3] : '';
3642
    $return['day'] = $matches[4] !== '' ? (int) $matches[4] : '';
3643
  }
3644

    
3645
  // Check for a time string.
3646
  if ($type == 'time' || !isset($type)) {
3647
    $return['hour'] = $matches[6] !== '' ? (int) $matches[6] : '';
3648
    $return['minute'] = $matches[7] !== '' ? (int) $matches[7] : '';
3649
    $return['second'] = $matches[8] !== '' ? (int) $matches[8] : '';
3650
  }
3651

    
3652
  return $return;
3653
}
3654

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

    
3667
  if ($type == 'date' || !isset($type)) {
3668
    $string .= empty($array['year']) ? '0000' : sprintf('%04d', $array['year']);
3669
    $string .= '-';
3670
    $string .= empty($array['month']) ? '00' : sprintf('%02d', $array['month']);
3671
    $string .= '-';
3672
    $string .= empty($array['day']) ? '00' : sprintf('%02d', $array['day']);
3673
  }
3674

    
3675
  if (!isset($type)) {
3676
    $string .= 'T';
3677
  }
3678

    
3679
  if ($type == 'time' || !isset($type)) {
3680
    $string .= empty($array['hour']) ? '00' :  sprintf('%02d', $array['hour']);
3681
    $string .= ':';
3682
    $string .= empty($array['minute']) ? '00' :  sprintf('%02d', $array['minute']);
3683
    $string .= ':';
3684
    $string .= empty($array['second']) ? '00' :  sprintf('%02d', $array['second']);
3685
  }
3686

    
3687
  return $string;
3688
}
3689

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

    
3704
    // Ensure that a day, month, and year value are present. Use a default
3705
    // format if all the values are not found.
3706
    if (!preg_match('/[dj]/', $date_format) || !preg_match('/[FmMn]/', $date_format) || !preg_match('/[oYy]/', $date_format)) {
3707
      $date_format = 'm/d/Y';
3708
    }
3709

    
3710
    return $date_format;
3711
}
3712

    
3713
/**
3714
 * Return a date in the desired format taking into consideration user timezones.
3715
 */
3716
function webform_strtodate($format, $string, $timezone_name = NULL) {
3717
  global $user;
3718

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

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

    
3745
/**
3746
 * Get a timestamp in GMT time, ensuring timezone accuracy.
3747
 */
3748
function webform_strtotime($date) {
3749
  $current_tz = date_default_timezone_get();
3750
  date_default_timezone_set('UTC');
3751
  $timestamp = strtotime($date);
3752
  date_default_timezone_set($current_tz);
3753
  return $timestamp;
3754
}
3755

    
3756
/**
3757
 * Wrapper function for i18n_string() if i18nstrings enabled.
3758
 */
3759
function webform_tt($name, $string, $langcode = NULL, $update = FALSE) {
3760
  if (function_exists('i18n_string')) {
3761
    $options = array(
3762
      'langcode' => $langcode,
3763
      'update' => $update,
3764
    );
3765
    return i18n_string($name, $string, $options);
3766
  }
3767
  else {
3768
    return $string;
3769
  }
3770
}
3771

    
3772
/**
3773
 * Check if any available HTML mail handlers are available for Webform to use.
3774
 */
3775
function webform_email_html_capable() {
3776
  // TODO: Right now we only support MIME Mail and HTML Mail. Support others
3777
  // if available through a hook?
3778
  $supported_html_modules = array(
3779
    'mimemail' => 'MimeMailSystem',
3780
    'htmlmail' => 'HTMLMailSystem',
3781
  );
3782
  foreach ($supported_html_modules as $mail_module => $mail_system_name) {
3783
    if (module_exists($mail_module)) {
3784
      $mail_systems = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
3785
      if (isset($mail_systems['webform'])) {
3786
        $enable = strpos($mail_systems['webform'], $mail_system_name) !== FALSE ? $mail_systems['webform'] : FALSE;
3787
      }
3788
      else {
3789
        $enable = $mail_system_name;
3790
      }
3791
    }
3792
  }
3793
  if (!empty($enable)) {
3794
    // We assume that if a solution exists even if it's not specified we should
3795
    // use it. Webform will specify if e-mails sent with the system are plain-
3796
    // text or not when sending each e-mail.
3797
    $GLOBALS['conf']['mail_system']['webform'] = $enable;
3798
    return TRUE;
3799
  }
3800
  return FALSE;
3801
}
3802

    
3803
/**
3804
 * Implements hook_views_api().
3805
 */
3806
function webform_views_api() {
3807
  return array(
3808
    'api' => 2.0,
3809
    'path' => drupal_get_path('module', 'webform') . '/views',
3810
  );
3811
}
3812

    
3813
/**
3814
 * Implements hook_field_extra_fields().
3815
 */
3816
function webform_field_extra_fields() {
3817
  $extra = array();
3818
  foreach (webform_variable_get('webform_node_types') as $type) {
3819
    $extra['node'][$type]['display']['webform'] = array(
3820
      'label' => t('Webform'),
3821
      'description' => t('Webform client form.'),
3822
      'weight' => 10,
3823
    );
3824
  }
3825
  return $extra;
3826
}
3827

    
3828
/**
3829
 * Implements hook_mollom_form_list().
3830
 */
3831
function webform_mollom_form_list() {
3832
  $forms = array();
3833
  $webform_types = webform_variable_get('webform_node_types');
3834
  if (empty($webform_types)) {
3835
    return $forms;
3836
  }
3837

    
3838
  $query = db_select('webform', 'w');
3839
  $query->innerJoin('node', 'n', 'n.nid = w.nid');
3840
  $query->fields('n', array('nid', 'title'));
3841
  $query->condition('n.type', $webform_types, 'IN');
3842
  $result = $query->execute();
3843

    
3844
  foreach ($result as $node) {
3845
    $form_id = 'webform_client_form_' . $node->nid;
3846
    $forms[$form_id] = array(
3847
      'title' => t('@name form', array('@name' => $node->title)),
3848
      'entity' => 'webform',
3849
      'delete form' => 'webform_submission_delete_form',
3850
    );
3851
  }
3852
  return $forms;
3853
}
3854

    
3855
/**
3856
 * Implements hook_mollom_form_info().
3857
 */
3858
function webform_mollom_form_info($form_id) {
3859
  module_load_include('inc', 'webform', 'includes/webform.components');
3860

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

    
3915
  return $form_info;
3916
}