Projet

Général

Profil

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

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

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
  // Use the node title for the block title.
1738
  $subject = $node->title;
1739

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

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

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

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

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

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

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

    
1806
  return $form;
1807
}
1808

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2016
  return $form;
2017
}
2018

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

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

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

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

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

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

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

    
2088
  return $show_component;
2089
}
2090

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2527

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

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

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

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

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

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

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

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

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

    
2623
  return $values;
2624
}
2625

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2750
  $output .= "</div>\n";
2751

    
2752
  return $output;
2753
}
2754

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

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

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

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

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

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

    
2804
  if ($output) {
2805
    $output .= "\n";
2806
  }
2807

    
2808
  return $output;
2809
}
2810

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

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

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

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

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

    
2848
  $output .= "</div>\n";
2849

    
2850
  return $output;
2851
}
2852

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3068
  $find = array_keys($safe_replacements);
3069
  $replace = array_values($safe_replacements);
3070
  $string = str_replace($find, $replace, $string);
3071

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

    
3079
  return $strict ? _webform_filter_xss($string) : $string;
3080
}
3081

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

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

    
3098

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

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

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

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

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

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

    
3199
  static $tokens = array();
3200

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

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

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

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

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

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

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

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

    
3274
function _webform_safe_name($name) {
3275
  $new = trim($name);
3276

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

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

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

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

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

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

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

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

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

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

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

    
3411
  return _webform_filter_values($subject, $node, $submission, NULL, FALSE, TRUE);
3412
}
3413

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

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

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

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

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

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

    
3499
  return $include_disabled ? $components : array_diff_key($components, $disabled);
3500
}
3501

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

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

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

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

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

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

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

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

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

    
3604
  drupal_set_breadcrumb($breadcrumb);
3605
}
3606

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

    
3638
  $return = array();
3639

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

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

    
3654
  return $return;
3655
}
3656

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

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

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

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

    
3689
  return $string;
3690
}
3691

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

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

    
3712
    return $date_format;
3713
}
3714

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3917
  return $form_info;
3918
}