Projet

Général

Profil

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

root / drupal7 / sites / all / modules / webform / webform.api.php @ 8c72e82a

1
<?php
2

    
3
/**
4
 * @file
5
 * Sample hooks demonstrating usage in Webform.
6
 */
7

    
8
/**
9
 * @defgroup webform_hooks Webform Module Hooks
10
 * @{
11
 * Webform's hooks enable other modules to intercept events within Webform, such
12
 * as the completion of a submission or adding validation. Webform's hooks also
13
 * allow other modules to provide additional components for use within forms.
14
 */
15

    
16
/**
17
 * Define callbacks that can be used as select list options.
18
 *
19
 * When users create a select component, they may select a pre-built list of
20
 * certain options. Webform core provides a few of these lists such as the
21
 * United States, countries of the world, and days of the week. This hook
22
 * provides additional lists that may be utilized.
23
 *
24
 * @see webform_options_example()
25
 * @see hook_webform_select_options_info_alter()
26
 *
27
 * @return array
28
 *   An array of callbacks that can be used for select list options. This array
29
 *   should be keyed by the "name" of the pre-defined list. The values should
30
 *   be an array with the following additional keys:
31
 *     - title: The translated title for this list.
32
 *     - options callback: The name of a function implementing
33
 *       callback_webform_options() that will return the list.
34
 *     - options arguments: Any additional arguments to send to the callback.
35
 *     - file: Optional. The file containing the options callback, relative to
36
 *       the module root.
37
 */
38
function hook_webform_select_options_info() {
39
  $items = array();
40

    
41
  $items['days'] = array(
42
    'title' => t('Days of the week'),
43
    'options callback' => 'webform_options_days',
44
    'file' => 'includes/webform.options.inc',
45
  );
46

    
47
  return $items;
48
}
49

    
50
/**
51
 * Alter the list of select list options provided by Webform and other modules.
52
 *
53
 * @see hook_webform_select_options_info()
54
 */
55
function hook_webform_select_options_info_alter(&$items) {
56
  // Remove the days of the week options.
57
  unset($items['days']);
58
}
59

    
60
/**
61
 * Define a list of options that Webform may use in a select component.
62
 *
63
 * Callback for hook_webform_select_options_info().
64
 *
65
 * @param $component
66
 *   The Webform component array for the select component being displayed.
67
 * @param $flat
68
 *   Boolean value indicating whether the returned list needs to be a flat array
69
 *   of key => value pairs. Select components support up to one level of
70
 *   nesting, but when results are displayed, the list needs to be returned
71
 *   without the nesting.
72
 * @param $arguments
73
 *   The "options arguments" specified in hook_webform_select_options_info().
74
 *
75
 * @return array
76
 *   An array of key => value pairs suitable for a select list's #options
77
 *   FormAPI property.
78
 */
79
function callback_webform_options($component, $flat, $arguments) {
80
  $options = array(
81
    'one' => t('Pre-built option one'),
82
    'two' => t('Pre-built option two'),
83
    'three' => t('Pre-built option three'),
84
  );
85

    
86
  return $options;
87
}
88

    
89
/**
90
 * Respond to the loading of Webform submissions.
91
 *
92
 * @param $submissions
93
 *   An array of Webform submissions that are being loaded, keyed by the
94
 *   submission ID. Modifications to the submissions are done by reference.
95
 */
96
function hook_webform_submission_load(&$submissions) {
97
  foreach ($submissions as $sid => $submission) {
98
    $submissions[$sid]->new_property = 'foo';
99
  }
100
}
101

    
102
/**
103
 * Respond to the creation of a new submission from form values.
104
 *
105
 * This hook is called when a user has completed a submission to initialize the
106
 * submission object. After this object has its values populated, it will be
107
 * saved by webform_submission_insert(). Note that this hook is only called for
108
 * new submissions, not for submissions being edited. If responding to the
109
 * saving of all submissions, it's recommended to use
110
 * hook_webform_submission_presave().
111
 *
112
 * @param $submission
113
 *   The submission object that has been created.
114
 * @param $node
115
 *   The Webform node for which this submission is being saved.
116
 * @param $account
117
 *   The user account that is creating the submission.
118
 * @param $form_state
119
 *   The contents of form state that is the basis for this submission.
120
 *
121
 * @see webform_submission_create()
122
 */
123
function hook_webform_submission_create_alter(&$submission, &$node, &$account, &$form_state) {
124
  $submission->new_property = TRUE;
125
}
126

    
127
/**
128
 * Modify a Webform submission, prior to saving it in the database.
129
 *
130
 * @param $node
131
 *   The Webform node on which this submission was made.
132
 * @param $submission
133
 *   The Webform submission that is about to be saved to the database.
134
 */
135
function hook_webform_submission_presave($node, &$submission) {
136
  // Update some component's value before it is saved.
137
  $component_id = 4;
138
  $submission->data[$component_id][0] = 'foo';
139
}
140

    
141
/**
142
 * Respond to a Webform submission being inserted.
143
 *
144
 * Note that this hook is called after a submission has already been saved to
145
 * the database. If needing to modify the submission prior to insertion, use
146
 * hook_webform_submission_presave().
147
 *
148
 * @param $node
149
 *   The Webform node on which this submission was made.
150
 * @param $submission
151
 *   The Webform submission that was just inserted into the database.
152
 */
153
function hook_webform_submission_insert($node, $submission) {
154
  // Insert a record into a 3rd-party module table when a submission is added.
155
  db_insert('mymodule_table')
156
    ->fields(array(
157
      'nid' => $node->nid,
158
      'sid' => $submission->sid,
159
      'foo' => 'foo_data',
160
    ))
161
    ->execute();
162
}
163

    
164
/**
165
 * Respond to a Webform submission being updated.
166
 *
167
 * Note that this hook is called after a submission has already been saved to
168
 * the database. If needing to modify the submission prior to updating, use
169
 * hook_webform_submission_presave().
170
 *
171
 * @param $node
172
 *   The Webform node on which this submission was made.
173
 * @param $submission
174
 *   The Webform submission that was just updated in the database.
175
 */
176
function hook_webform_submission_update($node, $submission) {
177
  // Update a record in a 3rd-party module table when a submission is updated.
178
  db_update('mymodule_table')
179
    ->fields(array(
180
      'foo' => 'foo_data',
181
    ))
182
    ->condition('nid', $node->nid)
183
    ->condition('sid', $submission->sid)
184
    ->execute();
185
}
186

    
187
/**
188
 * Respond to a Webform submission being deleted.
189
 *
190
 * @param $node
191
 *   The Webform node on which this submission was made.
192
 * @param $submission
193
 *   The Webform submission that was just deleted from the database.
194
 */
195
function hook_webform_submission_delete($node, $submission) {
196
  // Delete a record from a 3rd-party module table when a submission is deleted.
197
  db_delete('mymodule_table')
198
    ->condition('nid', $node->nid)
199
    ->condition('sid', $submission->sid)
200
    ->execute();
201
}
202

    
203
/**
204
 * Provide a list of actions that can be executed on a submission.
205
 *
206
 * Some actions are displayed in the list of submissions such as edit, view, and
207
 * delete. All other actions are displayed only when viewing the submission.
208
 * These additional actions may be specified in this hook. Examples included
209
 * directly in the Webform module include PDF, print, and resend e-mails. Other
210
 * modules may extend this list by using this hook.
211
 *
212
 * @param $node
213
 *   The Webform node on which this submission was made.
214
 * @param $submission
215
 *   The Webform submission on which the actions may be performed.
216
 *
217
 * @return array
218
 *   List of action.
219
 */
220
function hook_webform_submission_actions($node, $submission) {
221
  $actions= array();
222

    
223
  if (webform_results_access($node)) {
224
    $actions['myaction'] = array(
225
      'title' => t('Do my action'),
226
      'href' => 'node/' . $node->nid . '/submission/' . $submission->sid . '/myaction',
227
      'query' => drupal_get_destination(),
228
    );
229
  }
230

    
231
  return $actions;
232
}
233

    
234
/**
235
 * Modify the draft to be presented for editing.
236
 *
237
 * When drafts are enabled for the webform, by default, a pre-existig draft is
238
 * presented when the webform is displayed to that user. To allow multiple
239
 * drafts, implement this alter function to set the $sid to NULL, or use your
240
 * application's business logic to determine whether a new draft or which of
241
 * he pre-existing drafts should be presented.
242
 *
243
 * @param integer $sid
244
 *    The id of the most recent submission to be presented for editing. Change
245
 *    to a different draft's sid or set to NULL for a new draft.
246
 * @param array $context
247
 *    Array of context with indices 'nid' and 'uid'.
248
 */
249
function hook_webform_draft_alter(&$sid, $context) {
250
  if ($_GET['newdraft']) {
251
    $sid = NULL;
252
  }
253
}
254

    
255
/**
256
 * Alter the display of a Webform submission.
257
 *
258
 * This function applies to both e-mails sent by Webform and normal display of
259
 * submissions when viewing through the adminsitrative interface.
260
 *
261
 * @param $renderable
262
 *   The Webform submission in a renderable array, similar to FormAPI's
263
 *   structure. This variable must be passed in by-reference. Important
264
 *   properties of this array include #node, #submission, #email, and #format,
265
 *   which can be used to find the context of the submission that is being
266
 *   rendered.
267
 */
268
function hook_webform_submission_render_alter(&$renderable) {
269
  // Remove page breaks from sent e-mails.
270
  if (isset($renderable['#email'])) {
271
    foreach (element_children($renderable) as $key) {
272
      if ($renderable[$key]['#component']['type'] == 'pagebreak') {
273
        unset($renderable[$key]);
274
      }
275
    }
276
  }
277
}
278

    
279
/**
280
 * Modify a loaded Webform component.
281
 *
282
 * IMPORTANT: This hook does not actually exist because components are loaded
283
 * in bulk as part of webform_node_load(). Use hook_node_load() to modify loaded
284
 * components when the node is loaded. This example is provided merely to point
285
 * to hook_node_load().
286
 *
287
 * @see hook_nodeapi()
288
 * @see webform_node_load()
289
 */
290
function hook_webform_component_load() {
291
  // This hook does not exist. Instead use hook_node_load().
292
}
293

    
294
/**
295
 * Modify a Webform component before it is saved to the database.
296
 *
297
 * Note that most of the time this hook is not necessary, because Webform will
298
 * automatically add data to the component based on the component form. Using
299
 * hook_form_alter() will be sufficient in most cases.
300
 *
301
 * @see hook_form_alter()
302
 * @see webform_component_edit_form()
303
 *
304
 * @param $component
305
 *   The Webform component being saved.
306
 */
307
function hook_webform_component_presave(&$component) {
308
  $component['extra']['new_option'] = 'foo';
309
}
310

    
311
/**
312
 * Respond to a Webform component being inserted into the database.
313
 */
314
function hook_webform_component_insert($component) {
315
  // Insert a record into a 3rd-party module table when a component is inserted.
316
  db_insert('mymodule_table')
317
    ->fields(array(
318
      'nid' => $component['nid'],
319
      'cid' => $component['cid'],
320
      'foo' => 'foo_data',
321
    ))
322
    ->execute();
323
}
324

    
325
/**
326
 * Respond to a Webform component being updated in the database.
327
 */
328
function hook_webform_component_update($component) {
329
  // Update a record in a 3rd-party module table when a component is updated.
330
  db_update('mymodule_table')
331
    ->fields(array(
332
      'foo' => 'foo_data',
333
    ))
334
    ->condition('nid', $component['nid'])
335
    ->condition('cid', $component['cid'])
336
    ->execute();
337
}
338

    
339
/**
340
 * Respond to a Webform component being deleted.
341
 */
342
function hook_webform_component_delete($component) {
343
  // Delete a record in a 3rd-party module table when a component is deleted.
344
  db_delete('mymodule_table')
345
    ->condition('nid', $component['nid'])
346
    ->condition('cid', $component['cid'])
347
    ->execute();
348
}
349

    
350
/**
351
 * Alter the entire analysis before rendering to the page on the Analysis tab.
352
 *
353
 * This alter hook allows modification of the entire analysis of a node's
354
 * Webform results. The resulting analysis is displayed on the Results ->
355
 * Analysis tab on the Webform.
356
 *
357
 * @param array $analysis
358
 *   A Drupal renderable array, passed by reference, containing the entire
359
 *   contents of the analysis page. This typically will contain the following
360
 *   two major keys:
361
 *   - form: The form for configuring the shown analysis.
362
 *   - components: The list of analyses for each analysis-enabled component
363
 *     for the node. Each keyed by its component ID.
364
 */
365
function hook_webform_analysis_alter(&$analysis) {
366
  $node = $analysis['#node'];
367

    
368
  // Add an additional piece of information to every component's analysis:
369
  foreach (element_children($analysis['components']) as $cid) {
370
    $component = $node->components[$cid];
371
    $analysis['components'][$cid]['chart'] = array(
372
      '#markup' => t('Chart for the @name component', array('@name' => $component['name'])),
373
    );
374
  }
375
}
376
/**
377
 * Alter data when displaying an analysis on that component.
378
 *
379
 * This hook modifies the data from an individual component's analysis results.
380
 * It can be used to add additional analysis, or to modify the existing results.
381
 * If needing to alter the entire set of analyses rather than an individual
382
 * component, hook_webform_analysis_alter() may be used instead.
383
 *
384
 * @param array $data
385
 *   An array containing the result of a components analysis hook, passed by
386
 *   reference. This is passed directly from a component's
387
 *   _webform_analysis_component() function. See that hook for more information
388
 *   on this value.
389
 * @param object $node
390
 *   The node object that contains the component being analyzed.
391
 * @param array $component
392
 *   The Webform component array whose analysis results are being displayed.
393
 *
394
 * @see _webform_analysis_component()
395
 * @see hook_webform_analysis_alter()
396
 */
397
function hook_webform_analysis_component_data_alter(&$data, $node, $component) {
398
  if ($component['type'] === 'textfield') {
399
    // Do not display rows that contain a zero value.
400
    foreach ($data as $row_number => $row_data) {
401
      if ($row_data[1] === 0) {
402
        unset($data[$row_number]);
403
      }
404
    }
405
  }
406
}
407

    
408
/**
409
 * Alter a Webform submission's header when exported.
410
 */
411
function hook_webform_csv_header_alter(&$header, $component) {
412
  // Use the machine name for component headers, but only for the webform
413
  // with node 5 and components that are text fields.
414
  if ($component['nid'] == 5 && $component['type'] == 'textfield') {
415
    $header[2] = $component['form_key'];
416
  }
417
}
418

    
419
/**
420
 * Alter a Webform submission's data when exported.
421
 */
422
function hook_webform_csv_data_alter(&$data, $component, $submission) {
423
  // If a value of a field was left blank, use the value from another
424
  // field.
425
  if ($component['cid'] == 1 && empty($data)) {
426
    $data = $submission->data[2]['value'][0];
427
  }
428
}
429

    
430
/**
431
 * Define components to Webform.
432
 *
433
 * @return array
434
 *   An array of components, keyed by machine name. Required properties are
435
 *   "label" and "description". The "features" array defines which capabilities
436
 *   the component has, such as being displayed in e-mails or csv downloads.
437
 *   A component like "markup" for example would not show in these locations.
438
 *   The possible features of a component include:
439
 *
440
 *     - csv
441
 *     - email
442
 *     - email_address
443
 *     - email_name
444
 *     - required
445
 *     - conditional
446
 *     - spam_analysis
447
 *     - group
448
 *
449
 *   Note that most of these features do not indicate the default state, but
450
 *   determine if the component can have this property at all. Setting
451
 *   "required" to TRUE does not mean that a component's fields will always be
452
 *   required, but instead give the option to the administrator to choose the
453
 *   requiredness. See the example implementation for details on how these
454
 *   features may be set.
455
 *
456
 *   An optional "file" may be specified to be loaded when the component is
457
 *   needed. A set of callbacks will be established based on the name of the
458
 *   component. All components follow the pattern:
459
 *
460
 *   _webform_[callback]_[component]
461
 *
462
 *   Where [component] is the name of the key of the component and [callback] is
463
 *   any of the following:
464
 *
465
 *     - defaults
466
 *     - edit
467
 *     - render
468
 *     - display
469
 *     - submit
470
 *     - delete
471
 *     - help
472
 *     - theme
473
 *     - analysis
474
 *     - table
475
 *     - csv_headers
476
 *     - csv_data
477
 *
478
 * See the sample component implementation for details on each one of these
479
 * callbacks.
480
 *
481
 * @see webform_components()
482
 */
483
function hook_webform_component_info() {
484
  $components = array();
485

    
486
  $components['textfield'] = array(
487
    'label' => t('Textfield'),
488
    'description' => t('Basic textfield type.'),
489
    'features' => array(
490
      // This component includes an analysis callback. Defaults to TRUE.
491
      'analysis' => TRUE,
492

    
493
      // Add content to CSV downloads. Defaults to TRUE.
494
      'csv' => TRUE,
495

    
496
      // This component supports default values. Defaults to TRUE.
497
      'default_value' => FALSE,
498

    
499
      // This component supports a description field. Defaults to TRUE.
500
      'description' => FALSE,
501

    
502
      // Show this component in e-mailed submissions. Defaults to TRUE.
503
      'email' => TRUE,
504

    
505
      // Allow this component to be used as an e-mail FROM or TO address.
506
      // Defaults to FALSE.
507
      'email_address' => FALSE,
508

    
509
      // Allow this component to be used as an e-mail SUBJECT or FROM name.
510
      // Defaults to FALSE.
511
      'email_name' => TRUE,
512

    
513
      // This component may be toggled as required or not. Defaults to TRUE.
514
      'required' => TRUE,
515

    
516
      // This component supports a title attribute. Defaults to TRUE.
517
      'title' => FALSE,
518

    
519
      // This component has a title that can be toggled as displayed or not.
520
      'title_display' => TRUE,
521

    
522
      // This component has a title that can be displayed inline.
523
      'title_inline' => TRUE,
524

    
525
      // If this component can be used as a conditional SOURCE. All components
526
      // may always be displayed conditionally, regardless of this setting.
527
      // Defaults to TRUE.
528
      'conditional' => TRUE,
529

    
530
      // If this component allows other components to be grouped within it
531
      // (like a fieldset or tabs). Defaults to FALSE.
532
      'group' => FALSE,
533

    
534
      // If this component can be used for SPAM analysis, usually with Mollom.
535
      'spam_analysis' => FALSE,
536

    
537
      // If this component saves a file that can be used as an e-mail
538
      // attachment. Defaults to FALSE.
539
      'attachment' => FALSE,
540

    
541
      // If this component reflects a time range and should use labels such as
542
      // "Before" and "After" when exposed as filters in Views module.
543
      'views_range' => FALSE,
544
    ),
545

    
546
    // Specify the conditional behaviour of this component.
547
    // Examples are 'string', 'date', 'time', 'numeric', 'select'.
548
    // Defaults to 'string'.
549
    'conditional_type' => 'string',
550

    
551
    'file' => 'components/textfield.inc',
552
  );
553

    
554
  return $components;
555
}
556

    
557
/**
558
 * Alter the list of available Webform components.
559
 *
560
 * @param $components
561
 *   A list of existing components as defined by hook_webform_component_info().
562
 *
563
 * @see hook_webform_component_info()
564
 */
565
function hook_webform_component_info_alter(&$components) {
566
  // Completely remove a component.
567
  unset($components['grid']);
568

    
569
  // Change the name of a component.
570
  $components['textarea']['label'] = t('Text box');
571
}
572

    
573
/**
574
 * Alter the list of Webform component default values.
575
 *
576
 * @param $defaults
577
 *   A list of component defaults as defined by _webform_defaults_COMPONENT().
578
 * @param $type
579
 *   The component type whose defaults are being provided.
580
 *
581
 * @see _webform_defaults_component()
582
 */
583
function hook_webform_component_defaults_alter(&$defaults, $type) {
584
  // Alter a default for all component types.
585
  $defaults['required'] = 1;
586

    
587
  // Add a default for a new field added via hook_form_alter() or
588
  // hook_form_FORM_ID_alter() for all component types.
589
  $defaults['extra']['added_field'] = t('Added default value');
590

    
591
  // Add or alter defaults for specific component types:
592
  switch ($type) {
593
    case 'select':
594
      $defaults['extra']['optrand'] = 1;
595
      break;
596

    
597
    case 'textfield':
598
    case 'textarea':
599
      $defaults['extra']['another_added_field'] = t('Another added default value');
600
  }
601
}
602

    
603
/**
604
 * Alter access to a Webform submission.
605
 *
606
 * @param $node
607
 *   The Webform node on which this submission was made.
608
 * @param $submission
609
 *   The Webform submission.
610
 * @param $op
611
 *   The operation to be performed on the submission. Possible values are:
612
 *   - "view"
613
 *   - "edit"
614
 *   - "delete"
615
 *   - "list"
616
 * @param $account
617
 *   A user account object.
618
 *
619
 * @return bool
620
 *   TRUE if the current user has access to submission,
621
 *   or FALSE otherwise.
622
 */
623
function hook_webform_submission_access($node, $submission, $op = 'view', $account = NULL) {
624
  switch ($op) {
625
    case 'view':
626
      return TRUE;
627
      break;
628
    case 'edit':
629
      return FALSE;
630
      break;
631
    case 'delete':
632
      return TRUE;
633
      break;
634
    case 'list':
635
      return TRUE;
636
      break;
637
  }
638
}
639

    
640
/**
641
 * Determine if a user has access to see the results of a webform.
642
 *
643
 * Note in addition to the view access to the results granted here, the $account
644
 * must also have view access to the Webform node in order to see results.
645
 * Access via this hook is in addition (adds permission) to the standard
646
 * webform access.
647
 *
648
 * @see webform_results_access()
649
 *
650
 * @param $node
651
 *   The Webform node to check access on.
652
 * @param $account
653
 *   The user account to check access on.
654
 *
655
 * @return bool
656
 *   TRUE or FALSE if the user can access the webform results.
657
 */
658
function hook_webform_results_access($node, $account) {
659
  // Let editors view results of unpublished webforms.
660
  if ($node->status == 0 && in_array('editor', $account->roles)) {
661
    return TRUE;
662
  }
663
  else {
664
    return FALSE;
665
  }
666
}
667

    
668
/**
669
 * Determine if a user has access to clear the results of a webform.
670
 *
671
 * Access via this hook is in addition (adds permission) to the standard
672
 * webform access (delete all webform submissions).
673
 *
674
 * @see webform_results_clear_access()
675
 *
676
 * @param object $node
677
 *   The Webform node to check access on.
678
 * @param object $account
679
 *   The user account to check access on.
680
 * @return boolean
681
 *   TRUE or FALSE if the user can access the webform results.
682
 */
683
function hook_webform_results_clear_access($node, $account) {
684
  return user_access('my additional access', $account);
685
}
686

    
687
/**
688
 * Overrides the node_access and user_access permission to access and edit
689
 * webform components, e-mails, conditions, and form settings.
690
 *
691
 * Return NULL to defer to other modules. If all implementations defer, then
692
 * access to the node's EDIT tab plus 'edit webform components' permission
693
 * determines access. To grant access, return TRUE; to deny access, return
694
 * FALSE. If more than one implementation return TRUE/FALSE, all must be TRUE
695
 * to grant access.
696
 *
697
 * In this way, access to the EDIT tab of the node may be decoupled from
698
 * access to the WEBFORM tab. When returning TRUE, consider all aspects of
699
 * access as this will be the only test. For example, 'return TRUE;' would grant
700
 * annonymous access to creating webform components, which seldom be desired.
701
 *
702
 * @see webform_node_update_access()
703
 *
704
 * @param object $node
705
 *   The Webform node to check access on.
706
 * @param object $account
707
 *   The user account to check access on.
708
 * @return boolean|NULL
709
 *   TRUE or FALSE if the user can access the webform results, or NULL if
710
 *   access should be deferred to other implementations of this hook or
711
 *   node_access('update') plus user_access('edit webform components').
712
 */
713
function hook_webform_update_access($node, $account) {
714
  // Allow anyone who can see webform_editable_by_user nodes and who has
715
  // 'my webform component edit access' permission to see, edit, and delete the
716
  // webform components, e-mails, conditionals, and form settings.
717
  if ($node->type == 'webform_editable_by_user') {
718
    return node_access('view', $node, $account) && user_access('my webform component edit access', $account);
719
  }
720
}
721

    
722
/**
723
 * Return an array of files associated with the component.
724
 *
725
 * The output of this function will be used to attach files to e-mail messages.
726
 *
727
 * @param $component
728
 *   A Webform component array.
729
 * @param $value
730
 *   An array of information containing the submission result, directly
731
 *   correlating to the webform_submitted_data database schema.
732
 *
733
 * @return array
734
 *   An array of files, each file is an array with following keys:
735
 *     - filepath: The relative path to the file.
736
 *     - filename: The name of the file including the extension.
737
 *     - filemime: The mimetype of the file.
738
 *   This will result in an array looking something like this:
739
 *   @code
740
 *   array[0] => array(
741
 *     'filepath' => '/sites/default/files/attachment.txt',
742
 *     'filename' => 'attachment.txt',
743
 *     'filemime' => 'text/plain',
744
 *   );
745
 *   @endcode
746
 */
747
function _webform_attachments_component($component, $value) {
748
  $files = array();
749
  $files[] = (array) file_load($value[0]);
750
  return $files;
751
}
752

    
753
/**
754
 * Alter default settings for a newly created webform node.
755
 *
756
 * @param array $defaults
757
 *   Default settings for a newly created webform node as defined by webform_node_defaults().
758
 *
759
 * @see webform_node_defaults()
760
 */
761
function hook_webform_node_defaults_alter(&$defaults) {
762
  $defaults['allow_draft'] = '1';
763
}
764

    
765
/**
766
 * Add additional fields to submission data downloads.
767
 *
768
 * @return array
769
 *   Keys and titles for default submission information.
770
 *
771
 * @see hook_webform_results_download_submission_information_data()
772
 */
773
function hook_webform_results_download_submission_information_info() {
774
  return array(
775
    'field_key_1' => t('Field Title 1'),
776
    'field_key_2' => t('Field Title 2'),
777
  );
778
}
779

    
780
/**
781
 * Return values for submission data download fields.
782
 *
783
 * @param $token
784
 *   The name of the token being replaced.
785
 * @param $submission
786
 *   The data for an individual submission from webform_get_submissions().
787
 * @param array $options
788
 *   A list of options that define the output format. These are generally passed
789
 *   through from the GUI interface.
790
 * @param $serial_start
791
 *   The starting position for the Serial column in the output.
792
 * @param $row_count
793
 *   The number of the row being generated.
794
 *
795
 * @return string
796
 *   Value for requested submission information field.
797
 *
798
 * @see hook_webform_results_download_submission_information_info()
799
 */
800
function hook_webform_results_download_submission_information_data($token, $submission, array $options, $serial_start, $row_count) {
801
  switch ($token) {
802
    case 'field_key_1':
803
      return 'Field Value 1';
804
    case 'field_key_2':
805
      return 'Field Value 2';
806
  }
807
}
808

    
809
/**
810
 * @}
811
 */
812

    
813
/**
814
 * @defgroup webform_component Sample Webform Component
815
 * @{
816
 * In each of these examples, the word "component" should be replaced with the,
817
 * name of the component type (such as textfield or select). These are not
818
 * actual hooks, but instead samples of how Webform integrates with its own
819
 * built-in components.
820
 */
821

    
822
/**
823
 * Specify the default properties of a component.
824
 *
825
 * @return array
826
 *   An array defining the default structure of a component.
827
 */
828
function _webform_defaults_component() {
829
  return array(
830
    'name' => '',
831
    'form_key' => NULL,
832
    'required' => 0,
833
    'pid' => 0,
834
    'weight' => 0,
835
    'extra' => array(
836
      'options' => '',
837
      'questions' => '',
838
      'optrand' => 0,
839
      'qrand' => 0,
840
      'description' => '',
841
      'description_above' => FALSE,
842
      'private' => FALSE,
843
      'analysis' => TRUE,
844
    ),
845
  );
846
}
847

    
848
/**
849
 * Generate the form for editing a component.
850
 *
851
 * Create a set of form elements to be displayed on the form for editing this
852
 * component. Use care naming the form items, as this correlates directly to the
853
 * database schema. The component "Name" and "Description" fields are added to
854
 * every component type and are not necessary to specify here (although they
855
 * may be overridden if desired).
856
 *
857
 * @param $component
858
 *   A Webform component array.
859
 *
860
 * @return array
861
 *   An array of form items to be displayed on the edit component page
862
 */
863
function _webform_edit_component($component) {
864
  $form = array();
865

    
866
  // Disabling the description if not wanted.
867
  $form['description'] = array();
868

    
869
  // Most options are stored in the "extra" array, which stores any settings
870
  // unique to a particular component type.
871
  $form['extra']['options'] = array(
872
    '#type' => 'textarea',
873
    '#title' => t('Options'),
874
    '#default_value' => $component['extra']['options'],
875
    '#description' => t('Key-value pairs may be entered separated by pipes. i.e. safe_key|Some readable option') . ' ' . theme('webform_token_help'),
876
    '#cols' => 60,
877
    '#rows' => 5,
878
    '#weight' => -3,
879
    '#required' => TRUE,
880
  );
881
  return $form;
882
}
883

    
884
/**
885
 * Render a Webform component to be part of a form.
886
 *
887
 * @param $component
888
 *   A Webform component array.
889
 * @param $value
890
 *   If editing an existing submission or resuming a draft, this will contain
891
 *   an array of values to be shown instead of the default in the component
892
 *   configuration. This value will always be an array, keyed numerically for
893
 *   each value saved in this field.
894
 * @param $filter
895
 *   Whether or not to filter the contents of descriptions and values when
896
 *   rendering the component. Values need to be unfiltered to be editable by
897
 *   Form Builder.
898
 * @param $submission
899
 *   The submission from which this component is being rendered. Usually not
900
 *   needed. Used by _webform_render_date() to validate using the submission's
901
 *   completion date.
902
 *
903
 * @return array
904
 *   $form_item
905
 *
906
 * @see _webform_client_form_add_component()
907
 */
908
function _webform_render_component($component, $value = NULL, $filter = TRUE, $submission = NULL) {
909
  $form_item = array(
910
    '#type' => 'textfield',
911
    '#title' => $filter ? webform_filter_xss($component['name']) : $component['name'],
912
    '#required' => $component['required'],
913
    '#weight' => $component['weight'],
914
    '#description'   => $filter ? webform_filter_descriptions($component['extra']['description']) : $component['extra']['description'],
915
    '#default_value' => $filter ? webform_replace_tokens($component['value']) : $component['value'],
916
    '#theme_wrappers' => array('webform_element'),
917
  );
918

    
919
  if (isset($value)) {
920
    $form_item['#default_value'] = $value[0];
921
  }
922

    
923
  return $form_item;
924
}
925

    
926
/**
927
 * Allow modules to modify a webform component that is going to be rendered in a form.
928
 *
929
 * @param array $element
930
 *   The display element as returned by _webform_render_component().
931
 * @param array $component
932
 *   A Webform component array.
933
 *
934
 * @see _webform_render_component()
935
 */
936
function hook_webform_component_render_alter(&$element, &$component) {
937
  if ($component['cid'] == 10) {
938
    $element['#title'] = 'My custom title';
939
    $element['#default_value'] = 42;
940
  }
941
}
942

    
943
/**
944
 * Display the result of a submission for a component.
945
 *
946
 * The output of this function will be displayed under the "Results" tab then
947
 * "Submissions". This should output the saved data in some reasonable manner.
948
 *
949
 * @param $component
950
 *   A Webform component array.
951
 * @param $value
952
 *   An array of information containing the submission result, directly
953
 *   correlating to the webform_submitted_data database table schema.
954
 * @param $format
955
 *   Either 'html' or 'text'. Defines the format that the content should be
956
 *   returned as. Make sure that returned content is run through check_plain()
957
 *   or other filtering functions when returning HTML.
958
 * @param $submission
959
 *   The submission. Used to generate tokens.
960
 *
961
 * @return array
962
 *   A renderable element containing at the very least these properties:
963
 *    - #title
964
 *    - #weight
965
 *    - #component
966
 *    - #format
967
 *    - #value
968
 *   Webform also uses #theme_wrappers to output the end result to the user,
969
 *   which will properly format the label and content for use within an e-mail
970
 *   (such as wrapping the text) or as HTML (ensuring consistent output).
971
 */
972
function _webform_display_component($component, $value, $format = 'html', $submission = array()) {
973
  return array(
974
    '#title' => $component['name'],
975
    '#weight' => $component['weight'],
976
    '#theme' => 'webform_display_textfield',
977
    '#theme_wrappers' => $format == 'html' ? array('webform_element') : array('webform_element_text'),
978
    '#post_render' => array('webform_element_wrapper'),
979
    '#field_prefix' => $component['extra']['field_prefix'],
980
    '#field_suffix' => $component['extra']['field_suffix'],
981
    '#component' => $component,
982
    '#format' => $format,
983
    '#value' => isset($value[0]) ? $value[0] : '',
984
  );
985
}
986

    
987
/**
988
 * Allow modules to modify a "display only" webform component.
989
 *
990
 * @param array $element
991
 *   The display element as returned by _webform_display_component().
992
 * @param array $component
993
 *   A Webform component array.
994
 *
995
 * @see _webform_display_component()
996
 */
997
function hook_webform_component_display_alter(&$element, &$component) {
998
  if ($component['cid'] == 10) {
999
    $element['#title'] = 'My custom title';
1000
    $element['#default_value'] = 42;
1001
  }
1002
}
1003

    
1004
/**
1005
 * Performs the conditional action set on an implemented component.
1006
 *
1007
 * Setting the form element allows form validation functions to see the value
1008
 * that webform has set for the given component.
1009
 *
1010
 * @param array $component
1011
 *   The webform component array whose value is being set for the currently-
1012
 *   edited submission.
1013
 * @param array $element
1014
 *   The form element currently being set.
1015
 * @param array $form_state
1016
 *   The form's state.
1017
 * @param string $value
1018
 *   The value to be set, as defined in the conditional action.
1019
 */
1020
function _webform_action_set_component($component, &$element, &$form_state, $value) {
1021
  $element['#value'] = $value;
1022
  form_set_value($element, $value, $form_state);
1023
}
1024

    
1025
/**
1026
 * A hook for changing the input values before saving to the database.
1027
 *
1028
 * Webform expects a component to consist of a single field, or a single array
1029
 * of fields. If you have a component that requires a deeper form tree
1030
 * you must flatten the data into a single array using this callback
1031
 * or by setting #parents on each field to avoid data loss and/or unexpected
1032
 * behavior.
1033
 *
1034
 * Note that Webform will save the result of this function directly into the
1035
 * database.
1036
 *
1037
 * @param $component
1038
 *   A Webform component array.
1039
 * @param $value
1040
 *   The POST data associated with the user input.
1041
 * @return
1042
 *   An array of values to be saved into the database. Note that this should be
1043
 *   a numerically keyed array.
1044
 */
1045
function _webform_submit_component($component, $value) {
1046
  // Clean up a phone number into 123-456-7890 format.
1047
  if ($component['extra']['phone_number']) {
1048
    $number = preg_replace('/[^0-9]/', '', $value[0]);
1049
    if (strlen($number) == 7) {
1050
      $number = substr($number, 0, 3) . '-' . substr($number, 3, 4);
1051
    }
1052
    else {
1053
      $number = substr($number, 0, 3) . '-' . substr($number, 3, 3) . '-' . substr($number, 6, 4);
1054
    }
1055
  }
1056

    
1057
  $value[0] = $number;
1058
  return $value;
1059
}
1060

    
1061
/**
1062
 * Delete operation for a component or submission.
1063
 *
1064
 * @param $component
1065
 *   A Webform component array.
1066
 * @param $value
1067
 *   An array of information containing the submission result, directly
1068
 *   correlating to the webform_submitted_data database schema.
1069
 */
1070
function _webform_delete_component($component, $value) {
1071
  // Delete corresponding files when a submission is deleted.
1072
  if (!empty($value[0]) && ($file = webform_get_file($value[0]))) {
1073
    file_usage_delete($file, 'webform');
1074
    file_delete($file);
1075
  }
1076
}
1077

    
1078
/**
1079
 * Module specific instance of hook_help().
1080
 *
1081
 * This allows each Webform component to add information into hook_help().
1082
 */
1083
function _webform_help_component($section) {
1084
  switch ($section) {
1085
    case 'admin/config/content/webform#grid_description':
1086
      return t('Allows creation of grid questions, denoted by radio buttons.');
1087
  }
1088
}
1089

    
1090
/**
1091
 * Module specific instance of hook_theme().
1092
 *
1093
 * This allows each Webform component to add information into hook_theme(). If
1094
 * you specify a file to include, you must define the path to the module that
1095
 * this file belongs to.
1096
 */
1097
function _webform_theme_component() {
1098
  return array(
1099
    'webform_grid' => array(
1100
      'render element' => 'element',
1101
      'file' => 'components/grid.inc',
1102
      'path' => drupal_get_path('module', 'webform'),
1103
    ),
1104
    'webform_display_grid' => array(
1105
      'render element' => 'element',
1106
      'file' => 'components/grid.inc',
1107
      'path' => drupal_get_path('module', 'webform'),
1108
    ),
1109
  );
1110
}
1111

    
1112
/**
1113
 * Calculate and returns statistics about results for this component.
1114
 *
1115
 * This takes into account all submissions to this webform. The output of this
1116
 * function will be displayed under the "Results" tab then "Analysis".
1117
 *
1118
 * @param $component
1119
 *   An array of information describing the component, directly correlating to
1120
 *   the webform_component database schema.
1121
 * @param $sids
1122
 *   An optional array of submission IDs (sid). If supplied, the analysis will
1123
 *   be limited to these sids.
1124
 * @param $single
1125
 *   Boolean flag determining if the details about a single component are being
1126
 *   shown. May be used to provided detailed information about a single
1127
 *   component's analysis, such as showing "Other" options within a select list.
1128
 * @param $join
1129
 *   An optional SelectQuery object to be used to join with the submissions
1130
 *   table to restrict the submissions being analyzed.
1131
 *
1132
 * @return array
1133
 *   An array containing one or more of the following keys:
1134
 *   - table_rows: If this component has numeric data that can be represented in
1135
 *     a grid, return the values here. This array assumes a 2-dimensional
1136
 *     structure, with the first value being a label and subsequent values
1137
 *     containing a decimal or integer.
1138
 *   - table_header: If this component has more than a single set of values,
1139
 *     include a table header so each column can be labeled.
1140
 *   - other_data: If your component has non-numeric data to include, such as
1141
 *     a description or link, include that in the other_data array. Each item
1142
 *     may be a string or an array of values that matches the number of columns
1143
 *     in the table_header property.
1144
 *   At the very least, either table_rows or other_data should be provided.
1145
 *   Note that if you want your component's analysis to be available by default
1146
 *   without the user specifically enabling it, you must set
1147
 *   $component['extra']['analysis'] = TRUE in your
1148
 *   _webform_defaults_component() callback.
1149
 *
1150
 * @see _webform_defaults_component()
1151
 */
1152
function _webform_analysis_component($component, $sids = array(), $single = FALSE, $join = NULL) {
1153
  // Generate the list of options and questions.
1154
  $options = _webform_select_options_from_text($component['extra']['options'], TRUE);
1155
  $questions = _webform_select_options_from_text($component['extra']['questions'], TRUE);
1156

    
1157
  // Generate a lookup table of results.
1158
  $query = db_select('webform_submitted_data', 'wsd')
1159
    ->fields('wsd', array('no', 'data'))
1160
    ->condition('nid', $component['nid'])
1161
    ->condition('cid', $component['cid'])
1162
    ->condition('data', '', '<>')
1163
    ->groupBy('no')
1164
    ->groupBy('data');
1165
  $query->addExpression('COUNT(sid)', 'datacount');
1166

    
1167
  if (count($sids)) {
1168
    $query->condition('sid', $sids, 'IN');
1169
  }
1170

    
1171
  if ($join) {
1172
    $query->innerJoin($join, 'ws2_', 'wsd.sid = ws2_.sid');
1173
  }
1174

    
1175
  $result = $query->execute();
1176
  $counts = array();
1177
  foreach ($result as $data) {
1178
    $counts[$data->no][$data->data] = $data->datacount;
1179
  }
1180

    
1181
  // Create an entire table to be put into the returned row.
1182
  $rows = array();
1183
  $header = array('');
1184

    
1185
  // Add options as a header row.
1186
  foreach ($options as $option) {
1187
    $header[] = $option;
1188
  }
1189

    
1190
  // Add questions as each row.
1191
  foreach ($questions as $qkey => $question) {
1192
    $row = array($question);
1193
    foreach ($options as $okey => $option) {
1194
      $row[] = !empty($counts[$qkey][$okey]) ? $counts[$qkey][$okey] : 0;
1195
    }
1196
    $rows[] = $row;
1197
  }
1198

    
1199
  $other = array();
1200
  $other[] = l(t('More information'), 'node/' . $component['nid'] . '/webform-results/analysis/' . $component['cid']);
1201

    
1202
  return array(
1203
    'table_header' => $header,
1204
    'table_rows' => $rows,
1205
    'other_data' => $other,
1206
  );
1207
}
1208

    
1209
/**
1210
 * Return the result of a component value for display in a table.
1211
 *
1212
 * The output of this function will be displayed under the "Results" tab then
1213
 * "Table".
1214
 *
1215
 * @param $component
1216
 *   A Webform component array.
1217
 * @param $value
1218
 *   An array of information containing the submission result, directly
1219
 *   correlating to the webform_submitted_data database schema.
1220
 *
1221
 * @return string
1222
 *   Textual output formatted for human reading.
1223
 */
1224
function _webform_table_component($component, $value) {
1225
  $questions = array_values(_webform_component_options($component['extra']['questions']));
1226
  $output = '';
1227
  // Set the value as a single string.
1228
  if (is_array($value)) {
1229
    foreach ($value as $item => $value) {
1230
      if ($value !== '') {
1231
        $output .= $questions[$item] . ': ' . check_plain($value) . '<br />';
1232
      }
1233
    }
1234
  }
1235
  else {
1236
    $output = check_plain(!isset($value['0']) ? '' : $value['0']);
1237
  }
1238
  return $output;
1239
}
1240

    
1241
/**
1242
 * Return the header for this component to be displayed in a CSV file.
1243
 *
1244
 * The output of this function will be displayed under the "Results" tab then
1245
 * "Download".
1246
 *
1247
 * @param $component
1248
 *   A Webform component array.
1249
 * @param $export_options
1250
 *   An array of options that may configure export of this field.
1251
 *
1252
 * @return array
1253
 *   An array of data to be displayed in the first three rows of a CSV file, not
1254
 *   including either prefixed or trailing commas.
1255
 */
1256
function _webform_csv_headers_component($component, $export_options) {
1257
  $header = array();
1258
  $header[0] = array('');
1259
  $header[1] = array($export_options['header_keys'] ? $component['form_key'] : $component['name']);
1260
  $items = _webform_component_options($component['extra']['questions']);
1261
  $count = 0;
1262
  foreach ($items as $key => $item) {
1263
    // Empty column per sub-field in main header.
1264
    if ($count != 0) {
1265
      $header[0][] = '';
1266
      $header[1][] = '';
1267
    }
1268
    // The value for this option.
1269
    $header[2][] = $item;
1270
    $count++;
1271
  }
1272

    
1273
  return $header;
1274
}
1275

    
1276
/**
1277
 * Format the submitted data of a component for CSV downloading.
1278
 *
1279
 * The output of this function will be displayed under the "Results" tab then
1280
 * "Download".
1281
 *
1282
 * @param $component
1283
 *   A Webform component array.
1284
 * @param $export_options
1285
 *   An array of options that may configure export of this field.
1286
 * @param $value
1287
 *   An array of information containing the submission result, directly
1288
 *   correlating to the webform_submitted_data database schema.
1289
 *
1290
 * @return array
1291
 *   An array of items to be added to the CSV file. Each value within the array
1292
 *   will be another column within the file. This function is called once for
1293
 *   every row of data.
1294
 */
1295
function _webform_csv_data_component($component, $export_options, $value) {
1296
  $questions = array_keys(_webform_select_options($component['extra']['questions']));
1297
  $return = array();
1298
  foreach ($questions as $key => $question) {
1299
    $return[] = isset($value[$key]) ? $value[$key] : '';
1300
  }
1301
  return $return;
1302
}
1303

    
1304
/**
1305
 * Adjusts the view field(s) that are automatically generated for number
1306
 * components.
1307
 *
1308
 * Provides each component the opportunity to adjust how this component is
1309
 * displayed in a view as a field in a view table. For example, a component may
1310
 * modify how it responds to click-sorting. Or it may add additional fields,
1311
 * such as a grid component having a column for each question.
1312
 *
1313
 * @param array $component
1314
 *   A Webform component array
1315
 * @param array $fields
1316
 *   An array of field-definition arrays. Will be passed one field definition,
1317
 *   which may be modified. Additional fields may be added to the array.
1318
 * @return array
1319
 *   The modified $fields array.
1320
 */
1321
function _webform_view_field_component($component, $fields) {
1322
  foreach ($fields as &$field) {
1323
    $field['webform_datatype'] = 'number';
1324
  }
1325
  return $fields;
1326
}
1327

    
1328
/**
1329
 * Modify the how a view was expanded to show all the components.
1330
 *
1331
 * This alter function is only called when the view is actually modified. It
1332
 * provides modules an opportunity to alter the changes that webform made to
1333
 * the view.
1334
 *
1335
 * This hook is called from webform_views_pre_view. If another module also
1336
 * changes views by implementing this same views hook, the relative order of
1337
 * execution of the two implementations will depend upon the module weights of
1338
 * the two modules. Using hook_webform_view_alter instead guarantees an
1339
 * opportuinty to modify the view AFTER webform.
1340
 *
1341
 * @param object $view
1342
 *   The view object.
1343
 * @param string $display_id
1344
 *   The display_id that was expanded by webform.
1345
 * @param array $args
1346
 *   The argumentst that were passed to the view.
1347
 */
1348
function hook_webform_view_alter($view, $display_id, $args) {
1349
  // Don't show component with cid == 4
1350
  $fields = $view->get_items('field', $display_id);
1351
  foreach ($fields as $id => $field) {
1352
    if (isset($field['webform_cid']) && $field['webform_cid'] == 4) {
1353
      unset($fields[$id]);
1354
    }
1355
  }
1356
  $view->display[$display_id]->handler->set_option('fields', $fields);
1357
}
1358

    
1359
/**
1360
 * Modify the list of mail systems that are capable of sending HTML email.
1361
 *
1362
 * @param array &$systems
1363
 *   An array of mail system class names.
1364
 */
1365
function hook_webform_html_capable_mail_systems_alter(&$systems) {
1366
  if (module_exists('my_module')) {
1367
    $systems[] = 'MyModuleMailSystem';
1368
  }
1369
}
1370

    
1371
/**
1372
 * Define a list of webform exporters.
1373
 *
1374
 * @return array
1375
 *   A list of the available exporters provided by the module.
1376
 *
1377
 * @see webform_webform_exporters()
1378
 */
1379
function hook_webform_exporters() {
1380
  $exporters = array(
1381
    'webform_exporter_custom' => array(
1382
      'title' => t('Webform exporter name'),
1383
      'description' => t('The description for this exporter.'),
1384
      'handler' => 'webform_exporter_custom',
1385
      'file' => drupal_get_path('module', 'yourmodule') . '/includes/webform_exporter_custom.inc',
1386
      'weight' => 10,
1387
    ),
1388
  );
1389

    
1390
  return $exporters;
1391
}
1392

    
1393
/**
1394
 * Modify the list of webform exporters definitions.
1395
 *
1396
 * @param  array &$exporters
1397
 *   A list of all available webform exporters.
1398
 */
1399
function hook_webform_exporters_alter(&$exporters) {
1400
  $exporters['excel']['handler'] = 'customized_excel_exporter';
1401
  $exporters['excel']['file'] = drupal_get_path('module', 'yourmodule') . '/includes/customized_excel_exporter.inc';
1402
}
1403

    
1404
/**
1405
 * @}
1406
 */