Projet

Général

Profil

Paste
Télécharger (17,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / captcha / image_captcha / image_captcha.admin.inc @ ac1bc5de

1
<?php
2

    
3
/**
4
 * @file
5
 * Functions for administration/settings interface.
6
 */
7

    
8
/**
9
 * Configuration form for image_captcha.
10
 */
11
function image_captcha_settings_form() {
12

    
13
  $form = array();
14

    
15
  // Add CSS for theming of admin form.
16
  $form['#attached']['css'] = array(drupal_get_path('module', 'image_captcha') . '/image_captcha.css');
17
  // Use javascript for some added usability on admin form.
18
  $form['#attached']['js'] = array(drupal_get_path('module', 'image_captcha') . '/image_captcha.js');
19

    
20
  // First some error checking.
21
  $setup_status = _image_captcha_check_setup(FALSE);
22
  if ($setup_status & IMAGE_CAPTCHA_ERROR_NO_GDLIB) {
23
    drupal_set_message(t(
24
      'The Image CAPTCHA module can not generate images because your PHP setup does not support it (no <a href="!gdlib">GD library</a> with JPEG support).',
25
      array('!gdlib' => 'http://php.net/manual/en/book.image.php')
26
    ), 'error');
27
    // It is no use to continue building the rest of the settings form.
28
    return $form;
29
  }
30

    
31
  $form['image_captcha_example'] = array(
32
    '#type' => 'fieldset',
33
    '#title' => t('Example'),
34
    '#description' => t('Presolved image CAPTCHA example, generated with the current settings.'),
35
  );
36
  $form['image_captcha_example']['image'] = array(
37
    '#type' => 'captcha',
38
    '#captcha_type' => 'image_captcha/Image',
39
    '#captcha_admin_mode' => TRUE,
40
  );
41

    
42
  // General code settings.
43
  $form['image_captcha_code_settings'] = array(
44
    '#type' => 'fieldset',
45
    '#title' => t('Code settings'),
46
  );
47
  $form['image_captcha_code_settings']['image_captcha_image_allowed_chars'] = array(
48
    '#type' => 'textfield',
49
    '#title' => t('Characters to use in the code'),
50
    '#default_value' => variable_get('image_captcha_image_allowed_chars', IMAGE_CAPTCHA_ALLOWED_CHARACTERS),
51
  );
52
  $form['image_captcha_code_settings']['image_captcha_code_length'] = array(
53
    '#type' => 'select',
54
    '#title' => t('Code length'),
55
    '#options' => array(2 => 2, 3, 4, 5, 6, 7, 8, 9, 10),
56
    '#default_value' => (int) variable_get('image_captcha_code_length', 5),
57
    '#description' => t('The code length influences the size of the image. Note that larger values make the image generation more CPU intensive.'),
58
  );
59
  // RTL support option (only show this option when there are RTL languages).
60
  $languages = language_list('direction');
61
  if (isset($languages[LANGUAGE_RTL])) {
62
    $form['image_captcha_code_settings']['image_captcha_rtl_support'] = array(
63
      '#type' => 'checkbox',
64
      '#title' => t('RTL support'),
65
      '#default_value' => variable_get('image_captcha_rtl_support', 0),
66
      '#description' => t('Enable this option to render the code from right to left for right to left languages.'),
67
    );
68
  }
69

    
70
  // Font related stuff.
71
  $form['image_captcha_font_settings'] = _image_captcha_settings_form_font_section();
72

    
73
  // Color and file format settings.
74
  $form['image_captcha_color_settings'] = array(
75
    '#type' => 'fieldset',
76
    '#title' => t('Color and image settings'),
77
    '#description' => t('Configuration of the background, text colors and file format of the image CAPTCHA.'),
78
  );
79
  $form['image_captcha_color_settings']['image_captcha_background_color'] = array(
80
    '#type' => 'textfield',
81
    '#title' => t('Background color'),
82
    '#description' => t('Enter the hexadecimal code for the background color (e.g. #FFF or #FFCE90). When using the PNG file format with transparent background, it is recommended to set this close to the underlying background color.'),
83
    '#default_value' => variable_get('image_captcha_background_color', '#ffffff'),
84
    '#maxlength' => 7,
85
    '#size' => 8,
86
  );
87
  $form['image_captcha_color_settings']['image_captcha_foreground_color'] = array(
88
    '#type' => 'textfield',
89
    '#title' => t('Text color'),
90
    '#description' => t('Enter the hexadecimal code for the text color (e.g. #000 or #004283).'),
91
    '#default_value' => variable_get('image_captcha_foreground_color', '#000000'),
92
    '#maxlength' => 7,
93
    '#size' => 8,
94
  );
95
  $form['image_captcha_color_settings']['image_captcha_foreground_color_randomness'] = array(
96
    '#type' => 'select',
97
    '#title' => t('Additional variation of text color'),
98
    '#options' => array(
99
      0 => t('No variation'),
100
      50 => t('Little variation'),
101
      100 => t('Medium variation'),
102
      150 => t('High variation'),
103
      200 => t('Very high variation'),
104
    ),
105
    '#default_value' => (int) variable_get('image_captcha_foreground_color_randomness', 100),
106
    '#description' => t('The different characters will have randomized colors in the specified range around the text color.'),
107
  );
108
  $form['image_captcha_color_settings']['image_captcha_file_format'] = array(
109
    '#type' => 'select',
110
    '#title' => t('File format'),
111
    '#description' => t('Select the file format for the image. JPEG usually results in smaller files, PNG allows tranparency.'),
112
    '#default_value' => variable_get('image_captcha_file_format', IMAGE_CAPTCHA_FILE_FORMAT_JPG),
113
    '#options' => array(
114
      IMAGE_CAPTCHA_FILE_FORMAT_JPG => t('JPEG'),
115
      IMAGE_CAPTCHA_FILE_FORMAT_PNG => t('PNG'),
116
      IMAGE_CAPTCHA_FILE_FORMAT_TRANSPARENT_PNG => t('PNG with transparent background'),
117
    ),
118
  );
119

    
120
  // Distortion and noise settings.
121
  $form['image_captcha_distortion_and_noise'] = array(
122
    '#type' => 'fieldset',
123
    '#title' => t('Distortion and noise'),
124
    '#description' => t('With these settings you can control the degree of obfuscation by distortion and added noise. Do not exaggerate the obfuscation and assure that the code in the image is reasonably readable. For example, do not combine high levels of distortion and noise.'),
125
  );
126
  // Distortion.
127
  $form['image_captcha_distortion_and_noise']['image_captcha_distortion_amplitude'] = array(
128
    '#type' => 'select',
129
    '#title' => t('Distortion level'),
130
    '#options' => array(
131
      0 => t('@level - no distortion', array('@level' => '0')),
132
      1 => t('@level - low', array('@level' => '1')),
133
      2 => '2',
134
      3 => '3',
135
      4 => '4',
136
      5 => t('@level - medium', array('@level' => '5')),
137
      6 => '6',
138
      7 => '7',
139
      8 => '8',
140
      9 => '9',
141
      10 => t('@level - high', array('@level' => '10')),
142
    ),
143
    '#default_value' => (int) variable_get('image_captcha_distortion_amplitude', 0),
144
    '#description' => t('Set the degree of wave distortion in the image.'),
145
  );
146
  $form['image_captcha_distortion_and_noise']['image_captcha_bilinear_interpolation'] = array(
147
    '#type' => 'checkbox',
148
    '#title' => t('Smooth distortion'),
149
    '#default_value' => variable_get('image_captcha_bilinear_interpolation', FALSE),
150
    '#description' => t('This option enables bilinear interpolation of the distortion which makes the image look smoother, but it is more CPU intensive.'),
151
  );
152
  // Noise.
153
  $form['image_captcha_distortion_and_noise']['image_captcha_dot_noise'] = array(
154
    '#type' => 'checkbox',
155
    '#title' => t('Add salt and pepper noise'),
156
    '#default_value' => variable_get('image_captcha_dot_noise', 0),
157
    '#description' => t('This option adds randomly colored point noise.'),
158
  );
159
  $form['image_captcha_distortion_and_noise']['image_captcha_line_noise'] = array(
160
    '#type' => 'checkbox',
161
    '#title' => t('Add line noise'),
162
    '#default_value' => variable_get('image_captcha_line_noise', 0),
163
    '#description' => t('This option enables lines randomly drawn on top of the text code.'),
164
  );
165
  $form['image_captcha_distortion_and_noise']['image_captcha_noise_level'] = array(
166
    '#type' => 'select',
167
    '#title' => t('Noise level'),
168
    '#options' => array(
169
      1 => '1 - ' . t('low'),
170
      2 => '2',
171
      3 => '3 - ' . t('medium'),
172
      4 => '4',
173
      5 => '5 - ' . t('high'),
174
      7 => '7',
175
      10 => '10 - ' . t('severe'),
176
    ),
177
    '#default_value' => (int) variable_get('image_captcha_noise_level', 5),
178
  );
179

    
180
  // Add a validation handler.
181
  $form['#validate'] = array('image_captcha_settings_form_validate');
182

    
183
  // Make it a settings form.
184
  $form = system_settings_form($form);
185
  // But also do some custom submission handling.
186
  $form['#submit'][] = 'image_captcha_settings_form_submit';
187

    
188
  return $form;
189
}
190

    
191
/**
192
 * Form elements for the font specific setting.
193
 *
194
 * This is refactored to a separate function to avoid poluting the
195
 * general form function image_captcha_settings_form with some
196
 * specific logic.
197
 *
198
 * @return array
199
 *   the font settings specific form elements.
200
 */
201
function _image_captcha_settings_form_font_section() {
202
  // Put it all in a fieldset.
203
  $form = array(
204
    '#type' => 'fieldset',
205
    '#title' => t('Font settings'),
206
  );
207

    
208
  // First check if there is TrueType support.
209
  $setup_status = _image_captcha_check_setup(FALSE);
210
  if ($setup_status & IMAGE_CAPTCHA_ERROR_NO_TTF_SUPPORT) {
211
    // Show a warning that there is no TrueType support.
212
    $form['no_ttf_support'] = array(
213
      '#type' => 'item',
214
      '#title' => t('No TrueType support'),
215
      '#markup' => t('The Image CAPTCHA module can not use TrueType fonts because your PHP setup does not support it. You can only use a PHP built-in bitmap font of fixed size.'),
216
    );
217

    
218
  }
219
  else {
220
    // Build a list of  all available fonts.
221
    $available_fonts = array();
222

    
223
    // List of folders to search through for TrueType fonts.
224
    $fonts = _image_captcha_get_available_fonts_from_directories();
225
    // Cache the list of previewable fonts. All the previews are done
226
    // in separate requests, and we don't want to rescan the filesystem
227
    // every time, so we cache the result.
228
    variable_set('image_captcha_fonts_preview_map_cache', $fonts);
229
    // Put these fonts with preview image in the list.
230
    foreach ($fonts as $token => $font) {
231
      $img_src = check_url(url('admin/config/people/captcha/image_captcha/font_preview/' . $token));
232
      $title = t('Font preview of @font (@file)', array('@font' => $font->name, '@file' => $font->uri));
233
      $available_fonts[$font->uri] = '<img src="' . $img_src . '" alt="' . $title . '" title="' . $title . '" />';
234
    }
235

    
236
    // Append the PHP built-in font at the end.
237
    $img_src = check_url(url('admin/config/people/captcha/image_captcha/font_preview/BUILTIN'));
238
    $title = t('Preview of built-in font');
239
    $available_fonts['BUILTIN'] = t('PHP built-in font: !font_preview',
240
      array('!font_preview' => '<img src="' . $img_src . '" alt="' . $title . '" title="' . $title . '" />')
241
    );
242

    
243
    $default_fonts = _image_captcha_get_enabled_fonts();
244
    $form['image_captcha_fonts'] = array(
245
      '#type' => 'checkboxes',
246
      '#title' => t('Fonts'),
247
      '#default_value' => $default_fonts,
248
      '#description' => t('Select the fonts to use for the text in the image CAPTCHA. Apart from the provided defaults, you can also use your own TrueType fonts (filename extension .ttf) by putting them in %fonts_library_general or %fonts_library_specific.',
249
        array(
250
          '%fonts_library_general' => 'sites/all/libraries/fonts',
251
          '%fonts_library_specific' => conf_path() . '/libraries/fonts',
252
        )
253
      ),
254
      '#options' => $available_fonts,
255
      '#attributes' => array('class' => array('image_captcha_admin_fonts_selection')),
256
      '#process' => array('form_process_checkboxes'),
257
    );
258

    
259
    // Font size.
260
    $form['image_captcha_font_size'] = array(
261
      '#type' => 'select',
262
      '#title' => t('Font size'),
263
      '#options' => array(
264
        9 => '9 pt - ' . t('tiny'),
265
        12 => '12 pt - ' . t('small'),
266
        18 => '18 pt',
267
        24 => '24 pt - ' . t('normal'),
268
        30 => '30 pt',
269
        36 => '36 pt - ' . t('large'),
270
        48 => '48 pt',
271
        64 => '64 pt - ' . t('extra large'),
272
      ),
273
      '#default_value' => (int) variable_get('image_captcha_font_size', 30),
274
      '#description' => t('The font size influences the size of the image. Note that larger values make the image generation more CPU intensive.'),
275
    );
276

    
277
  }
278

    
279
  // Character spacing (available for both the TrueType fonts and the builtin font.
280
  $form['image_captcha_font_settings']['image_captcha_character_spacing'] = array(
281
    '#type' => 'select',
282
    '#title' => t('Character spacing'),
283
    '#description' => t('Define the average spacing between characters. Note that larger values make the image generation more CPU intensive.'),
284
    '#default_value' => variable_get('image_captcha_character_spacing', '1.2'),
285
    '#options' => array(
286
      '0.75' => t('tight'),
287
      '1' => t('normal'),
288
      '1.2' => t('wide'),
289
      '1.5' => t('extra wide'),
290
    ),
291
  );
292

    
293
  return $form;
294
}
295

    
296
/**
297
 * Helper function to get fonts from the given directories.
298
 *
299
 * @param array|null $directories
300
 *   an array of directories
301
 *   to recursively search through, if not given, the default
302
 *   directories will be used.
303
 *
304
 * @return array
305
 *   an array of fonts file objects (with fields 'name',
306
 *   'basename' and 'filename'), keyed on the md5 hash of the font
307
 *   path (to have an easy token that can be used in an url
308
 *   without en/decoding issues).
309
 */
310
function _image_captcha_get_available_fonts_from_directories($directories = NULL) {
311
  // If no fonts directories are given: use the default.
312
  if ($directories === NULL) {
313
    $directories = array(
314
      drupal_get_path('module', 'image_captcha') . '/fonts',
315
      'sites/all/libraries/fonts',
316
      conf_path() . '/libraries/fonts',
317
    );
318
  }
319
  // Collect the font information.
320
  $fonts = array();
321
  foreach ($directories as $directory) {
322
    foreach (file_scan_directory($directory, '/\.[tT][tT][fF]$/') as $filename => $font) {
323
      $fonts[md5($filename)] = $font;
324
    }
325
  }
326

    
327
  return $fonts;
328
}
329

    
330
/**
331
 * Validation function for image_captcha configuration form.
332
 */
333
function image_captcha_settings_form_validate($form, &$form_state) {
334
  // Check image_captcha_image_allowed_chars for spaces.
335
  if (preg_match('/\s/', $form_state['values']['image_captcha_image_allowed_chars'])) {
336
    form_set_error('image_captcha_image_allowed_chars', t('The list of characters to use should not contain spaces.'));
337
  }
338

    
339
  if (!isset($form['image_captcha_font_settings']['no_ttf_support'])) {
340
    // Check the selected fonts.
341
    // Filter the image_captcha fonts array to pick out the selected ones.
342
    $fonts = array_filter($form_state['values']['image_captcha_fonts']);
343
    if (count($fonts) < 1) {
344
      form_set_error('image_captcha_fonts', t('You need to select at least one font.'));
345
    }
346
    if ($form_state['values']['image_captcha_fonts']['BUILTIN']) {
347
      // With the built in font, only latin2 characters should be used.
348
      if (preg_match('/[^a-zA-Z0-9]/', $form_state['values']['image_captcha_image_allowed_chars'])) {
349
        form_set_error('image_captcha_image_allowed_chars', t('The built-in font only supports Latin2 characters. Only use "a" to "z" and numbers.'));
350
      }
351
    }
352
    list($readable_fonts, $problem_fonts) = _image_captcha_check_fonts($fonts);
353
    if (count($problem_fonts) > 0) {
354
      form_set_error('image_captcha_fonts', t('The following fonts are not readable: %fonts.', array('%fonts' => implode(', ', $problem_fonts))));
355
    }
356
  }
357

    
358
  // Check color settings.
359
  if (!preg_match('/^#([0-9a-fA-F]{3}){1,2}$/', $form_state['values']['image_captcha_background_color'])) {
360
    form_set_error('image_captcha_background_color', t('Background color is not a valid hexadecimal color value.'));
361
  }
362
  if (!preg_match('/^#([0-9a-fA-F]{3}){1,2}$/', $form_state['values']['image_captcha_foreground_color'])) {
363
    form_set_error('image_captcha_foreground_color', t('Text color is not a valid hexadecimal color value.'));
364
  }
365
}
366

    
367
/**
368
 * Submit function for image_captcha configuration form.
369
 */
370
function image_captcha_settings_form_submit($form, &$form_state) {
371
  if (!isset($form['image_captcha_font_settings']['no_ttf_support'])) {
372
    // Filter the image_captcha fonts array to pick out the selected ones.
373
    $fonts = array_filter($form_state['values']['image_captcha_fonts']);
374
    variable_set('image_captcha_fonts', $fonts);
375
  }
376
}
377

    
378
/**
379
 * Menu handler for font preview request.
380
 */
381
function image_captcha_font_preview($font_token) {
382

    
383
  // Get the font from the given font token.
384
  if ($font_token == 'BUILTIN') {
385
    $font = 'BUILTIN';
386
  }
387
  else {
388
    // Get the mapping of font tokens to font file objects.
389
    $fonts = variable_get('image_captcha_fonts_preview_map_cache', array());
390
    if (!isset($fonts[$font_token])) {
391
      echo ('bad token');
392
      exit();
393
    }
394
    // Get the font path.
395
    $font = $fonts[$font_token]->uri;
396
    // Some sanity checks if the given font is valid.
397
    if (!is_file($font) || !is_readable($font)) {
398
      echo ('bad font');
399
      exit();
400
    }
401
  }
402

    
403
  // Settings of the font preview.
404
  $width = 120;
405
  $text = 'AaBbCc123';
406
  $font_size = 14;
407
  $height = 2 * $font_size;
408

    
409
  // Allocate image resource.
410
  $image = imagecreatetruecolor($width, $height);
411
  if (!$image) {
412
    exit();
413
  }
414
  // White background and black foreground.
415
  $background_color = imagecolorallocate($image, 255, 255, 255);
416
  $color = imagecolorallocate($image, 0, 0, 0);
417
  imagefilledrectangle($image, 0, 0, $width, $height, $background_color);
418

    
419
  // Draw preview text.
420
  if ($font == 'BUILTIN') {
421
    imagestring($image, 5, 1, .5 * $height - 10, $text, $color);
422
  }
423
  else {
424
    imagettftext($image, $font_size, 0, 1, 1.5 * $font_size, $color, realpath($font), $text);
425
  }
426

    
427
  // Set content type.
428
  drupal_add_http_header('Content-Type', 'image/png');
429
  // Dump image data to client.
430
  imagepng($image);
431
  // Release image memory.
432
  imagedestroy($image);
433

    
434
  // Close connection.
435
  exit();
436
}