Projet

Général

Profil

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

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

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
  // View mode of 'form' is exempted to allow blocks and views to force display.
1439
  $extra_fields = field_extra_fields_get_display('node', $node->type, $view_mode);
1440
  if ($view_mode != 'form' && empty($extra_fields['webform']['visible'])) {
1441
    return;
1442
  }
1443

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1621
  $type = 'status';
1622

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1754

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

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

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

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

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

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

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

    
1821
  return $form;
1822
}
1823

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2031
  return $form;
2032
}
2033

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

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

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

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

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

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

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

    
2103
  return $show_component;
2104
}
2105

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2542

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

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

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

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

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

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

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

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

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

    
2638
  return $values;
2639
}
2640

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2767
  return $output;
2768
}
2769

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

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

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

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

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

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

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

    
2823
  return $output;
2824
}
2825

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

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

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

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

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

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

    
2865
  return $output;
2866
}
2867

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3114

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

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

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

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

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

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

    
3215
  static $tokens = array();
3216

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3689
  $return = array();
3690

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

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

    
3705
  return $return;
3706
}
3707

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

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

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

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

    
3740
  return $string;
3741
}
3742

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

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

    
3763
    return $date_format;
3764
}
3765

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3968
  return $form_info;
3969
}