image_captcha.module 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. <?php
  2. /**
  3. * @file
  4. * Implements image CAPTCHA for use with the CAPTCHA module
  5. */
  6. define('IMAGE_CAPTCHA_ALLOWED_CHARACTERS', 'aAbBCdEeFfGHhijKLMmNPQRrSTtWXYZ23456789');
  7. // Setup status flags.
  8. define('IMAGE_CAPTCHA_ERROR_NO_GDLIB', 1);
  9. define('IMAGE_CAPTCHA_ERROR_NO_TTF_SUPPORT', 2);
  10. define('IMAGE_CAPTCHA_ERROR_TTF_FILE_READ_PROBLEM', 4);
  11. define('IMAGE_CAPTCHA_FILE_FORMAT_JPG', 1);
  12. define('IMAGE_CAPTCHA_FILE_FORMAT_PNG', 2);
  13. define('IMAGE_CAPTCHA_FILE_FORMAT_TRANSPARENT_PNG', 3);
  14. /**
  15. * Implements hook_help().
  16. */
  17. function image_captcha_help($path, $arg) {
  18. switch ($path) {
  19. case 'admin/config/people/captcha/image_captcha':
  20. $output = '<p>' . t('The image CAPTCHA is a popular challenge where a random textual code is obfuscated in an image. The image is generated on the fly for each request, which is rather CPU intensive for the server. Be careful with the size and computation related settings.') . '</p>';
  21. return $output;
  22. }
  23. }
  24. /**
  25. * Implements hook_menu().
  26. */
  27. function image_captcha_menu() {
  28. $items = array();
  29. // Add an administration tab for image_captcha.
  30. $items['admin/config/people/captcha/image_captcha'] = array(
  31. 'title' => 'Image CAPTCHA',
  32. 'file' => 'image_captcha.admin.inc',
  33. 'page callback' => 'drupal_get_form',
  34. 'page arguments' => array('image_captcha_settings_form'),
  35. 'access arguments' => array('administer CAPTCHA settings'),
  36. 'type' => MENU_LOCAL_TASK,
  37. );
  38. // Menu path for generating font example.
  39. $items['admin/config/people/captcha/image_captcha/font_preview'] = array(
  40. 'title' => 'Font example',
  41. 'file' => 'image_captcha.admin.inc',
  42. 'page callback' => 'image_captcha_font_preview',
  43. 'access arguments' => array('administer CAPTCHA settings'),
  44. 'type' => MENU_CALLBACK,
  45. );
  46. // Callback for generating an image.
  47. $items['image_captcha'] = array(
  48. 'file' => 'image_captcha.user.inc',
  49. 'page callback' => 'image_captcha_image',
  50. 'access callback' => TRUE,
  51. 'type' => MENU_CALLBACK,
  52. );
  53. return $items;
  54. }
  55. /**
  56. * Helper function for getting the fonts to use in the image CAPTCHA.
  57. *
  58. * @return array
  59. * a list of font paths.
  60. */
  61. function _image_captcha_get_enabled_fonts() {
  62. if (IMAGE_CAPTCHA_ERROR_NO_TTF_SUPPORT & _image_captcha_check_setup(FALSE)) {
  63. return array('BUILTIN');
  64. }
  65. else {
  66. $default = array(
  67. drupal_get_path('module', 'image_captcha') . '/fonts/Tesox/tesox.ttf',
  68. drupal_get_path('module', 'image_captcha') . '/fonts/Tuffy/Tuffy.ttf',
  69. );
  70. return variable_get('image_captcha_fonts', $default);
  71. }
  72. }
  73. /**
  74. * Helper function for checking if the specified fonts are available.
  75. *
  76. * @param array $fonts
  77. * paths of fonts to check.
  78. *
  79. * @return array
  80. * list($readable_fonts, $problem_fonts)
  81. */
  82. function _image_captcha_check_fonts($fonts) {
  83. $readable_fonts = array();
  84. $problem_fonts = array();
  85. foreach ($fonts as $font) {
  86. if ($font != 'BUILTIN' && (!is_file($font) || !is_readable($font))) {
  87. $problem_fonts[] = $font;
  88. }
  89. else {
  90. $readable_fonts[] = $font;
  91. }
  92. }
  93. return array($readable_fonts, $problem_fonts);
  94. }
  95. /**
  96. * Helper function for splitting an utf8 string correctly in characters.
  97. *
  98. * Assumes the given utf8 string is well formed.
  99. * See http://en.wikipedia.org/wiki/Utf8 for more info
  100. */
  101. function _image_captcha_utf8_split($str) {
  102. $characters = array();
  103. $len = strlen($str);
  104. for ($i = 0; $i < $len;) {
  105. $chr = ord($str[$i]);
  106. // One byte character (0zzzzzzz)
  107. if (($chr & 0x80) == 0x00) {
  108. $width = 1;
  109. }
  110. else {
  111. // Two byte character (first byte: 110yyyyy)
  112. if (($chr & 0xE0) == 0xC0) {
  113. $width = 2;
  114. }
  115. // Three byte character (first byte: 1110xxxx)
  116. elseif (($chr & 0xF0) == 0xE0) {
  117. $width = 3;
  118. }
  119. // Four byte character (first byte: 11110www)
  120. elseif (($chr & 0xF8) == 0xF0) {
  121. $width = 4;
  122. }
  123. else {
  124. watchdog('CAPTCHA', 'Encountered an illegal byte while splitting an utf8 string in characters.', array(), WATCHDOG_ERROR);
  125. return $characters;
  126. }
  127. }
  128. $characters[] = substr($str, $i, $width);
  129. $i += $width;
  130. }
  131. return $characters;
  132. }
  133. /**
  134. * Helper function for checking the setup of the Image CAPTCHA.
  135. *
  136. * The image CAPTCHA requires at least the GD PHP library.
  137. * Support for TTF is recommended and the enabled
  138. * font files should be readable.
  139. * This functions checks these things.
  140. *
  141. * @param bool $check_fonts
  142. * whether or not the enabled fonts should be checked.
  143. *
  144. * @return int
  145. * status code: bitwise 'OR' of status flags like
  146. * IMAGE_CAPTCHA_ERROR_NO_GDLIB, IMAGE_CAPTCHA_ERROR_NO_TTF_SUPPORT,
  147. * IMAGE_CAPTCHA_ERROR_TTF_FILE_READ_PROBLEM.
  148. */
  149. function _image_captcha_check_setup($check_fonts = TRUE) {
  150. // Start clean.
  151. $status = 0;
  152. // Check if we can use the GD library.
  153. // We need at least the imagepng function (for font previews on the settings page).
  154. // Note that the imagejpg function is optionally also used, but not required.
  155. if (!function_exists('imagepng')) {
  156. $status = $status | IMAGE_CAPTCHA_ERROR_NO_GDLIB;
  157. }
  158. if (!function_exists('imagettftext')) {
  159. $status = $status | IMAGE_CAPTCHA_ERROR_NO_TTF_SUPPORT;
  160. }
  161. if ($check_fonts) {
  162. // Check availability of enabled fonts.
  163. $fonts = _image_captcha_get_enabled_fonts();
  164. list($readable_fonts, $problem_fonts) = _image_captcha_check_fonts($fonts);
  165. if (count($problem_fonts) != 0) {
  166. $status = $status | IMAGE_CAPTCHA_ERROR_TTF_FILE_READ_PROBLEM;
  167. }
  168. }
  169. return $status;
  170. }
  171. /**
  172. * Helper function for calculating image height and width based on given code and current font/spacing settings.
  173. *
  174. * @return array
  175. * array($width, $heigh)
  176. */
  177. function _image_captcha_image_size($code) {
  178. // Get settings.
  179. $font_size = (int) variable_get('image_captcha_font_size', 30);
  180. $character_spacing = (float) variable_get('image_captcha_character_spacing', '1.2');
  181. $characters = _image_captcha_utf8_split($code);
  182. $character_quantity = count($characters);
  183. // Calculate height and width.
  184. $width = $character_spacing * $font_size * $character_quantity;
  185. $height = 2 * $font_size;
  186. return array($width, $height);
  187. }
  188. /**
  189. * Implements hook_captcha().
  190. */
  191. function image_captcha_captcha($op, $captcha_type = '', $captcha_sid = NULL) {
  192. switch ($op) {
  193. case 'list':
  194. // Only offer the image CAPTCHA if it is possible to generate an image on this setup.
  195. if (!(_image_captcha_check_setup() & IMAGE_CAPTCHA_ERROR_NO_GDLIB)) {
  196. return array('Image');
  197. }
  198. else {
  199. return array();
  200. }
  201. break;
  202. case 'generate':
  203. if ($captcha_type == 'Image') {
  204. // In maintenance mode, the image CAPTCHA does not work because the request
  205. // for the image itself won't succeed (only ?q=user is permitted for
  206. // unauthenticated users). We fall back to the Math CAPTCHA in that case.
  207. global $user;
  208. if (variable_get('maintenance_mode', 0) && $user->uid == 0) {
  209. return captcha_captcha('generate', 'Math');
  210. }
  211. // Generate a CAPTCHA code.
  212. $allowed_chars = _image_captcha_utf8_split(variable_get('image_captcha_image_allowed_chars', IMAGE_CAPTCHA_ALLOWED_CHARACTERS));
  213. $code_length = (int) variable_get('image_captcha_code_length', 5);
  214. $code = '';
  215. for ($i = 0; $i < $code_length; $i++) {
  216. $code .= $allowed_chars[array_rand($allowed_chars)];
  217. }
  218. // Build the result to return.
  219. $result = array();
  220. $result['solution'] = $code;
  221. // Generate image source URL (add timestamp to avoid problems with
  222. // client side caching: subsequent images of the same CAPTCHA session
  223. // have the same URL, but should display a different code).
  224. $options = array(
  225. 'query' => array(
  226. 'sid' => $captcha_sid,
  227. 'ts' => REQUEST_TIME,
  228. ),
  229. );
  230. $img_src = drupal_strip_dangerous_protocols(url("image_captcha", $options));
  231. list($width, $height) = _image_captcha_image_size($code);
  232. $result['form']['captcha_image'] = array(
  233. '#theme' => 'image',
  234. '#weight' => -2,
  235. '#path' => $img_src,
  236. '#width' => $width,
  237. '#height' => $height,
  238. '#title' => t('Image CAPTCHA'),
  239. '#alt' => t('Image CAPTCHA'),
  240. );
  241. $result['form']['captcha_response'] = array(
  242. '#type' => 'textfield',
  243. '#title' => t('What code is in the image?'),
  244. '#description' => t('Enter the characters shown in the image.'),
  245. '#weight' => 0,
  246. '#required' => TRUE,
  247. '#size' => 15,
  248. );
  249. // Handle the case insensitive validation option combined with ignoring spaces.
  250. switch (variable_get('captcha_default_validation', CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE)) {
  251. case CAPTCHA_DEFAULT_VALIDATION_CASE_SENSITIVE:
  252. $result['captcha_validate'] = 'captcha_validate_ignore_spaces';
  253. break;
  254. case CAPTCHA_DEFAULT_VALIDATION_CASE_INSENSITIVE:
  255. $result['captcha_validate'] = 'captcha_validate_case_insensitive_ignore_spaces';
  256. break;
  257. }
  258. return $result;
  259. }
  260. break;
  261. }
  262. }