Projet

Général

Profil

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

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

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_node_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
  // If the webform is not set to display in this view mode, return early.
1438
  $extra_fields = field_extra_fields_get_display('node', $node->type, $view_mode);
1439
  if (empty($extra_fields['webform']['visible'])) {
1440
    return;
1441
  }
1442

    
1443
  $info = array();
1444
  $submission = array();
1445
  $submission_count = 0;
1446
  $enabled = TRUE;
1447
  $logging_in = FALSE;
1448
  $total_limit_exceeded = FALSE;
1449
  $user_limit_exceeded = FALSE;
1450
  $closed = FALSE;
1451
  $allowed_roles = array();
1452

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

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

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

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

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

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

    
1501
    // Disable the form if the limit is exceeded and page cache is not active.
1502
    if (($user_limit_exceeded = _webform_submission_user_limit_check($node)) && !$cached) {
1503
      $enabled = FALSE;
1504
    }
1505
  }
1506

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

    
1512
    // Disable the form if the limit is exceeded and page cache is not active.
1513
    if (($total_limit_exceeded = _webform_submission_total_limit_check($node)) && !$cached) {
1514
      $enabled = FALSE;
1515
    }
1516
  }
1517

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

    
1530
  // Avoid building the same form twice on the same page request (which can
1531
  // happen if the webform is displayed in a panel or block) because this
1532
  // causes multistep forms to build incorrectly the second time.
1533
  $cached_forms = &drupal_static(__FUNCTION__, array());
1534
  if (isset($cached_forms[$node->nid])) {
1535
    $form = $cached_forms[$node->nid];
1536
  }
1537
  // If this is the first time, generate the form array.
1538
  else {
1539
    $form = drupal_get_form('webform_client_form_' . $node->nid, $node, $submission, $is_draft);
1540
    $cached_forms[$node->nid] = $form;
1541
  }
1542

    
1543
  // Remove the surrounding <form> tag if this is a preview.
1544
  if (!empty($node->in_preview)) {
1545
    $form['#type'] = 'markup';
1546
  }
1547

    
1548
  // Print out messages for the webform.
1549
  if (empty($node->in_preview) && !isset($node->webform_block) && !$logging_in) {
1550
    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));
1551
  }
1552

    
1553
  // Add the output to the node.
1554
  $node->content['webform'] = array(
1555
    '#theme' => 'webform_view',
1556
    '#node' => $node,
1557
    '#teaser' => $teaser,
1558
    '#page' => $page,
1559
    '#form' => $form,
1560
    '#enabled' => $enabled,
1561
    '#weight' => 10,
1562
  );
1563
}
1564

    
1565
/**
1566
 * Output the Webform into the node content.
1567
 *
1568
 * @param $node
1569
 *   The webform node object.
1570
 * @param $teaser
1571
 *   If this webform is being displayed as the teaser view of the node.
1572
 * @param $page
1573
 *   If this webform node is being viewed as the main content of the page.
1574
 * @param $form
1575
 *   The rendered form.
1576
 * @param $enabled
1577
 *   If the form allowed to be completed by the current user.
1578
 */
1579
function theme_webform_view($variables) {
1580
  // Only show the form if this user is allowed access.
1581
  if ($variables['webform']['#enabled']) {
1582
    return drupal_render($variables['webform']['#form']);
1583
  }
1584
}
1585

    
1586
/**
1587
 * Display a message to a user if they are not allowed to fill out a form.
1588
 *
1589
 * @param $node
1590
 *   The webform node object.
1591
 * @param $teaser
1592
 *   If this webform is being displayed as the teaser view of the node.
1593
 * @param $page
1594
 *   If this webform node is being viewed as the main content of the page.
1595
 * @param $submission_count
1596
 *   The number of submissions this user has already submitted. Not calculated
1597
 *   for anonymous users.
1598
 * @param $user_limit_exceeded
1599
 *   Boolean value if the submission limit for this user has been exceeded.
1600
 * @param $total_limit_exceeded
1601
 *   Boolean value if the total submission limit has been exceeded.
1602
 * @param $allowed_roles
1603
 *   A list of user roles that are allowed to submit this webform.
1604
 * @param $closed
1605
 *   Boolean value if submissions are closed.
1606
 */
1607
function theme_webform_view_messages($variables) {
1608
  global $user;
1609

    
1610
  $node = $variables['node'];
1611
  $teaser = $variables['teaser'];
1612
  $page = $variables['page'];
1613
  $submission_count = $variables['submission_count'];
1614
  $user_limit_exceeded = $variables['user_limit_exceeded'];
1615
  $total_limit_exceeded = $variables['total_limit_exceeded'];
1616
  $allowed_roles = $variables['allowed_roles'];
1617
  $closed = $variables['closed'];
1618
  $cached = $variables['cached'];
1619

    
1620
  $type = 'status';
1621

    
1622
  if ($closed) {
1623
    $message = t('Submissions for this form are closed.');
1624
  }
1625
  // If open and not allowed to submit the form, give an explanation.
1626
  elseif (array_search(TRUE, $allowed_roles) === FALSE && $user->uid != 1) {
1627
    if (empty($allowed_roles)) {
1628
      // No roles are allowed to submit the form.
1629
      $message = t('Submissions for this form are closed.');
1630
    }
1631
    elseif (isset($allowed_roles[2])) {
1632
      // The "authenticated user" role is allowed to submit and the user is currently logged-out.
1633
      $login = url('user/login', array('query' => drupal_get_destination()));
1634
      $register = url('user/register', array('query' => drupal_get_destination()));
1635
      if (variable_get('user_register', 1) == 0) {
1636
        $message = t('You must <a href="!login">login</a> to view this form.', array('!login' => $login));
1637
      }
1638
      else {
1639
        $message = t('You must <a href="!login">login</a> or <a href="!register">register</a> to view this form.', array('!login' => $login, '!register' => $register));
1640
      }
1641
    }
1642
    else {
1643
      // The user must be some other role to submit.
1644
      $message = t('You do not have permission to view this form.');
1645
      $type = 'error';
1646
    }
1647
  }
1648

    
1649
  // If the user has exceeded the limit of submissions, explain the limit.
1650
  elseif ($user_limit_exceeded && !$cached) {
1651
    if ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] > 1) {
1652
      $message = t('You have submitted this form the maximum number of times (@count).', array('@count' => $node->webform['submit_limit']));
1653
    }
1654
    elseif ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] == 1) {
1655
      $message = t('You have already submitted this form.');
1656
    }
1657
    else {
1658
      $message = t('You may not submit another entry at this time.');
1659
    }
1660
    $type = 'error';
1661
  }
1662
  elseif ($total_limit_exceeded && !$cached) {
1663
    if ($node->webform['total_submit_interval'] == -1 && $node->webform['total_submit_limit'] > 1) {
1664
      $message = t('This form has received the maximum number of entries.');
1665
    }
1666
    else {
1667
      $message = t('You may not submit another entry at this time.');
1668
    }
1669
  }
1670

    
1671
  // If the user has submitted before, give them a link to their submissions.
1672
  if ($submission_count > 0 && $node->webform['submit_notice'] == 1 && !$cached) {
1673
    if (empty($message)) {
1674
      $message = t('You have already submitted this form.') . ' ' . t('<a href="!url">View your previous submissions</a>.', array('!url' => url('node/' . $node->nid . '/submissions')));
1675
    }
1676
    else {
1677
      $message .= ' ' . t('<a href="!url">View your previous submissions</a>.', array('!url' => url('node/' . $node->nid . '/submissions')));
1678
    }
1679
  }
1680

    
1681
  if ($page && isset($message)) {
1682
    drupal_set_message($message, $type, FALSE);
1683
  }
1684
}
1685

    
1686
/**
1687
 * Implements hook_mail().
1688
 */
1689
function webform_mail($key, &$message, $params) {
1690
  $message['headers'] = array_merge($message['headers'], $params['headers']);
1691
  $message['subject'] = $params['subject'];
1692
  $message['body'][] = $params['message'];
1693
}
1694

    
1695
/**
1696
 * Implements hook_block_info().
1697
 */
1698
function webform_block_info() {
1699
  $blocks = array();
1700
  $webform_node_types = webform_variable_get('webform_node_types');
1701
  if (!empty($webform_node_types)) {
1702
    $query = db_select('webform', 'w')->fields('w')->fields('n', array('title'));
1703
    $query->leftJoin('node', 'n', 'w.nid = n.nid');
1704
    $query->condition('w.block', 1);
1705
    $query->condition('n.type', $webform_node_types, 'IN');
1706
    $result = $query->execute();
1707
    foreach ($result as $data) {
1708
      $blocks['client-block-' . $data->nid] = array(
1709
        'info' => t('Webform: !title', array('!title' => $data->title)),
1710
        'cache' => DRUPAL_NO_CACHE,
1711
      );
1712
    }
1713
  }
1714
  return $blocks;
1715
}
1716

    
1717
/**
1718
 * Implements hook_block_view().
1719
 */
1720
function webform_block_view($delta = '') {
1721
  global $user;
1722

    
1723
  // Load the block-specific configuration settings.
1724
  $webform_blocks = variable_get('webform_blocks', array());
1725
  $settings = isset($webform_blocks[$delta]) ? $webform_blocks[$delta] : array();
1726
  $settings += array(
1727
    'display' => 'form',
1728
    'pages_block' => 0,
1729
  );
1730

    
1731
  // Get the node ID from delta.
1732
  $nid = drupal_substr($delta, strrpos($delta, '-') + 1);
1733

    
1734
  // Load node in current language.
1735
  if (module_exists('translation')) {
1736
    global $language;
1737
    if (($translations = translation_node_get_translations($nid)) && (isset($translations[$language->language]))) {
1738
      $nid = $translations[$language->language]->nid;
1739
    }
1740
  }
1741

    
1742
  // The webform node to display in the block.
1743
  $node = node_load($nid);
1744

    
1745
  // Return if user has no access to the webform node.
1746
  if (!node_access('view', $node)) {
1747
    return;
1748
  }
1749

    
1750
  // This is a webform node block.
1751
  $node->webform_block = TRUE;
1752

    
1753

    
1754
  // If not displaying pages in the block, set the #action property on the form.
1755
  if ($settings['pages_block']) {
1756
    $node->webform['action'] = FALSE;
1757
  }
1758
  else {
1759
    $query = array_diff_key($_GET, array('q' => ''));
1760
    $node->webform['action'] = url('node/' . $node->nid, array('query' => $query));
1761
  }
1762

    
1763
  // Generate the content of the block based on display settings.
1764
  if ($settings['display'] == 'form') {
1765
    webform_node_view($node, 'full');
1766
    $content = isset($node->content['webform']) ? $node->content['webform'] : array();
1767
  }
1768
  else {
1769
    $teaser = ($settings['display'] == 'teaser') ? 'teaser' : 'full';
1770
    $content = node_view($node, $teaser);
1771
  }
1772

    
1773
  // Add contextual links for the webform node if they aren't already there.
1774
  if (!isset($content['#contextual_links']['node'])) {
1775
    $content['#contextual_links']['node'] = array('node', array($node->nid));
1776
  }
1777

    
1778
  // Create the block, using the node title for the block title.
1779
  // Note that we render the content immediately here rather than passing back
1780
  // a renderable so that if the block is empty it is hidden.
1781
  $block = array(
1782
    'subject' => check_plain($node->title),
1783
    'content' => drupal_render($content),
1784
  );
1785
  return $block;
1786
}
1787

    
1788
/**
1789
 * Implements hook_block_configure().
1790
 */
1791
function webform_block_configure($delta = '') {
1792
  // Load the block-specific configuration settings.
1793
  $webform_blocks = variable_get('webform_blocks', array());
1794
  $settings = isset($webform_blocks[$delta]) ? $webform_blocks[$delta] : array();
1795
  $settings += array(
1796
    'display' => 'form',
1797
    'pages_block' => 0,
1798
  );
1799

    
1800
  $form = array();
1801
  $form['display'] = array(
1802
    '#type' => 'radios',
1803
    '#title' => t('Display mode'),
1804
    '#default_value' => $settings['display'],
1805
    '#options' => array(
1806
      'form' => t('Form only'),
1807
      'full' => t('Full node'),
1808
      'teaser' => t('Teaser'),
1809
    ),
1810
    '#description' => t('The display mode determines how much of the webform to show within the block.'),
1811
  );
1812

    
1813
  $form['pages_block'] = array(
1814
    '#type' => 'checkbox',
1815
    '#title' => t('Show all webform pages in block'),
1816
    '#default_value' => $settings['pages_block'],
1817
    '#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.'),
1818
  );
1819

    
1820
  return $form;
1821
}
1822

    
1823
/**
1824
 * Implements hook_block_save().
1825
 */
1826
function webform_block_save($delta = '', $edit = array()) {
1827
  // Load the previously defined block-specific configuration settings.
1828
  $settings = variable_get('webform_blocks', array());
1829
  // Build the settings array.
1830
  $new_settings[$delta] = array(
1831
    'display' => $edit['display'],
1832
    'pages_block' => $edit['pages_block'],
1833
  );
1834
  // We store settings for multiple blocks in just one variable
1835
  // so we merge the existing settings with the new ones before save.
1836
  variable_set('webform_blocks', array_merge($settings, $new_settings));
1837
}
1838

    
1839
/**
1840
 * Client form generation function. If this is displaying an existing
1841
 * submission, pass in the $submission variable with the contents of the
1842
 * submission to be displayed.
1843
 *
1844
 * @param $form
1845
 *   The current form array (always empty).
1846
 * @param $form_state
1847
 *   The current form values of a submission, used in multipage webforms.
1848
 * @param $node
1849
 *   The current webform node.
1850
 * @param $submission
1851
 *   An object containing information about the form submission if we're
1852
 *   displaying a result.
1853
 * @param $is_draft
1854
 *   Optional. Set to TRUE if displaying a draft.
1855
 * @param $filter
1856
 *   Whether or not to filter the contents of descriptions and values when
1857
 *   building the form. Values need to be unfiltered to be editable by
1858
 *   Form Builder.
1859
 */
1860
function webform_client_form($form, &$form_state, $node, $submission, $is_draft = FALSE, $filter = TRUE) {
1861
  global $user;
1862

    
1863
  // Attach necessary JavaScript and CSS.
1864
  $form['#attached'] = array(
1865
    'css' => array(drupal_get_path('module', 'webform') . '/css/webform.css'),
1866
    'js' => array(drupal_get_path('module', 'webform') . '/js/webform.js'),
1867
  );
1868
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.components');
1869
  form_load_include($form_state, 'inc', 'webform', 'includes/webform.submissions');
1870

    
1871
  $form['#process'] = array(
1872
    'webform_client_form_includes',
1873
  );
1874

    
1875
  // If in a multi-step form, a submission ID may be specified in form state.
1876
  // Load this submission. This allows anonymous users to use auto-save.
1877
  if (empty($submission) && !empty($form_state['values']['details']['sid'])) {
1878
    $submission = webform_get_submission($node->nid, $form_state['values']['details']['sid']);
1879
    $is_draft = $submission->is_draft;
1880
  }
1881

    
1882
  // Bind arguments to $form to make them available in theming and form_alter.
1883
  $form['#node'] = $node;
1884
  $form['#submission'] = $submission;
1885
  $form['#is_draft'] = $is_draft;
1886
  $form['#filter'] = $filter;
1887

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

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

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

    
1897
  // Sometimes when displaying a webform as a teaser or block, a custom action
1898
  // property is set to direct the user to the node page.
1899
  if (!empty($node->webform['action'])) {
1900
    $form['#action'] = $node->webform['action'];
1901
  }
1902

    
1903
  $form['#submit'] = array('webform_client_form_pages', 'webform_client_form_submit');
1904
  $form['#validate'] = array('webform_client_form_validate');
1905

    
1906
  if (is_array($node->webform['components']) && !empty($node->webform['components'])) {
1907
    // Prepare a new form array.
1908
    $form['submitted'] = array(
1909
      '#tree' => TRUE
1910
    );
1911
    $form['details'] = array(
1912
      '#tree' => TRUE,
1913
    );
1914

    
1915
    // Put the components into a tree structure.
1916
    if (!isset($form_state['storage']['component_tree'])) {
1917
      $form_state['webform']['component_tree'] = array();
1918
      $form_state['webform']['page_count'] = 1;
1919
      $form_state['webform']['page_num'] = 1;
1920
      _webform_components_tree_build($node->webform['components'], $form_state['webform']['component_tree'], 0, $form_state['webform']['page_count']);
1921
    }
1922
    else {
1923
      $form_state['webform']['component_tree'] = $form_state['storage']['component_tree'];
1924
      $form_state['webform']['page_count'] = $form_state['storage']['page_count'];
1925
      $form_state['webform']['page_num'] = $form_state['storage']['page_num'];
1926
    }
1927

    
1928
    // Shorten up our variable names.
1929
    $component_tree = $form_state['webform']['component_tree'];
1930
    $page_count = $form_state['webform']['page_count'];
1931
    $page_num = $form_state['webform']['page_num'];
1932

    
1933
    if ($page_count > 1) {
1934
      $next_page_labels = array();
1935
      $prev_page_labels = array();
1936
    }
1937

    
1938
    // Recursively add components to the form. The unfiltered version of the
1939
    // form (typically used in Form Builder), includes all components.
1940
    foreach ($component_tree['children'] as $cid => $component) {
1941
      $component_value = isset($form_state['values']['submitted'][$cid]) ? $form_state['values']['submitted'][$cid] : NULL;
1942
      if ($filter == FALSE || _webform_client_form_rule_check($node, $component, $page_num, $form_state)) {
1943
        if ($component['type'] == 'pagebreak') {
1944
          $next_page_labels[$component['page_num'] - 1] = !empty($component['extra']['next_page_label']) ? t($component['extra']['next_page_label']) : t('Next Page >');
1945
          $prev_page_labels[$component['page_num']] = !empty($component['extra']['prev_page_label']) ? t($component['extra']['prev_page_label']) : t('< Previous Page');
1946
        }
1947
        _webform_client_form_add_component($node, $component, $component_value, $form['submitted'], $form, $form_state, $submission, 'form', $page_num, $filter);
1948
      }
1949
    }
1950

    
1951
    // These form details help managing data upon submission.
1952
    $form['details']['nid'] = array(
1953
      '#type' => 'value',
1954
      '#value' => $node->nid,
1955
    );
1956
    $form['details']['sid'] = array(
1957
      '#type' => 'hidden',
1958
      '#value' => isset($submission->sid) ? $submission->sid : NULL,
1959
    );
1960
    $form['details']['uid'] = array(
1961
      '#type' => 'value',
1962
      '#value' => isset($submission->uid) ? $submission->uid : $user->uid,
1963
    );
1964
    $form['details']['page_num'] = array(
1965
      '#type'  => 'hidden',
1966
      '#value' => $page_num,
1967
    );
1968
    $form['details']['page_count'] = array(
1969
      '#type'  => 'hidden',
1970
      '#value' => $page_count,
1971
    );
1972
    $form['details']['finished'] = array(
1973
      '#type' => 'hidden',
1974
      '#value' => isset($submission->is_draft) ? (!$submission->is_draft) : 0,
1975
    );
1976

    
1977
    // Add buttons for pages, drafts, and submissions.
1978
    $form['actions'] = array(
1979
      '#type' => 'actions',
1980
      '#weight' => 1000,
1981
    );
1982

    
1983
    // Add the draft button.
1984
    if ($node->webform['allow_draft'] && (empty($submission) || $submission->is_draft) && $user->uid != 0) {
1985
      $form['actions']['draft'] = array(
1986
        '#type' => 'submit',
1987
        '#value' => t('Save Draft'),
1988
        '#weight' => -2,
1989
        '#validate' => array(),
1990
        '#attributes' => array('formnovalidate' => 'formnovalidate'),
1991
      );
1992
    }
1993

    
1994
    if ($page_count > 1) {
1995
      // Add the submit button(s).
1996
      if ($page_num > 1) {
1997
        $form['actions']['previous'] = array(
1998
          '#type' => 'submit',
1999
          '#value' => $prev_page_labels[$page_num],
2000
          '#weight' => 5,
2001
          '#validate' => array(),
2002
          '#attributes' => array('formnovalidate' => 'formnovalidate'),
2003
        );
2004
      }
2005
      if ($page_num == $page_count) {
2006
        $form['actions']['submit'] = array(
2007
          '#type' => 'submit',
2008
          '#value' => empty($node->webform['submit_text']) ? t('Submit') : t($node->webform['submit_text']),
2009
          '#weight' => 10,
2010
        );
2011
      }
2012
      elseif ($page_num < $page_count) {
2013
        $form['actions']['next'] = array(
2014
          '#type' => 'submit',
2015
          '#value' => $next_page_labels[$page_num],
2016
          '#weight' => 10,
2017
        );
2018
      }
2019
    }
2020
    else {
2021
      // Add the submit button.
2022
      $form['actions']['submit'] = array(
2023
        '#type' => 'submit',
2024
        '#value' => empty($node->webform['submit_text']) ? t('Submit') : t($node->webform['submit_text']),
2025
        '#weight' => 10,
2026
      );
2027
    }
2028
  }
2029

    
2030
  return $form;
2031
}
2032

    
2033
/**
2034
 * Process function for webform_client_form().
2035
 *
2036
 * Include all the enabled components for this form to ensure availability.
2037
 */
2038
function webform_client_form_includes($form, $form_state) {
2039
  $components = webform_components();
2040
  foreach ($components as $component_type => $component) {
2041
    webform_component_include($component_type);
2042
  }
2043
  return $form;
2044
}
2045

    
2046
/**
2047
 * Check if a component should be displayed on the current page.
2048
 */
2049
function _webform_client_form_rule_check($node, $component, $page_num, $form_state = NULL, $submission = NULL) {
2050
  $conditional_values = isset($component['extra']['conditional_values']) ? $component['extra']['conditional_values'] : NULL;
2051
  $conditional_component = isset($component['extra']['conditional_component']) && isset($node->webform['components'][$component['extra']['conditional_component']]) ? $node->webform['components'][$component['extra']['conditional_component']] : NULL;
2052
  $conditional_cid = $conditional_component['cid'];
2053

    
2054
  // Check the rules for this entire page. Note individual page breaks are
2055
  // checked down below in the individual component rule checks.
2056
  $show_page = TRUE;
2057
  if ($component['page_num'] > 1 && $component['type'] != 'pagebreak') {
2058
    foreach ($node->webform['components'] as $cid => $page_component) {
2059
      if ($page_component['type'] == 'pagebreak' && $page_component['page_num'] == $page_num) {
2060
        $show_page = _webform_client_form_rule_check($node, $page_component, $page_num, $form_state, $submission);
2061
        break;
2062
      }
2063
    }
2064
  }
2065

    
2066
  // Check any parents' visibility rules.
2067
  $show_parent = $show_page;
2068
  if ($show_parent && $component['pid'] && isset($node->webform['components'][$component['pid']])) {
2069
    $parent_component = $node->webform['components'][$component['pid']];
2070
    $show_parent = _webform_client_form_rule_check($node, $parent_component, $page_num, $form_state, $submission);
2071
  }
2072

    
2073
  // Check the individual component rules.
2074
  $show_component = $show_parent;
2075
  if ($show_component && ($page_num == 0 || $component['page_num'] == $page_num) && $conditional_component && strlen(trim($conditional_values))) {
2076
    $input_values = array();
2077
    if (isset($form_state)) {
2078
      $input_value = isset($form_state['values']['submitted'][$conditional_cid]) ? $form_state['values']['submitted'][$conditional_cid] : NULL;
2079
      $input_values = is_array($input_value) ? $input_value : array($input_value);
2080
    }
2081
    elseif (isset($submission)) {
2082
      $input_values = isset($submission->data[$conditional_cid]['value']) ? $submission->data[$conditional_cid]['value'] : array();
2083
    }
2084

    
2085
    $test_values = array_map('trim', explode("\n", $conditional_values));
2086
    if (empty($input_values) && !empty($test_values)) {
2087
      $show_component = FALSE;
2088
    }
2089
    else {
2090
      foreach ($input_values as $input_value) {
2091
        if ($show_component = in_array($input_value, $test_values)) {
2092
          break;
2093
        }
2094
      }
2095
    }
2096

    
2097
    if ($component['extra']['conditional_operator'] == '!=') {
2098
      $show_component = !$show_component;
2099
    }
2100
  }
2101

    
2102
  return $show_component;
2103
}
2104

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

    
2139
  // Load with submission information if necessary.
2140
  if ($format != 'form') {
2141
    // This component is display only.
2142
    $data = empty($submission->data[$cid]['value']) ? NULL : $submission->data[$cid]['value'];
2143
    if ($display_element = webform_component_invoke($component['type'], 'display', $component, $data, $format)) {
2144
      // Set access based on the private property.
2145
      $element['#access'] = $component_access;
2146

    
2147
      // Ensure the component is added as a property.
2148
      $display_element['#webform_component'] = $component;
2149

    
2150
      // Allow modules to modify a "display only" webform component.
2151
      drupal_alter('webform_component_display', $display_element, $component);
2152

    
2153
      // The form_builder() function usually adds #parents and #id for us, but
2154
      // because these are not marked for #input, we need to add them manually.
2155
      if (!isset($display_element['#parents'])) {
2156
        $parents = isset($parent_fieldset['#parents']) ? $parent_fieldset['#parents'] : array('submitted');
2157
        $parents[] = $component['form_key'];
2158
        $display_element['#parents'] = $parents;
2159
      }
2160
      if (!isset($display_element['#id'])) {
2161
        $display_element['#id'] = drupal_clean_css_identifier('edit-' . implode('-', $display_element['#parents']));
2162
      }
2163

    
2164
      // Add the element into the proper parent in the display.
2165
      $parent_fieldset[$component['form_key']] = $display_element;
2166
    }
2167
  }
2168
  // Show the component only on its form page, or if building an unfiltered
2169
  // version of the form (such as for Form Builder).
2170
  elseif ($component['page_num'] == $page_num || $filter == FALSE) {
2171
    // Add this user-defined field to the form (with all the values that are always available).
2172
    $data = isset($submission->data[$cid]['value']) ? $submission->data[$cid]['value'] : NULL;
2173
    if ($element = webform_component_invoke($component['type'], 'render', $component, $data, $filter)) {
2174
      // Set access based on the private property.
2175
      $element['#access'] = $component_access;
2176

    
2177
      // Ensure the component is added as a property.
2178
      $element['#webform_component'] = $component;
2179

    
2180
      // The 'private' option is in most components, but it's not a real
2181
      // property. Add it for Form Builder compatibility.
2182
      if (webform_component_feature($component['type'], 'private')) {
2183
        $element['#webform_private'] = $component['extra']['private'];
2184
      }
2185

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

    
2189
      // Add the element into the proper parent in the form.
2190
      $parent_fieldset[$component['form_key']] = $element;
2191

    
2192
      // Override the value if one already exists in the form state.
2193
      if (isset($component_value)) {
2194
        $parent_fieldset[$component['form_key']]['#default_value'] = $component_value;
2195
        if (is_array($component_value)) {
2196
          foreach ($component_value as $key => $value) {
2197
            if (isset($parent_fieldset[$component['form_key']][$key])) {
2198
              $parent_fieldset[$component['form_key']][$key]['#default_value'] = $value;
2199
            }
2200
          }
2201
        }
2202
      }
2203
    }
2204
    else {
2205
      drupal_set_message(t('The webform component @type is not able to be displayed', array('@type' => $component['type'])));
2206
    }
2207
  }
2208

    
2209
  // Disable validation initially on all elements. We manually validate
2210
  // all webform elements in webform_client_form_validate().
2211
  if (isset($parent_fieldset[$component['form_key']])) {
2212
    $parent_fieldset[$component['form_key']]['#validated'] = TRUE;
2213
    $parent_fieldset[$component['form_key']]['#webform_validated'] = FALSE;
2214
  }
2215

    
2216
  if (isset($component['children']) && is_array($component['children'])) {
2217
    foreach ($component['children'] as $scid => $subcomponent) {
2218
      $subcomponent_value = isset($form_state['values']['submitted'][$scid]) ? $form_state['values']['submitted'][$scid] : NULL;
2219
      if (_webform_client_form_rule_check($node, $subcomponent, $page_num, $form_state, $submission)) {
2220
        _webform_client_form_add_component($node, $subcomponent, $subcomponent_value, $parent_fieldset[$component['form_key']], $form, $form_state, $submission, $format, $page_num, $filter);
2221
      }
2222
    }
2223
  }
2224
}
2225

    
2226
function webform_client_form_validate($form, &$form_state) {
2227
  $node = node_load($form_state['values']['details']['nid']);
2228
  $finished = $form_state['values']['details']['finished'];
2229

    
2230
  // Check that the submissions have not exceeded the total submission limit.
2231
  if ($node->webform['total_submit_limit'] != -1) {
2232
    module_load_include('inc', 'webform', 'includes/webform.submissions');
2233
    // Check if the total number of entries was reached before the user submitted
2234
    // the form.
2235
    if (!$finished && $total_limit_exceeded = _webform_submission_total_limit_check($node)) {
2236
      // Show the user the limit has exceeded.
2237
      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));
2238
      form_set_error('', NULL);
2239
      return;
2240
    }
2241
  }
2242

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

    
2249
    if (!$finished && $user_limit_exceeded = _webform_submission_user_limit_check($node)) {
2250
      // Assume that webform_view_messages will print out the necessary message,
2251
      // then stop the processing of the form with an empty form error.
2252
      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));
2253
      form_set_error('', NULL);
2254
      return;
2255
    }
2256
  }
2257

    
2258
  // Run all #element_validate and #required checks. These are skipped initially
2259
  // by setting #validated = TRUE on all components when they are added.
2260
  _webform_client_form_validate($form, $form_state);
2261
}
2262

    
2263
/**
2264
 * Recursive validation function to trigger normal Drupal validation.
2265
 *
2266
 * This function imitates _form_validate in Drupal's form.inc, only it sets
2267
 * a different property to ensure that validation has occurred.
2268
 */
2269
function _webform_client_form_validate($elements, &$form_state, $first_run = TRUE) {
2270
  static $form;
2271
  if ($first_run) {
2272
    $form = $elements;
2273
  }
2274

    
2275
  // Recurse through all children.
2276
  foreach (element_children($elements) as $key) {
2277
    if (isset($elements[$key]) && $elements[$key]) {
2278
      _webform_client_form_validate($elements[$key], $form_state, FALSE);
2279
    }
2280
  }
2281
  // Validate the current input.
2282
  if (isset($elements['#webform_validated']) && $elements['#webform_validated'] == FALSE) {
2283
    if (isset($elements['#needs_validation'])) {
2284
      // Make sure a value is passed when the field is required.
2285
      // A simple call to empty() will not cut it here as some fields, like
2286
      // checkboxes, can return a valid value of '0'. Instead, check the
2287
      // length if it's a string, and the item count if it's an array. For
2288
      // radios, FALSE means that no value was submitted, so check that too.
2289
      if ($elements['#required'] && (!count($elements['#value']) || (is_string($elements['#value']) && strlen(trim($elements['#value'])) == 0) || $elements['#value'] === FALSE)) {
2290
        form_error($elements, t('!name field is required.', array('!name' => $elements['#title'])));
2291
      }
2292

    
2293
      // Verify that the value is not longer than #maxlength.
2294
      if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
2295
        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']))));
2296
      }
2297

    
2298
      if (isset($elements['#options']) && isset($elements['#value'])) {
2299
        if ($elements['#type'] == 'select') {
2300
          $options = form_options_flatten($elements['#options']);
2301
        }
2302
        else {
2303
          $options = $elements['#options'];
2304
        }
2305
        if (is_array($elements['#value'])) {
2306
          $value = $elements['#type'] == 'checkboxes' ? array_keys(array_filter($elements['#value'])) : $elements['#value'];
2307
          foreach ($value as $v) {
2308
            if (!isset($options[$v])) {
2309
              form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
2310
              watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
2311
            }
2312
          }
2313
        }
2314
        elseif ($elements['#value'] !== '' && !isset($options[$elements['#value']])) {
2315
          form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
2316
          watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
2317
        }
2318
      }
2319
    }
2320

    
2321
    // Call any element-specific validators. These must act on the element
2322
    // #value data.
2323
    if (isset($elements['#element_validate'])) {
2324
      foreach ($elements['#element_validate'] as $function) {
2325
        if (function_exists($function))  {
2326
          $function($elements, $form_state, $form);
2327
        }
2328
      }
2329
    }
2330
    $elements['#webform_validated'] = TRUE;
2331
  }
2332
}
2333

    
2334
/**
2335
 * Handle the processing of pages and conditional logic.
2336
 */
2337
function webform_client_form_pages($form, &$form_state) {
2338
  $node = node_load($form_state['values']['details']['nid']);
2339

    
2340
  // Multistep forms may not have any components on the first page.
2341
  if (!isset($form_state['values']['submitted'])) {
2342
    $form_state['values']['submitted'] = array();
2343
  }
2344

    
2345
  // Move special settings to storage.
2346
  if (isset($form_state['webform']['component_tree'])) {
2347
    $form_state['storage']['component_tree'] = $form_state['webform']['component_tree'];
2348
    $form_state['storage']['page_count'] = $form_state['webform']['page_count'];
2349
    $form_state['storage']['page_num'] = $form_state['webform']['page_num'];
2350
  }
2351

    
2352
  // Perform post processing by components.
2353
  _webform_client_form_submit_process($node, $form_state['values']['submitted']);
2354

    
2355
  // Flatten trees within the submission.
2356
  $form_state['values']['submitted_tree'] = $form_state['values']['submitted'];
2357
  $form_state['values']['submitted'] = _webform_client_form_submit_flatten($node, $form_state['values']['submitted']);
2358

    
2359
  // Assume the form is completed unless the page logic says otherwise.
2360
  $form_state['webform_completed'] = TRUE;
2361

    
2362
  // Check for a multi-page form that is not yet complete.
2363
  $submit_op = !empty($form['actions']['submit']['#value']) ? $form['actions']['submit']['#value'] : t('Submit');
2364
  $draft_op = !empty($form['actions']['draft']['#value']) ? $form['actions']['draft']['#value'] : t('Save Draft');
2365
  if (!in_array($form_state['values']['op'], array($submit_op, $draft_op))) {
2366
    // Store values from the current page in the form state storage.
2367
    if (is_array($form_state['values']['submitted'])) {
2368
      foreach ($form_state['values']['submitted'] as $key => $val) {
2369
        $form_state['storage']['submitted'][$key] = $val;
2370
      }
2371
    }
2372

    
2373
    // Update form state values with those from storage.
2374
    if (isset($form_state['storage']['submitted'])) {
2375
      foreach ($form_state['storage']['submitted'] as $key => $val) {
2376
        $form_state['values']['submitted'][$key] = $val;
2377
      }
2378
    }
2379

    
2380
    // Set the page number.
2381
    if (!isset($form_state['storage']['page_num'])) {
2382
      $form_state['storage']['page_num'] = 1;
2383
    }
2384
    if (end($form_state['clicked_button']['#parents']) == 'next') {
2385
      $direction = 1;
2386
    }
2387
    else {
2388
      $direction = 0;
2389
    }
2390

    
2391
    // If the next page has no components that need to be displayed, skip it.
2392
    if (isset($direction)) {
2393
      $components = $direction ? $node->webform['components'] : array_reverse($node->webform['components'], TRUE);
2394
      $last_component = end($node->webform['components']);
2395
      foreach ($components as $component) {
2396
        if ($component['type'] == 'pagebreak' && (
2397
            $direction == 1 && $component['page_num'] > $form_state['storage']['page_num'] ||
2398
            $direction == 0 && $component['page_num'] <= $form_state['storage']['page_num'])) {
2399
          $previous_pagebreak = $component;
2400
          continue;
2401
        }
2402
        if (isset($previous_pagebreak)) {
2403
          $page_num = $previous_pagebreak['page_num'] + $direction - 1;
2404
          // If we've found an component on this page, advance to that page.
2405
          if ($component['page_num'] == $page_num && _webform_client_form_rule_check($node, $component, $page_num, $form_state)) {
2406
            $form_state['storage']['page_num'] = $page_num;
2407
            break;
2408
          }
2409
          // If we've gotten to the end of the form without finding any more
2410
          // components, set the page number more than the max, ending the form.
2411
          elseif ($direction && $component['cid'] == $last_component['cid']) {
2412
            $form_state['storage']['page_num'] = $page_num + 1;
2413
          }
2414
        }
2415
      }
2416
    }
2417

    
2418
    // The form is done if the page number is greater than the page count.
2419
    $form_state['webform_completed'] = $form_state['storage']['page_num'] > $form_state['storage']['page_count'];
2420
  }
2421

    
2422
  // Merge any stored submission data for multistep forms.
2423
  if (isset($form_state['storage']['submitted'])) {
2424
    $original_values = is_array($form_state['values']['submitted']) ? $form_state['values']['submitted'] : array();
2425
    unset($form_state['values']['submitted']);
2426

    
2427
    foreach ($form_state['storage']['submitted'] as $key => $val) {
2428
      $form_state['values']['submitted'][$key] = $val;
2429
    }
2430
    foreach ($original_values as $key => $val) {
2431
      $form_state['values']['submitted'][$key] = $val;
2432
    }
2433

    
2434
    // Remove the variable so it doesn't show up in the additional processing.
2435
    unset($original_values);
2436
  }
2437

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

    
2441
  // Determine what we need to do on the next page.
2442
  if (!empty($form_state['save_draft']) || !$form_state['webform_completed']) {
2443
    // Rebuild the form and display the current (on drafts) or next page.
2444
    $form_state['rebuild'] = TRUE;
2445
  }
2446
  else {
2447
    // Remove the form state storage now that we're done with the pages.
2448
    $form_state['rebuild'] = FALSE;
2449
    unset($form_state['storage']);
2450
  }
2451
}
2452

    
2453
/**
2454
 * Submit handler for saving the form values and sending e-mails.
2455
 */
2456
function webform_client_form_submit($form, &$form_state) {
2457
  module_load_include('inc', 'webform', 'includes/webform.submissions');
2458
  module_load_include('inc', 'webform', 'includes/webform.components');
2459
  global $user;
2460

    
2461
  if (empty($form_state['save_draft']) && empty($form_state['webform_completed'])) {
2462
    return;
2463
  }
2464

    
2465
  $node = $form['#node'];
2466
  $sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;
2467

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

    
2471
  if (!$sid) {
2472
    // Create a new submission object.
2473
    $submission = (object) array(
2474
      'nid' => $node->nid,
2475
      'uid' => $form_state['values']['details']['uid'],
2476
      'submitted' => REQUEST_TIME,
2477
      'remote_addr' => ip_address(),
2478
      'is_draft' => $is_draft,
2479
      'data' => webform_submission_data($node, $form_state['values']['submitted']),
2480
    );
2481
  }
2482
  else {
2483
    // To maintain time and user information, load the existing submission.
2484
    $submission = webform_get_submission($node->webform['nid'], $sid);
2485
    $submission->is_draft = $is_draft;
2486

    
2487
    // Merge with new submission data. The + operator maintains numeric keys.
2488
    // This maintains existing data with just-submitted data when a user resumes
2489
    // a submission previously saved as a draft.
2490
    $new_data = webform_submission_data($node, $form_state['values']['submitted']);
2491
    $submission->data = $new_data + $submission->data;
2492
  }
2493

    
2494
  // If there is no data to be saved (such as on a multipage form with no fields
2495
  // on the first page), process no further. Submissions with no data cannot
2496
  // be loaded from the database as efficiently, so we don't save them at all.
2497
  if (empty($submission->data)) {
2498
    return;
2499
  }
2500

    
2501
  // Save the submission to the database.
2502
  if (!$sid) {
2503
    // No sid was found thus insert it in the dataabase.
2504
    $form_state['values']['details']['sid'] = $sid = webform_submission_insert($node, $submission);
2505
    $form_state['values']['details']['is_new'] = TRUE;
2506

    
2507
    // Set a cookie including the server's submission time.
2508
    // The cookie expires in the length of the interval plus a day to compensate for different timezones.
2509
    if (variable_get('webform_use_cookies', 0)) {
2510
      $cookie_name = 'webform-' . $node->nid;
2511
      $time = REQUEST_TIME;
2512
      $params = session_get_cookie_params();
2513
      setcookie($cookie_name . '[' . $time . ']', $time, $time + $node->webform['submit_interval'] + 86400, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
2514
    }
2515

    
2516
    // Save session information about this submission for anonymous users,
2517
    // allowing them to access or edit their submissions.
2518
    if (!$user->uid && user_access('access own webform submissions')) {
2519
      $_SESSION['webform_submission'][$form_state['values']['details']['sid']] = $node->nid;
2520
    }
2521
  }
2522
  else {
2523
    // Sid was found thus update the existing sid in the database.
2524
    webform_submission_update($node, $submission);
2525
    $form_state['values']['details']['is_new'] = FALSE;
2526
  }
2527

    
2528
  // Check if this form is sending an email.
2529
  if (!$is_draft && !$form_state['values']['details']['finished']) {
2530
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);
2531
    webform_submission_send_mail($node, $submission);
2532
  }
2533

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

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

    
2541

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

    
2545
  // Check confirmation and redirect_url fields.
2546
  $message = NULL;
2547
  $redirect = NULL;
2548
  $external_url = FALSE;
2549
  if (isset($form['actions']['draft']['#value']) && $form_state['values']['op'] == $form['actions']['draft']['#value']) {
2550
    $message = t('Submission saved. You may return to this form later and it will restore the current values.');
2551
  }
2552
  elseif ($is_draft) {
2553
    $redirect = NULL;
2554
  }
2555
  elseif (!empty($form_state['values']['details']['finished'])) {
2556
    $message = t('Submission updated.');
2557
  }
2558
  elseif ($redirect_url == '<none>') {
2559
    $redirect = NULL;
2560
  }
2561
  elseif ($redirect_url == '<confirmation>') {
2562
    $redirect = array('node/' . $node->nid . '/done', array('query' => array('sid' => $sid)));
2563
  }
2564
  elseif (valid_url($redirect_url, TRUE)) {
2565
    $redirect = $redirect_url;
2566
    $external_url = TRUE;
2567
  }
2568
  elseif ($redirect_url && strpos($redirect_url, 'http') !== 0) {
2569
    $parts = drupal_parse_url($redirect_url);
2570
    $parts['query'] ? ($parts['query']['sid'] = $sid) : ($parts['query'] = array('sid' => $sid));
2571
    $query = $parts['query'];
2572
    $redirect = array($parts['path'], array('query' => $query, 'fragment' => $parts['fragment']));
2573
  }
2574

    
2575
  // Show a message if manually set.
2576
  if (isset($message)) {
2577
    drupal_set_message($message);
2578
  }
2579
  // If redirecting and we have a confirmation message, show it as a message.
2580
  elseif (!$is_draft && !$external_url && (!empty($redirect_url) && $redirect_url != '<confirmation>') && !empty($confirmation)) {
2581
    drupal_set_message(check_markup($confirmation, $node->webform['confirmation_format'], '', TRUE));
2582
  }
2583

    
2584
  $form_state['redirect'] = $redirect;
2585
}
2586

    
2587
/**
2588
 * Post processes the submission tree with any updates from components.
2589
 *
2590
 * @param $node
2591
 *   The full webform node.
2592
 * @param $form_values
2593
 *   The form values for the form.
2594
 * @param $types
2595
 *   Optional. Specific types to perform processing.
2596
 * @param $parent
2597
 *   Internal use. The current parent CID whose children are being processed.
2598
 */
2599
function _webform_client_form_submit_process($node, &$form_values, $types = NULL, $parent = 0) {
2600
  if (is_array($form_values)) {
2601
    foreach ($form_values as $form_key => $value) {
2602
      $cid = webform_get_cid($node, $form_key, $parent);
2603
      if (is_array($value) && isset($node->webform['components'][$cid]['type']) && webform_component_feature($node->webform['components'][$cid]['type'], 'group')) {
2604
        _webform_client_form_submit_process($node, $form_values[$form_key], $types, $cid);
2605
      }
2606

    
2607
      if (isset($node->webform['components'][$cid])) {
2608
        // Call the component process submission function.
2609
        $component = $node->webform['components'][$cid];
2610
        if ((!isset($types) || in_array($component['type'], $types)) && webform_component_implements($component['type'], 'submit')) {
2611
          $form_values[$component['form_key']] = webform_component_invoke($component['type'], 'submit', $component, $form_values[$component['form_key']]);
2612
        }
2613
      }
2614
    }
2615
  }
2616
}
2617

    
2618
/**
2619
 * Flattens a submitted form back into a single array representation (rather than nested fields)
2620
 */
2621
function _webform_client_form_submit_flatten($node, $fieldset, $parent = 0) {
2622
  $values = array();
2623

    
2624
  if (is_array($fieldset)) {
2625
    foreach ($fieldset as $form_key => $value) {
2626
      $cid = webform_get_cid($node, $form_key, $parent);
2627

    
2628
      if (is_array($value) && webform_component_feature($node->webform['components'][$cid]['type'], 'group')) {
2629
        $values += _webform_client_form_submit_flatten($node, $value, $cid);
2630
      }
2631
      else {
2632
        $values[$cid] = $value;
2633
      }
2634
    }
2635
  }
2636

    
2637
  return $values;
2638
}
2639

    
2640
/**
2641
 * Prints the confirmation message after a successful submission.
2642
 */
2643
function _webform_confirmation($node) {
2644
  drupal_set_title($node->title);
2645
  webform_set_breadcrumb($node, TRUE);
2646
  $sid = isset($_GET['sid']) ? $_GET['sid'] : NULL;
2647
  return theme(array('webform_confirmation_' . $node->nid, 'webform_confirmation'), array('node' => $node, 'sid' => $sid));
2648
}
2649

    
2650
/**
2651
 * Prepare for theming of the webform form.
2652
 */
2653
function template_preprocess_webform_form(&$vars) {
2654
  if (isset($vars['form']['details']['nid']['#value'])) {
2655
    $vars['nid'] = $vars['form']['details']['nid']['#value'];
2656
  }
2657
  elseif (isset($vars['form']['submission']['#value'])) {
2658
    $vars['nid'] = $vars['form']['submission']['#value']->nid;
2659
  }
2660
}
2661

    
2662
/**
2663
 * Prepare for theming of the webform submission confirmation.
2664
 */
2665
function template_preprocess_webform_confirmation(&$vars) {
2666
  $confirmation = check_markup($vars['node']->webform['confirmation'], $vars['node']->webform['confirmation_format'], '', TRUE);
2667
  // Strip out empty tags added by WYSIWYG editors if needed.
2668
  $vars['confirmation_message'] = strlen(trim(strip_tags($confirmation))) ? $confirmation : '';
2669
}
2670

    
2671
/**
2672
 * Prepare to theme the contents of e-mails sent by webform.
2673
 */
2674
function template_preprocess_webform_mail_message(&$vars) {
2675
  global $user;
2676

    
2677
  $vars['user'] = $user;
2678
  $vars['ip_address'] = ip_address();
2679
}
2680

    
2681
/**
2682
 * A Form API #pre_render function. Sets display based on #title_display.
2683
 *
2684
 * This function is used regularly in D6 for all elements, but specifically for
2685
 * fieldsets in D7, which don't support #title_display natively.
2686
 */
2687
function webform_element_title_display($element) {
2688
  if (isset($element['#title_display']) && strcmp($element['#title_display'], 'none') === 0) {
2689
    $element['#title'] = NULL;
2690
  }
2691
  return $element;
2692
}
2693

    
2694
/**
2695
 * Replacement for theme_form_element().
2696
 */
2697
function theme_webform_element($variables) {
2698
  // Ensure defaults.
2699
  $variables['element'] += array(
2700
    '#title_display' => 'before',
2701
  );
2702

    
2703
  $element = $variables['element'];
2704

    
2705
  // All elements using this for display only are given the "display" type.
2706
  if (isset($element['#format']) && $element['#format'] == 'html') {
2707
    $type = 'display';
2708
  }
2709
  else {
2710
    $type = (isset($element['#type']) && !in_array($element['#type'], array('markup', 'textfield', 'webform_email', 'webform_number'))) ? $element['#type'] : $element['#webform_component']['type'];
2711
  }
2712

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

    
2717
  $wrapper_classes = array(
2718
   'form-item',
2719
   'webform-component',
2720
   'webform-component-' . $type,
2721
  );
2722
  if (isset($element['#title_display']) && strcmp($element['#title_display'], 'inline') === 0) {
2723
    $wrapper_classes[] = 'webform-container-inline';
2724
  }
2725
  $output = '<div class="' . implode(' ', $wrapper_classes) . '" id="webform-component-' . $parents . '">' . "\n";
2726

    
2727
  // If #title_display is none, set it to invisible instead - none only used if
2728
  // we have no title at all to use.
2729
  if ($element['#title_display'] == 'none') {
2730
    $variables['element']['#title_display'] = 'invisible';
2731
    $element['#title_display'] = 'invisible';
2732
  }
2733
  // If #title is not set, we don't display any label or required marker.
2734
  if (!isset($element['#title'])) {
2735
    $element['#title_display'] = 'none';
2736
  }
2737
  $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . _webform_filter_xss($element['#field_prefix']) . '</span> ' : '';
2738
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . _webform_filter_xss($element['#field_suffix']) . '</span>' : '';
2739

    
2740
  switch ($element['#title_display']) {
2741
    case 'inline':
2742
    case 'before':
2743
    case 'invisible':
2744
      $output .= ' ' . theme('form_element_label', $variables);
2745
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
2746
      break;
2747

    
2748
    case 'after':
2749
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
2750
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
2751
      break;
2752

    
2753
    case 'none':
2754
    case 'attribute':
2755
      // Output no label and no required marker, only the children.
2756
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
2757
      break;
2758
  }
2759

    
2760
  if (!empty($element['#description'])) {
2761
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
2762
  }
2763

    
2764
  $output .= "</div>\n";
2765

    
2766
  return $output;
2767
}
2768

    
2769
/**
2770
 * Output a form element in plain text format.
2771
 */
2772
function theme_webform_element_text($variables) {
2773
  $element = $variables['element'];
2774
  $value = $variables['element']['#children'];
2775

    
2776
  $output = '';
2777
  $is_group = webform_component_feature($element['#webform_component']['type'], 'group');
2778

    
2779
  // Output the element title.
2780
  if (isset($element['#title'])) {
2781
    if ($is_group) {
2782
      $output .= '--' . $element['#title'] . '--';
2783
    }
2784
    elseif (!in_array(drupal_substr($element['#title'], -1), array('?', ':', '!', '%', ';', '@'))) {
2785
      $output .= $element['#title'] . ':';
2786
    }
2787
    else {
2788
      $output .= $element['#title'];
2789
    }
2790
  }
2791

    
2792
  // Wrap long values at 65 characters, allowing for a few fieldset indents.
2793
  // It's common courtesy to wrap at 75 characters in e-mails.
2794
  if ($is_group && drupal_strlen($value) > 65) {
2795
    $value = wordwrap($value, 65, "\n");
2796
    $lines = explode("\n", $value);
2797
    foreach ($lines as $key => $line) {
2798
      $lines[$key] = '  ' . $line;
2799
    }
2800
    $value = implode("\n", $lines);
2801
  }
2802

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

    
2806
  // Indent fieldsets.
2807
  if ($is_group) {
2808
    $lines = explode("\n", $output);
2809
    foreach ($lines as $number => $line) {
2810
      if (strlen($line)) {
2811
        $lines[$number] = '  ' . $line;
2812
      }
2813
    }
2814
    $output = implode("\n", $lines);
2815
    $output .= "\n";
2816
  }
2817

    
2818
  if ($output) {
2819
    $output .= "\n";
2820
  }
2821

    
2822
  return $output;
2823
}
2824

    
2825
/**
2826
 * Theme a radio button and another element together.
2827
 *
2828
 * This is used in the e-mail configuration to show a radio button and a text
2829
 * field or select list on the same line.
2830
 */
2831
function theme_webform_inline_radio($variables) {
2832
  $element = $variables['element'];
2833

    
2834
  // Add element's #type and #name as class to aid with JS/CSS selectors.
2835
  $class = array('form-item');
2836
  if (!empty($element['#type'])) {
2837
    $class[] = 'form-type-' . strtr($element['#type'], '_', '-');
2838
  }
2839
  if (!empty($element['#name'])) {
2840
    $class[] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
2841
  }
2842

    
2843
  // Add container-inline to all elements.
2844
  $class[] = 'webform-container-inline';
2845
  if (isset($element['#inline_element']) && isset($variables['element']['#title'])) {
2846
    $variables['element']['#title'] .= ': ';
2847
  }
2848

    
2849
  $output = '<div class="' . implode(' ', $class) . '">' . "\n";
2850
  $output .= ' ' . $element['#children'];
2851
  if (!empty($element['#title'])) {
2852
    $output .= ' ' . theme('form_element_label', $variables) . "\n";
2853
  }
2854
  if (isset($element['#inline_element'])) {
2855
    $output .= ' ' . $element['#inline_element'] . "\n";
2856
  }
2857

    
2858
  if (!empty($element['#description'])) {
2859
    $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
2860
  }
2861

    
2862
  $output .= "</div>\n";
2863

    
2864
  return $output;
2865
}
2866

    
2867
/**
2868
 * Theme the headers when sending an email from webform.
2869
 *
2870
 * @param $node
2871
 *   The complete node object for the webform.
2872
 * @param $submission
2873
 *   The webform submission of the user.
2874
 * @param $email
2875
 *   If you desire to make different e-mail headers depending on the recipient,
2876
 *   you can check the $email['email'] property to output different content.
2877
 *   This will be the ID of the component that is a conditional e-mail
2878
 *   recipient. For the normal e-mails, it will have the value of 'default'.
2879
 * @return
2880
 *   An array of headers to be used when sending a webform email. If headers
2881
 *   for "From", "To", or "Subject" are set, they will take precedence over
2882
 *   the values set in the webform configuration.
2883
 */
2884
function theme_webform_mail_headers($variables) {
2885
  $headers = array(
2886
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
2887
  );
2888
  return $headers;
2889
}
2890

    
2891
/**
2892
 * Check if current user has a draft of this webform, and return the sid.
2893
 */
2894
function _webform_fetch_draft_sid($nid, $uid) {
2895
  return db_select('webform_submissions')
2896
    ->fields('webform_submissions', array('sid'))
2897
    ->condition('nid', $nid)
2898
    ->condition('uid', $uid)
2899
    ->condition('is_draft', 1)
2900
    ->orderBy('submitted', 'DESC')
2901
    ->execute()
2902
    ->fetchField();
2903
}
2904

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

    
2933
  // Don't do any filtering if the string is empty.
2934
  if (strlen(trim($string)) == 0) {
2935
    return $string;
2936
  }
2937

    
2938
  // Setup default token replacements.
2939
  if (!isset($replacements)) {
2940
    $replacements['unsafe'] = array();
2941
    $replacements['safe']['%site'] = variable_get('site_name', 'drupal');
2942
    $replacements['safe']['%date'] = format_date(REQUEST_TIME, 'long');
2943
  }
2944

    
2945
  // Node replacements.
2946
  if (isset($node) && !array_key_exists('%nid', $replacements['safe'])) {
2947
    $replacements['safe']['%nid'] = $node->nid;
2948
    $replacements['safe']['%title'] = $node->title;
2949
  }
2950

    
2951
  // Determine the display format.
2952
  $format = isset($email['html']) && $email['html'] ? 'html' : 'text';
2953

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

    
2958
    // Set the submission ID.
2959
    $replacements['unsafe']['%sid'] = $submission->sid;
2960

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

    
2964
    // Populate token values for each component.
2965
    foreach ($node->webform['components'] as $cid => $component) {
2966
      // Find by form key.
2967
      $parents = webform_component_parent_keys($node, $component);
2968
      $form_key = implode('][', $parents);
2969
      if (isset($submission->data[$cid])) {
2970
        $value = $submission->data[$cid];
2971

    
2972
        $display_element = webform_component_invoke($component['type'], 'display', $component, $value['value'], $format);
2973

    
2974
        // Ensure the component is added as a property.
2975
        $display_element['#webform_component'] = $component;
2976

    
2977
        if (empty($display_element['#parents'])) {
2978
          $display_element['#parents'] = array_merge(array('submitted'), $parents);
2979
        }
2980
        if (empty($display_element['#id'])) {
2981
          $display_element['#id'] = drupal_html_id('edit-' . implode('-', $display_element['#parents']));
2982
        }
2983
        $replacements['email'][$format]['%email[' . $form_key . ']'] = render($display_element);
2984
        $display_element['#theme_wrappers'] = array(); // Remove label and wrappers.
2985
        $replacements['email'][$format]['%value[' . $form_key . ']'] = render($display_element);
2986
      }
2987
      else {
2988
        // Provide an empty value for components without submitted data.
2989
        $replacements['email'][$format]['%email[' . $form_key . ']'] = '';
2990
        $replacements['email'][$format]['%value[' . $form_key . ']'] = '';
2991
      }
2992
    }
2993
    // Reverse the order of tokens so that nested tokens (ie. inside fieldsets)
2994
    // come before their parents.
2995
    $replacements['email'][$format] = array_reverse($replacements['email'][$format]);
2996

    
2997
    // Submission edit URL.
2998
    $replacements['unsafe']['%submission_url'] = url('node/' . $node->nid . '/submission/' . $submission->sid, array('absolute' => TRUE));
2999
  }
3000

    
3001
  // Token for the entire form tree for e-mails.
3002
  if (isset($submission) && isset($email)) {
3003
    $replacements['email'][$format]['%email_values'] = webform_submission_render($node, $submission, $email, $format);
3004
  }
3005

    
3006
  // Provide a list of candidates for token replacement.
3007
  $special_tokens = array(
3008
    'safe' => array(
3009
      '%get' => $_GET,
3010
      '%post' => $_POST,
3011
    ),
3012
    'unsafe' => array(
3013
      '%cookie' => isset($_COOKIE) ? $_COOKIE : array(),
3014
      '%session' => isset($_SESSION) ? $_SESSION : array(),
3015
      '%request' => $_REQUEST,
3016
      '%server' => $_SERVER,
3017
      '%profile' => (array) $user,
3018
    ),
3019
  );
3020

    
3021
  // Replacements of global variable tokens.
3022
  if (!isset($replacements['specials_set'])) {
3023
    $replacements['specials_set'] = TRUE;
3024

    
3025
    // Load profile information if available.
3026
    if ($user->uid) {
3027
      $account = user_load($user->uid);
3028
      $special_tokens['unsafe']['%profile'] = (array) $account;
3029
    }
3030

    
3031
    // User replacements.
3032
    if (!array_key_exists('%uid', $replacements['unsafe'])) {
3033
      $replacements['unsafe']['%uid'] = !empty($user->uid) ? $user->uid : '';
3034
      $replacements['unsafe']['%username'] = isset($user->name) ? $user->name : '';
3035
      $replacements['unsafe']['%useremail'] = isset($user->mail) ? $user->mail : '';
3036
      $replacements['unsafe']['%ip_address'] = ip_address();
3037
    }
3038

    
3039
    // Populate the replacements array with special variables.
3040
    foreach ($special_tokens as $safe_state => $tokens) {
3041
      foreach ($tokens as $token => $variable) {
3042
        // Safety check in case $_POST or some other global has been removed
3043
        // by a naughty module, in which case $variable may be NULL.
3044
        if (!is_array($variable)) {
3045
          continue;
3046
        }
3047

    
3048
        foreach ($variable as $key => $value) {
3049
          // This special case for profile module dates.
3050
          if ($token == '%profile' && is_array($value) && isset($value['year'])) {
3051
            $replacement = webform_strtodate(webform_date_format(), $value['month'] . '/' . $value['day'] . '/' . $value['year'], 'UTC');
3052
          }
3053
          else {
3054
            // Checking for complex types (arrays and objects) fails here with
3055
            // incomplete objects (see http://php.net/is_object), so we check
3056
            // for simple types instead.
3057
            $replacement = (is_string($value) || is_bool($value) || is_numeric($value)) ? $value : '';
3058
          }
3059
          $replacements[$safe_state][$token . '[' . $key . ']'] = $replacement;
3060
        }
3061
      }
3062
    }
3063
  }
3064

    
3065
  // Make a copy of the replacements so we don't affect the static version.
3066
  $safe_replacements = $replacements['safe'];
3067

    
3068
  // Restrict replacements for anonymous users. Not all tokens can be used
3069
  // because they may expose session or other private data to other users when
3070
  // anonymous page caching is enabled.
3071
  if ($user->uid || $allow_anonymous) {
3072
    $safe_replacements += $replacements['unsafe'];
3073
    if (isset($replacements['email'][$format])) {
3074
      $safe_replacements += $replacements['email'][$format];
3075
    }
3076
  }
3077
  else {
3078
    foreach ($replacements['unsafe'] as $key => $value) {
3079
      $safe_replacements[$key] = '';
3080
    }
3081
  }
3082

    
3083
  $find = array_keys($safe_replacements);
3084
  $replace = array_values($safe_replacements);
3085
  $string = str_replace($find, $replace, $string);
3086

    
3087
  // Clean up any unused tokens.
3088
  foreach ($special_tokens as $safe_state => $tokens) {
3089
    foreach (array_keys($tokens) as $token) {
3090
      $string = preg_replace('/\\' . $token . '\[\w+\]/', '', $string);
3091
    }
3092
  }
3093

    
3094
  return $strict ? _webform_filter_xss($string) : $string;
3095
}
3096

    
3097
/**
3098
 * Filters all special tokens provided by webform, and allows basic layout in descriptions.
3099
 */
3100
function _webform_filter_descriptions($string, $node = NULL, $submission = NULL) {
3101
  return strlen($string) == 0 ? '' : _webform_filter_xss(_webform_filter_values($string, $node, $submission, NULL, FALSE));
3102
}
3103

    
3104
/**
3105
 * Filter labels for display by running through XSS checks.
3106
 */
3107
function _webform_filter_xss($string) {
3108
  static $allowed_tags;
3109
  $allowed_tags = isset($allowed_tags) ? $allowed_tags : webform_variable_get('webform_allowed_tags');
3110
  return filter_xss($string, $allowed_tags);
3111
}
3112

    
3113

    
3114
/**
3115
 * Utility function to ensure that a webform record exists in the database.
3116
 *
3117
 * @param $node
3118
 *   The node object to check if a database entry exists.
3119
 * @return
3120
 *   This function should always return TRUE if no errors were encountered,
3121
 *   ensuring that a webform table row has been created. Will return FALSE if
3122
 *   a record does not exist and a new one could not be created.
3123
 */
3124
function webform_ensure_record(&$node) {
3125
  if (!$node->webform['record_exists']) {
3126
    // Even though webform_node_insert() would set this property to TRUE,
3127
    // we set record_exists to trigger a difference from the defaults.
3128
    $node->webform['record_exists'] = TRUE;
3129
    webform_node_insert($node);
3130
  }
3131
  return $node->webform['record_exists'];
3132
}
3133

    
3134
/**
3135
 * Utility function to check if a webform record is necessary in the database.
3136
 *
3137
 * If the node is no longer using any webform settings, this function will
3138
 * delete the settings from the webform table. Note that this function will NOT
3139
 * delete rows from the webform table if the node-type is exclusively used for
3140
 * webforms (per the "webform_node_types_primary" variable).
3141
 *
3142
 * @param $node
3143
 *   The node object to check if a database entry is still required.
3144
 * @return
3145
 *   Returns TRUE if the webform still has a record in the database. Returns
3146
 *   FALSE if the webform does not have a record or if the previously existing
3147
 *   record was just deleted.
3148
 */
3149
function webform_check_record(&$node) {
3150
  $webform = $node->webform;
3151
  $webform['record_exists'] = FALSE;
3152
  unset($webform['nid']);
3153

    
3154
  // Don't include empty values in the comparison, this makes it so modules that
3155
  // extend Webform with empty defaults won't affect cleanup of rows.
3156
  $webform = array_filter($webform);
3157
  $defaults = array_filter(webform_node_defaults());
3158
  if ($webform == $defaults && !in_array($node->type, webform_variable_get('webform_node_types_primary'))) {
3159
    webform_node_delete($node);
3160
    $node->webform = webform_node_defaults();
3161
  }
3162
  return $node->webform['record_exists'];
3163
}
3164

    
3165
/**
3166
 * Given a form_key and a list of form_key parents, determine the cid.
3167
 *
3168
 * @param $node
3169
 *   A fully loaded node object.
3170
 * @param $form_key
3171
 *   The form key for which we're finding a cid.
3172
 * @param $parent
3173
 *   The cid of the parent component.
3174
 */
3175
function webform_get_cid(&$node, $form_key, $pid) {
3176
  foreach ($node->webform['components'] as $cid => $component) {
3177
    if ($component['form_key'] == $form_key && $component['pid'] == $pid) {
3178
      return $cid;
3179
    }
3180
  }
3181
}
3182

    
3183
/**
3184
 * Retreive a Drupal variable with the appropriate default value.
3185
 */
3186
function webform_variable_get($variable) {
3187
  switch ($variable) {
3188
    case 'webform_allowed_tags':
3189
      $result = variable_get('webform_allowed_tags', array('a', 'em', 'strong', 'code', 'img'));
3190
      break;
3191
    case 'webform_default_from_name':
3192
      $result = variable_get('webform_default_from_name', variable_get('site_name', ''));
3193
      break;
3194
    case 'webform_default_from_address':
3195
      $result = variable_get('webform_default_from_address', variable_get('site_mail', ini_get('sendmail_from')));
3196
      break;
3197
    case 'webform_default_subject':
3198
      $result = variable_get('webform_default_subject', t('Form submission from: %title'));
3199
      break;
3200
    case 'webform_node_types':
3201
      $result = variable_get('webform_node_types', array('webform'));
3202
      break;
3203
    case 'webform_node_types_primary':
3204
      $result = variable_get('webform_node_types_primary', array('webform'));
3205
      break;
3206
  }
3207
  return $result;
3208
}
3209

    
3210
function theme_webform_token_help($variables) {
3211
  $groups = $variables['groups'];
3212
  $groups = empty($groups) ? array('basic', 'node', 'special') : $groups;
3213

    
3214
  static $tokens = array();
3215

    
3216
  if (empty($tokens)) {
3217
    $tokens['basic'] = array(
3218
      'title' => t('Basic tokens'),
3219
      'tokens' => array(
3220
        '%username' => t('The name of the user if logged in. Blank for anonymous users.'),
3221
        '%useremail' => t('The e-mail address of the user if logged in. Blank for anonymous users.'),
3222
        '%ip_address' => t('The IP address of the user.'),
3223
        '%site' => t('The name of the site (i.e. %site_name)', array('%site_name' => variable_get('site_name', ''))),
3224
        '%date' => t('The current date, formatted according to the site settings.'),
3225
      ),
3226
    );
3227

    
3228
    $tokens['node'] = array(
3229
      'title' => t('Node tokens'),
3230
      'tokens' => array(
3231
        '%nid' => t('The node ID.'),
3232
        '%title' => t('The node title.'),
3233
      ),
3234
    );
3235

    
3236
    $tokens['special'] = array(
3237
      'title' => t('Special tokens'),
3238
      'tokens' => array(
3239
        '%profile[' . t('key') . ']' => t('Any user profile field or value, such as %profile[name] or %profile[profile_first_name]'),
3240
        '%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".'),
3241
        '%post[' . t('key') . ']' => t('Tokens may also be populated from POST values that are submitted by forms.'),
3242
      ),
3243
      '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].'),
3244
    );
3245

    
3246
    $tokens['email'] = array(
3247
      'title' => t('E-mail tokens'),
3248
      'tokens' => array(
3249
        '%email_values' => t('All included components in a hierarchical structure.'),
3250
        '%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.'),
3251
        '%submission_url' => t('The URL for viewing the completed submission.'),
3252
      ),
3253
    );
3254

    
3255
    $tokens['submission'] = array(
3256
      'title' => t('Submission tokens'),
3257
      'tokens' => array(
3258
        '%sid' => t('The unique submission ID.'),
3259
        '%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.'),
3260
      ),
3261
    );
3262
  }
3263

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

    
3267
  foreach ($tokens as $group_name => $group) {
3268
    if (!is_array($groups) || in_array($group_name, $groups)) {
3269
      $items = array();
3270
      foreach ($group['tokens'] as $token => $token_description) {
3271
        $items[] = $token . ' - ' . $token_description;
3272
      }
3273
      $output .= theme('item_list', array('items' => $items, 'title' => $group['title']));
3274
      $output .= isset($group['description']) ? '<p>' . $group['description']  . '</p>' : '';
3275
    }
3276
  }
3277

    
3278
  $fieldset = array(
3279
    '#title' => t('Token values'),
3280
    '#type' => 'fieldset',
3281
    '#collapsible' => TRUE,
3282
    '#collapsed' => TRUE,
3283
    '#children' => '<div>' . $output . '</div>',
3284
    '#attributes' => array('class' => array('collapsible', 'collapsed')),
3285
  );
3286
  return theme('fieldset', array('element' => $fieldset));
3287
}
3288

    
3289
function _webform_safe_name($name) {
3290
  $new = trim($name);
3291

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

    
3304
  $new = drupal_strtolower($new);
3305
  $new = preg_replace('/[^a-z0-9_]/', '', $new);
3306
  return $new;
3307
}
3308

    
3309
/**
3310
 * Given an email address and a name, format an e-mail address.
3311
 *
3312
 * @param $address
3313
 *   The e-mail address.
3314
 * @param $name
3315
 *   The name to be used in the formatted address.
3316
 * @param $node
3317
 *   The webform node if replacements will be done.
3318
 * @param $submission
3319
 *   The webform submission values if replacements will be done.
3320
 * @param $encode
3321
 *   Encode the text for use in an e-mail.
3322
 * @param $single
3323
 *   Force a single value to be returned, even if a component expands to
3324
 *   multiple addresses. This is useful to ensure a single e-mail will be
3325
 *   returned for the "From" address.
3326
 * @param $format
3327
 *   The e-mail format, defaults to the site-wide setting. May be either "short"
3328
 *   or "long".
3329
 */
3330
function webform_format_email_address($address, $name, $node = NULL, $submission = NULL, $encode = TRUE, $single = TRUE, $format = NULL) {
3331
  if (!isset($format)) {
3332
    $format = variable_get('webform_email_address_format', 'long');
3333
  }
3334

    
3335
  if ($name == 'default') {
3336
    $name = webform_variable_get('webform_default_from_name');
3337
  }
3338
  elseif (is_numeric($name) && isset($node->webform['components'][$name])) {
3339
    if (isset($submission->data[$name]['value'])) {
3340
      $name = $submission->data[$name]['value'];
3341
    }
3342
    else {
3343
      $name = t('Value of !component', array('!component' => $node->webform['components'][$name]['name']));
3344
    }
3345
  }
3346

    
3347
  if ($address == 'default') {
3348
    $address = webform_variable_get('webform_default_from_address');
3349
  }
3350
  elseif (is_numeric($address) && isset($node->webform['components'][$address])) {
3351
    if (isset($submission->data[$address]['value'])) {
3352
      $values = $submission->data[$address]['value'];;
3353
      $address = array();
3354
      foreach ($values as $value) {
3355
        $address = array_merge($address, explode(',', $value));
3356
      }
3357
    }
3358
    else {
3359
      $address = t('Value of "!component"', array('!component' => $node->webform['components'][$address]['name']));
3360
    }
3361
  }
3362

    
3363
  // Convert arrays into a single value for From values.
3364
  if ($single) {
3365
    $address = is_array($address) ? reset($address) : $address;
3366
    $name = is_array($name) ? reset($name) : $name;
3367
  }
3368

    
3369
  // Address may be an array if a component value was used on checkboxes.
3370
  if (is_array($address)) {
3371
    foreach ($address as $key => $individual_address) {
3372
      $address[$key] = _webform_filter_values($individual_address, $node, $submission, NULL, FALSE, TRUE);
3373
    }
3374
  }
3375
  else {
3376
    $address = _webform_filter_values($address, $node, $submission, NULL, FALSE, TRUE);
3377
  }
3378

    
3379
  if ($format == 'long' && !empty($name)) {
3380
    $name = _webform_filter_values($name, $node, $submission, NULL, FALSE, TRUE);
3381
    if ($encode) {
3382
      $name = mime_header_encode($name);
3383
    }
3384
    $name = trim($name);
3385
    return '"' . $name . '" <' . $address . '>';
3386
  }
3387
  else {
3388
    return $address;
3389
  }
3390
}
3391

    
3392
/**
3393
 * Given an email subject, format it with any needed replacements.
3394
 */
3395
function webform_format_email_subject($subject, $node = NULL, $submission = NULL) {
3396
  if ($subject == 'default') {
3397
    $subject = webform_variable_get('webform_default_subject');
3398
  }
3399
  elseif (is_numeric($subject) && isset($node->webform['components'][$subject])) {
3400
    $component = $node->webform['components'][$subject];
3401
    if (isset($submission->data[$subject]['value'])) {
3402
      $display_function = '_webform_display_' . $component['type'];
3403
      $value = $submission->data[$subject]['value'];
3404

    
3405
      // Convert the value to a clean text representation if possible.
3406
      if (function_exists($display_function)) {
3407
        $display = $display_function($component, $value, 'text');
3408
        $display['#theme_wrappers'] = array();
3409
        $display['#webform_component'] = $component;
3410
        $subject = str_replace("\n", ' ', drupal_render($display));
3411
      }
3412
      else {
3413
        $subject = $value;
3414
      }
3415
    }
3416
    else {
3417
      $subject = t('Value of "!component"', array('!component' => $component['name']));
3418
    }
3419
  }
3420

    
3421
  // Convert arrays to strings (may happen if checkboxes are used as the value).
3422
  if (is_array($subject)) {
3423
    $subject = reset($subject);
3424
  }
3425

    
3426
  return _webform_filter_values($subject, $node, $submission, NULL, FALSE, TRUE);
3427
}
3428

    
3429
/**
3430
 * Convert an array of components into a tree
3431
 */
3432
function _webform_components_tree_build($src, &$tree, $parent, &$page_count) {
3433
  foreach ($src as $cid => $component) {
3434
    if ($component['pid'] == $parent) {
3435
      _webform_components_tree_build($src, $component, $cid, $page_count);
3436
      if ($component['type'] == 'pagebreak') {
3437
        $page_count++;
3438
      }
3439
      $tree['children'][$cid] = $component;
3440
      $tree['children'][$cid]['page_num'] = $page_count;
3441
    }
3442
  }
3443
  return $tree;
3444
}
3445

    
3446
/**
3447
 * Flatten a component tree into a flat list.
3448
 */
3449
function _webform_components_tree_flatten($tree) {
3450
  $components = array();
3451
  foreach ($tree as $cid => $component) {
3452
    if (isset($component['children'])) {
3453
      unset($component['children']);
3454
      $components[$cid] = $component;
3455
      // array_merge() can't be used here because the keys are numeric.
3456
      $children = _webform_components_tree_flatten($tree[$cid]['children']);
3457
      foreach ($children as $ccid => $ccomponent) {
3458
        $components[$ccid] = $ccomponent;
3459
      }
3460
    }
3461
    else {
3462
      $components[$cid] = $component;
3463
    }
3464
  }
3465
  return $components;
3466
}
3467

    
3468
/**
3469
 * Helper for the uasort in webform_tree_sort()
3470
 */
3471
function _webform_components_sort($a, $b) {
3472
  if ($a['weight'] == $b['weight']) {
3473
    return strcasecmp($a['name'], $b['name']);
3474
  }
3475
  return ($a['weight'] < $b['weight']) ? -1 : 1;
3476
}
3477

    
3478
/**
3479
 * Sort each level of a component tree by weight and name
3480
 */
3481
function _webform_components_tree_sort($tree) {
3482
  if (isset($tree['children']) && is_array($tree['children'])) {
3483
    $children = array();
3484
    uasort($tree['children'], '_webform_components_sort');
3485
    foreach ($tree['children'] as $cid => $component) {
3486
      $children[$cid] = _webform_components_tree_sort($component);
3487
    }
3488
    $tree['children'] = $children;
3489
  }
3490
  return $tree;
3491
}
3492

    
3493
/**
3494
 * Get a list of all available component definitions.
3495
 */
3496
function webform_components($include_disabled = FALSE, $reset = FALSE) {
3497
  static $components, $disabled;
3498

    
3499
  if (!isset($components) || $reset) {
3500
    $components = array();
3501
    $disabled = array_flip(variable_get('webform_disabled_components', array()));
3502
    foreach (module_implements('webform_component_info') as $module) {
3503
      $module_components = module_invoke($module, 'webform_component_info');
3504
      foreach ($module_components as $type => $info) {
3505
        $module_components[$type]['module'] = $module;
3506
        $module_components[$type]['enabled'] = !array_key_exists($type, $disabled);
3507
      }
3508
      $components += $module_components;
3509
    }
3510
    drupal_alter('webform_component_info', $components);
3511
    ksort($components);
3512
  }
3513

    
3514
  return $include_disabled ? $components : array_diff_key($components, $disabled);
3515
}
3516

    
3517
/**
3518
 * Build a list of components suitable for use as select list options.
3519
 */
3520
function webform_component_options($include_disabled = FALSE) {
3521
  $component_info = webform_components($include_disabled);
3522
  $options = array();
3523
  foreach ($component_info as $type => $info) {
3524
    $options[$type] = $info['label'];
3525
  }
3526
  return $options;
3527
}
3528

    
3529
/**
3530
 * Load a component file into memory.
3531
 *
3532
 * @param $component_type
3533
 *   The string machine name of a component.
3534
 */
3535
function webform_component_include($component_type) {
3536
  static $included = array();
3537

    
3538
  // No need to load components that have already been added once.
3539
  if (!isset($included[$component_type])) {
3540
    $components = webform_components(TRUE);
3541
    $included[$component_type] = TRUE;
3542

    
3543
    if (($info = $components[$component_type]) && isset($info['file'])) {
3544
      $pathinfo = pathinfo($info['file']);
3545
      $basename = basename($pathinfo['basename'], '.' . $pathinfo['extension']);
3546
      $path = (!empty($pathinfo['dirname']) ? $pathinfo['dirname'] . '/' : '') . $basename;
3547
      module_load_include($pathinfo['extension'], $info['module'], $path);
3548
    }
3549
  }
3550
}
3551

    
3552
/**
3553
 * Invoke a component callback.
3554
 *
3555
 * @param $type
3556
 *   The component type as a string.
3557
 * @param $callback
3558
 *   The callback to execute.
3559
 * @param ...
3560
 *   Any additional parameters required by the $callback.
3561
 */
3562
function webform_component_invoke($type, $callback) {
3563
  $args = func_get_args();
3564
  $type = array_shift($args);
3565
  $callback = array_shift($args);
3566
  $function = '_webform_' . $callback . '_' . $type;
3567
  webform_component_include($type);
3568
  if (function_exists($function)) {
3569
    return call_user_func_array($function, $args);
3570
  }
3571
}
3572

    
3573
/**
3574
 * Check if a component implements a particular hook.
3575
 *
3576
 * @param $type
3577
 *   The component type as a string.
3578
 * @param $callback
3579
 *   The callback to check.
3580
 */
3581
function webform_component_implements($type, $callback) {
3582
  $function = '_webform_' . $callback . '_' . $type;
3583
  webform_component_include($type);
3584
  return function_exists($function);
3585
}
3586

    
3587
/**
3588
 * Disable the Drupal page cache.
3589
 */
3590
function webform_disable_page_cache() {
3591
  drupal_page_is_cacheable(FALSE);
3592
}
3593

    
3594
/**
3595
 * Set the necessary breadcrumb for the page we are on.
3596
 *
3597
 * @param object $node
3598
 *   The loaded webform node.
3599
 * @param boolean|object $submission
3600
 *   The submission if the current page is viewing or dealing with a submission,
3601
 *   or TRUE to just include the webform node in the breadcrumbs (used for
3602
 *   the submission completion confirmation page), or NULL for no extra
3603
 *   processing
3604
 */
3605
function webform_set_breadcrumb($node, $submission = NULL) {
3606
  $node_path = "node/{$node->nid}";
3607

    
3608
  // Set the href of the current menu item to be the node's path. This has two
3609
  // effects. The active trail will be to the node's prefered menu tree location,
3610
  // expanding the menu as appropriate. And the breadcrumbs will be set as if
3611
  // the current page were under the node's preferred location.
3612
  // Note that menu_tree_set_path() could be used to set the path for the menu,
3613
  // but it will not affect the breadcrumbs when the webform is not in the
3614
  // default menu.
3615
  menu_set_item(NULL, array('href' => $node_path) + menu_get_item());
3616

    
3617
  if ($submission) {
3618
    $breadcrumb = menu_get_active_breadcrumb();
3619

    
3620
    // Append the node title (or its menu name), in case it isn't in the path already.
3621
    $active_trail = menu_get_active_trail();
3622
    $last_active = end($active_trail);
3623
    $breadcrumb[] = $last_active['href'] === $node_path && !empty($last_active['in_active_trail'])
3624
                      ? l($last_active['title'], $node_path, $last_active['localized_options'])
3625
                      : l($node->title, $node_path);
3626

    
3627
    // Setting the current menu href will cause the submission title and current
3628
    // tab (if not the default tab) to be added to the active path when the
3629
    // webform is in the default location in the menu (node/NID). The title
3630
    // is desirable, but the tab name (e.g. Edit or Delete) isn't.
3631
    if (preg_match('/href=".*"/', end($breadcrumb), $matches)) {
3632
      foreach ($breadcrumb as $index => $link) {
3633
        if (stripos($link, $matches[0]) !== FALSE) {
3634
          $breadcrumb = array_slice($breadcrumb, 0, $index + 1);
3635
          break;
3636
        }
3637
      }
3638
    }
3639

    
3640
    // If the user is dealing with a submission, then the breadcrumb should
3641
    // be fudged to allow them to return to a likely list of webforms.
3642
    // Note that this isn't necessarily where they came from, but it's the
3643
    // best guess available.
3644
    if (is_object($submission)) {
3645
      if (webform_results_access($node)) {
3646
        $breadcrumb[] = l(t('Webform results'), $node_path . '/webform-results');
3647
      }
3648
      elseif (user_access('access own webform results')) {
3649
        $breadcrumb[] = l(t('Submissions'), $node_path . '/submissions');
3650
      }
3651
    }
3652

    
3653
    drupal_set_breadcrumb($breadcrumb);
3654
  }
3655
}
3656

    
3657
/**
3658
 * Convert an ISO 8601 date or time into an array.
3659
 *
3660
 * This converts full format dates or times. Either a date or time may be
3661
 * provided, in which case only those portions will be returned. Dashes and
3662
 * colons must be used, never implied.
3663
 *
3664
 * Formats:
3665
 * Dates: YYYY-MM-DD
3666
 * Times: HH:MM:SS
3667
 * Datetimes: YYYY-MM-DDTHH:MM:SS
3668
 *
3669
 * @param $string
3670
 *   An ISO 8601 date, time, or datetime.
3671
 * @param $type
3672
 *   If wanting only specific fields back, specify either "date" or "time".
3673
 *   Leaving empty will return an array with both date and time keys, even if
3674
 *   some are empty. Returns an array with the following keys:
3675
 *   - year
3676
 *   - month
3677
 *   - day
3678
 *   - hour (in 24hr notation)
3679
 *   - minute
3680
 *   - second
3681
 */
3682
function webform_date_array($string, $type = NULL) {
3683
  $pattern = '/((\d{4}?)-(\d{2}?)-(\d{2}?))?(T?(\d{2}?):(\d{2}?):(\d{2}?))?/';
3684
  $matches = array();
3685
  preg_match($pattern, $string, $matches);
3686
  $matches += array_fill(0, 9, '');
3687

    
3688
  $return = array();
3689

    
3690
  // Check for a date string.
3691
  if ($type == 'date' || !isset($type)) {
3692
    $return['year'] = $matches[2] !== '' ? (int) $matches[2] : '';
3693
    $return['month'] = $matches[3] !== '' ? (int) $matches[3] : '';
3694
    $return['day'] = $matches[4] !== '' ? (int) $matches[4] : '';
3695
  }
3696

    
3697
  // Check for a time string.
3698
  if ($type == 'time' || !isset($type)) {
3699
    $return['hour'] = $matches[6] !== '' ? (int) $matches[6] : '';
3700
    $return['minute'] = $matches[7] !== '' ? (int) $matches[7] : '';
3701
    $return['second'] = $matches[8] !== '' ? (int) $matches[8] : '';
3702
  }
3703

    
3704
  return $return;
3705
}
3706

    
3707
/**
3708
 * Convert an array of a date or time into an ISO 8601 compatible string.
3709
 *
3710
 * @param $array
3711
 *   The array to convert to a date or time string.
3712
 * @param $type
3713
 *   If wanting a specific string format back specify either "date" or "time".
3714
 *   Otherwise a full ISO 8601 date and time string will be returned.
3715
 */
3716
function webform_date_string($array, $type = NULL) {
3717
  $string = '';
3718

    
3719
  if ($type == 'date' || !isset($type)) {
3720
    $string .= empty($array['year']) ? '0000' : sprintf('%04d', $array['year']);
3721
    $string .= '-';
3722
    $string .= empty($array['month']) ? '00' : sprintf('%02d', $array['month']);
3723
    $string .= '-';
3724
    $string .= empty($array['day']) ? '00' : sprintf('%02d', $array['day']);
3725
  }
3726

    
3727
  if (!isset($type)) {
3728
    $string .= 'T';
3729
  }
3730

    
3731
  if ($type == 'time' || !isset($type)) {
3732
    $string .= empty($array['hour']) ? '00' :  sprintf('%02d', $array['hour']);
3733
    $string .= ':';
3734
    $string .= empty($array['minute']) ? '00' :  sprintf('%02d', $array['minute']);
3735
    $string .= ':';
3736
    $string .= empty($array['second']) ? '00' :  sprintf('%02d', $array['second']);
3737
  }
3738

    
3739
  return $string;
3740
}
3741

    
3742
/**
3743
 * Get a date format according to the site settings.
3744
 *
3745
 * @param $size
3746
 *   A choice of 'short', 'medium', or 'long' date formats.
3747
 */
3748
function webform_date_format($size = 'medium') {
3749
    // Format date according to site's given format.
3750
    $format = variable_get('date_format_' . $size, 'D, m/d/Y - H:i');
3751
    $time = 'aABgGhHisueIOPTZ';
3752
    $day_of_week = 'Dlw';
3753
    $special = ',-: ';
3754
    $date_format = trim($format, $time . $day_of_week . $special);
3755

    
3756
    // Ensure that a day, month, and year value are present. Use a default
3757
    // format if all the values are not found.
3758
    if (!preg_match('/[dj]/', $date_format) || !preg_match('/[FmMn]/', $date_format) || !preg_match('/[oYy]/', $date_format)) {
3759
      $date_format = 'm/d/Y';
3760
    }
3761

    
3762
    return $date_format;
3763
}
3764

    
3765
/**
3766
 * Return a date in the desired format taking into consideration user timezones.
3767
 */
3768
function webform_strtodate($format, $string, $timezone_name = NULL) {
3769
  global $user;
3770

    
3771
  // Adjust the time based on the user or site timezone.
3772
  if (variable_get('configurable_timezones', 1) && $timezone_name == 'user' && $user->uid) {
3773
    $timezone_name = isset($GLOBALS['user']->timezone) ? $GLOBALS['user']->timezone : 'UTC';
3774
  }
3775
  // If the timezone is still empty or not set, use the site timezone.
3776
  if (empty($timezone_name) || $timezone_name == 'user') {
3777
    $timezone_name = variable_get('date_default_timezone', 'UTC');
3778
  }
3779

    
3780
  if (!empty($timezone_name) && class_exists('DateTimeZone')) {
3781
    // Suppress errors if encountered during string conversion. Exceptions are
3782
    // only supported for DateTime in PHP 5.3 and higher.
3783
    try {
3784
      @$timezone = new DateTimeZone($timezone_name);
3785
      @$datetime = new DateTime($string, $timezone);
3786
      return @$datetime->format($format);
3787
    }
3788
    catch (Exception $e) {
3789
      return '';
3790
    }
3791
  }
3792
  else {
3793
    return date($format, strtotime($string));
3794
  }
3795
}
3796

    
3797
/**
3798
 * Get a timestamp in GMT time, ensuring timezone accuracy.
3799
 */
3800
function webform_strtotime($date) {
3801
  $current_tz = date_default_timezone_get();
3802
  date_default_timezone_set('UTC');
3803
  $timestamp = strtotime($date);
3804
  date_default_timezone_set($current_tz);
3805
  return $timestamp;
3806
}
3807

    
3808
/**
3809
 * Wrapper function for i18n_string() if i18nstrings enabled.
3810
 */
3811
function webform_tt($name, $string, $langcode = NULL, $update = FALSE) {
3812
  if (function_exists('i18n_string')) {
3813
    $options = array(
3814
      'langcode' => $langcode,
3815
      'update' => $update,
3816
    );
3817
    return i18n_string($name, $string, $options);
3818
  }
3819
  else {
3820
    return $string;
3821
  }
3822
}
3823

    
3824
/**
3825
 * Check if any available HTML mail handlers are available for Webform to use.
3826
 */
3827
function webform_email_html_capable() {
3828
  // TODO: Right now we only support MIME Mail and HTML Mail. Support others
3829
  // if available through a hook?
3830
  $supported_html_modules = array(
3831
    'mimemail' => 'MimeMailSystem',
3832
    'htmlmail' => 'HTMLMailSystem',
3833
  );
3834
  foreach ($supported_html_modules as $mail_module => $mail_system_name) {
3835
    if (module_exists($mail_module)) {
3836
      $mail_systems = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
3837
      if (isset($mail_systems['webform'])) {
3838
        $enable = strpos($mail_systems['webform'], $mail_system_name) !== FALSE ? $mail_systems['webform'] : FALSE;
3839
      }
3840
      else {
3841
        $enable = $mail_system_name;
3842
      }
3843
    }
3844
  }
3845
  if (!empty($enable)) {
3846
    // We assume that if a solution exists even if it's not specified we should
3847
    // use it. Webform will specify if e-mails sent with the system are plain-
3848
    // text or not when sending each e-mail.
3849
    $GLOBALS['conf']['mail_system']['webform'] = $enable;
3850
    return TRUE;
3851
  }
3852
  return FALSE;
3853
}
3854

    
3855
/**
3856
 * Implements hook_views_api().
3857
 */
3858
function webform_views_api() {
3859
  return array(
3860
    'api' => 2.0,
3861
    'path' => drupal_get_path('module', 'webform') . '/views',
3862
  );
3863
}
3864

    
3865
/**
3866
 * Implements hook_field_extra_fields().
3867
 */
3868
function webform_field_extra_fields() {
3869
  $extra = array();
3870
  foreach (webform_variable_get('webform_node_types') as $type) {
3871
    $extra['node'][$type]['display']['webform'] = array(
3872
      'label' => t('Webform'),
3873
      'description' => t('Webform client form.'),
3874
      'weight' => 10,
3875
    );
3876
  }
3877
  return $extra;
3878
}
3879

    
3880
/**
3881
 * Implements hook_mollom_form_list().
3882
 */
3883
function webform_mollom_form_list() {
3884
  $forms = array();
3885
  $webform_types = webform_variable_get('webform_node_types');
3886
  if (empty($webform_types)) {
3887
    return $forms;
3888
  }
3889

    
3890
  $query = db_select('webform', 'w');
3891
  $query->innerJoin('node', 'n', 'n.nid = w.nid');
3892
  $query->fields('n', array('nid', 'title'));
3893
  $query->condition('n.type', $webform_types, 'IN');
3894
  $result = $query->execute();
3895

    
3896
  foreach ($result as $node) {
3897
    $form_id = 'webform_client_form_' . $node->nid;
3898
    $forms[$form_id] = array(
3899
      'title' => t('@name form', array('@name' => $node->title)),
3900
      'entity' => 'webform',
3901
      'delete form' => 'webform_submission_delete_form',
3902
    );
3903
  }
3904
  return $forms;
3905
}
3906

    
3907
/**
3908
 * Implements hook_mollom_form_info().
3909
 */
3910
function webform_mollom_form_info($form_id) {
3911
  module_load_include('inc', 'webform', 'includes/webform.components');
3912

    
3913
  $nid = drupal_substr($form_id, 20);
3914
  $node = node_load($nid);
3915
  $form_info = array(
3916
    'title' => t('@name form', array('@name' => $node->title)),
3917
    'mode' => MOLLOM_MODE_ANALYSIS,
3918
    'bypass access' => array('edit all webform submissions', 'edit any webform content'),
3919
    'entity' => 'webform',
3920
    'elements' => array(),
3921
    'mapping' => array(
3922
      'post_id' => 'details][sid',
3923
      'author_id' => 'details][uid',
3924
    ),
3925
  );
3926
  // Add components as elements.
3927
  // These components can be enabled for textual analysis (when not using a
3928
  // CAPTCHA-only protection) in Mollom's form configuration.
3929
  foreach ($node->webform['components'] as $cid => $component) {
3930
    if (webform_component_feature($component['type'], 'spam_analysis')) {
3931
      $parents = implode('][', webform_component_parent_keys($node, $component));
3932
      $form_info['elements']['submitted][' . $parents] = check_plain(t($component['name']));
3933
    }
3934
  }
3935
  // Assign field mappings based on webform configuration.
3936
  // Since multiple emails can be configured, we iterate over all and take
3937
  // over the assigned component for the field mapping in any email, unless
3938
  // we already assigned one. We are not interested in administratively
3939
  // configured static strings, only user-submitted values.
3940
  foreach ($node->webform['emails'] as $email) {
3941
    // Subject (post_title).
3942
    if (!isset($form_info['mapping']['post_title'])) {
3943
      $cid = $email['subject'];
3944
      if (is_numeric($cid)) {
3945
        $parents = implode('][', webform_component_parent_keys($node, $node->webform['components'][$cid]));
3946
        $form_info['mapping']['post_title'] = 'submitted][' . $parents;
3947
      }
3948
    }
3949
    // From name (author_name).
3950
    if (!isset($form_info['mapping']['author_name'])) {
3951
      $cid = $email['from_name'];
3952
      if (is_numeric($cid)) {
3953
        $parents = implode('][', webform_component_parent_keys($node, $node->webform['components'][$cid]));
3954
        $form_info['mapping']['author_name'] = 'submitted][' . $parents;
3955
      }
3956
    }
3957
    // From address (author_mail).
3958
    if (!isset($form_info['mapping']['author_mail'])) {
3959
      $cid = $email['from_address'];
3960
      if (is_numeric($cid)) {
3961
        $parents = implode('][', webform_component_parent_keys($node, $node->webform['components'][$cid]));
3962
        $form_info['mapping']['author_mail'] = 'submitted][' . $parents;
3963
      }
3964
    }
3965
  }
3966

    
3967
  return $form_info;
3968
}