PageRenderTime 40ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/system/helpers/captcha_helper.php

http://github.com/EllisLab/CodeIgniter
PHP | 384 lines | 237 code | 43 blank | 104 comment | 36 complexity | 08b2e492c3155686c889ac0248e093e2 MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * CodeIgniter CAPTCHA Helper
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Helpers
  44. * @category Helpers
  45. * @author EllisLab Dev Team
  46. * @link https://codeigniter.com/userguide3/helpers/captcha_helper.html
  47. */
  48. // ------------------------------------------------------------------------
  49. if ( ! function_exists('create_captcha'))
  50. {
  51. /**
  52. * Create CAPTCHA
  53. *
  54. * @param array $data Data for the CAPTCHA
  55. * @param string $img_path Path to create the image in (deprecated)
  56. * @param string $img_url URL to the CAPTCHA image folder (deprecated)
  57. * @param string $font_path Server path to font (deprecated)
  58. * @return string
  59. */
  60. function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
  61. {
  62. $defaults = array(
  63. 'word' => '',
  64. 'img_path' => '',
  65. 'img_url' => '',
  66. 'img_width' => '150',
  67. 'img_height' => '30',
  68. 'img_alt' => 'captcha',
  69. 'img_class' => '',
  70. 'font_path' => '',
  71. 'font_size' => 16,
  72. 'expiration' => 7200,
  73. 'word_length' => 8,
  74. 'img_id' => '',
  75. 'pool' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  76. 'colors' => array(
  77. 'background' => array(255,255,255),
  78. 'border' => array(153,102,102),
  79. 'text' => array(204,153,153),
  80. 'grid' => array(255,182,182)
  81. )
  82. );
  83. $now = microtime(TRUE);
  84. foreach ($defaults as $key => $val)
  85. {
  86. if ( ! is_array($data) && empty($$key))
  87. {
  88. $$key = $val;
  89. }
  90. else
  91. {
  92. $$key = isset($data[$key]) ? $data[$key] : $val;
  93. }
  94. }
  95. if ( ! extension_loaded('gd'))
  96. {
  97. log_message('error', 'create_captcha(): GD extension is not loaded.');
  98. return FALSE;
  99. }
  100. if ($img_path === '' OR $img_url === '')
  101. {
  102. log_message('error', 'create_captcha(): $img_path and $img_url are required.');
  103. return FALSE;
  104. }
  105. if ( ! is_dir($img_path) OR ! is_really_writable($img_path))
  106. {
  107. log_message('error', "create_captcha(): '{$img_path}' is not a dir, nor is it writable.");
  108. return FALSE;
  109. }
  110. if ($img_url !== '' OR $img_path !== '')
  111. {
  112. if ($img_path === '' OR $img_url === '')
  113. {
  114. log_message('error', 'create_captcha(): $img_path and $img_url are required.');
  115. return FALSE;
  116. }
  117. if ( ! is_dir($img_path) OR ! is_really_writable($img_path))
  118. {
  119. log_message('error', "create_captcha(): '{$img_path}' is not a dir, nor is it writable.");
  120. return FALSE;
  121. }
  122. /**
  123. * Remove old images
  124. */
  125. $current_dir = @opendir($img_path);
  126. while ($filename = @readdir($current_dir))
  127. {
  128. if (preg_match('#^(?<ts>\d{10})\.png$#', $filename, $match) && ($match['ts'] + $expiration) < $now)
  129. {
  130. @unlink($img_path.$filename);
  131. }
  132. }
  133. @closedir($current_dir);
  134. // This variable will later be used later to determine whether we write to disk or output a data:image URI
  135. $img_filename = $now.'.png';
  136. }
  137. else
  138. {
  139. $img_filename = NULL;
  140. }
  141. // -----------------------------------
  142. // Do we have a "word" yet?
  143. // -----------------------------------
  144. if (empty($word))
  145. {
  146. $word = '';
  147. $pool_length = strlen($pool);
  148. $rand_max = $pool_length - 1;
  149. // PHP7 or a suitable polyfill
  150. if (function_exists('random_int'))
  151. {
  152. try
  153. {
  154. for ($i = 0; $i < $word_length; $i++)
  155. {
  156. $word .= $pool[random_int(0, $rand_max)];
  157. }
  158. }
  159. catch (Exception $e)
  160. {
  161. // This means fallback to the next possible
  162. // alternative to random_int()
  163. $word = '';
  164. }
  165. }
  166. }
  167. if (empty($word))
  168. {
  169. // Nobody will have a larger character pool than
  170. // 256 characters, but let's handle it just in case ...
  171. //
  172. // No, I do not care that the fallback to mt_rand() can
  173. // handle it; if you trigger this, you're very obviously
  174. // trying to break it. -- Narf
  175. if ($pool_length > 256)
  176. {
  177. return FALSE;
  178. }
  179. // We'll try using the operating system's PRNG first,
  180. // which we can access through CI_Security::get_random_bytes()
  181. $security = get_instance()->security;
  182. // To avoid numerous get_random_bytes() calls, we'll
  183. // just try fetching as much bytes as we need at once.
  184. if (($bytes = $security->get_random_bytes($pool_length)) !== FALSE)
  185. {
  186. $byte_index = $word_index = 0;
  187. while ($word_index < $word_length)
  188. {
  189. // Do we have more random data to use?
  190. // It could be exhausted by previous iterations
  191. // ignoring bytes higher than $rand_max.
  192. if ($byte_index === $pool_length)
  193. {
  194. // No failures should be possible if the
  195. // first get_random_bytes() call didn't
  196. // return FALSE, but still ...
  197. for ($i = 0; $i < 5; $i++)
  198. {
  199. if (($bytes = $security->get_random_bytes($pool_length)) === FALSE)
  200. {
  201. continue;
  202. }
  203. $byte_index = 0;
  204. break;
  205. }
  206. if ($bytes === FALSE)
  207. {
  208. // Sadly, this means fallback to mt_rand()
  209. $word = '';
  210. break;
  211. }
  212. }
  213. list(, $rand_index) = unpack('C', $bytes[$byte_index++]);
  214. if ($rand_index > $rand_max)
  215. {
  216. continue;
  217. }
  218. $word .= $pool[$rand_index];
  219. $word_index++;
  220. }
  221. }
  222. }
  223. if (empty($word))
  224. {
  225. for ($i = 0; $i < $word_length; $i++)
  226. {
  227. $word .= $pool[mt_rand(0, $rand_max)];
  228. }
  229. }
  230. elseif ( ! is_string($word))
  231. {
  232. $word = (string) $word;
  233. }
  234. // -----------------------------------
  235. // Determine angle and position
  236. // -----------------------------------
  237. $length = strlen($word);
  238. $angle = ($length >= 6) ? mt_rand(-($length - 6), ($length - 6)) : 0;
  239. $x_axis = mt_rand(6, (360 / $length)-16);
  240. $y_axis = ($angle >= 0) ? mt_rand($img_height, $img_width) : mt_rand(6, $img_height);
  241. // Create image
  242. // PHP.net recommends imagecreatetruecolor(), but it isn't always available
  243. $im = function_exists('imagecreatetruecolor')
  244. ? imagecreatetruecolor($img_width, $img_height)
  245. : imagecreate($img_width, $img_height);
  246. // -----------------------------------
  247. // Assign colors
  248. // ----------------------------------
  249. is_array($colors) OR $colors = $defaults['colors'];
  250. foreach (array_keys($defaults['colors']) as $key)
  251. {
  252. // Check for a possible missing value
  253. is_array($colors[$key]) OR $colors[$key] = $defaults['colors'][$key];
  254. $colors[$key] = imagecolorallocate($im, $colors[$key][0], $colors[$key][1], $colors[$key][2]);
  255. }
  256. // Create the rectangle
  257. ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $colors['background']);
  258. // -----------------------------------
  259. // Create the spiral pattern
  260. // -----------------------------------
  261. $theta = 1;
  262. $thetac = 7;
  263. $radius = 16;
  264. $circles = 20;
  265. $points = 32;
  266. for ($i = 0, $cp = ($circles * $points) - 1; $i < $cp; $i++)
  267. {
  268. $theta += $thetac;
  269. $rad = $radius * ($i / $points);
  270. $x = ($rad * cos($theta)) + $x_axis;
  271. $y = ($rad * sin($theta)) + $y_axis;
  272. $theta += $thetac;
  273. $rad1 = $radius * (($i + 1) / $points);
  274. $x1 = ($rad1 * cos($theta)) + $x_axis;
  275. $y1 = ($rad1 * sin($theta)) + $y_axis;
  276. imageline($im, $x, $y, $x1, $y1, $colors['grid']);
  277. $theta -= $thetac;
  278. }
  279. // -----------------------------------
  280. // Write the text
  281. // -----------------------------------
  282. $use_font = ($font_path !== '' && file_exists($font_path) && function_exists('imagettftext'));
  283. if ($use_font === FALSE)
  284. {
  285. ($font_size > 5) && $font_size = 5;
  286. $x = mt_rand(0, $img_width / ($length / 3));
  287. $y = 0;
  288. }
  289. else
  290. {
  291. ($font_size > 30) && $font_size = 30;
  292. $x = mt_rand(0, $img_width / ($length / 1.5));
  293. $y = $font_size + 2;
  294. }
  295. for ($i = 0; $i < $length; $i++)
  296. {
  297. if ($use_font === FALSE)
  298. {
  299. $y = mt_rand(0 , $img_height / 2);
  300. imagestring($im, $font_size, $x, $y, $word[$i], $colors['text']);
  301. $x += ($font_size * 2);
  302. }
  303. else
  304. {
  305. $y = mt_rand($img_height / 2, $img_height - 3);
  306. imagettftext($im, $font_size, $angle, $x, $y, $colors['text'], $font_path, $word[$i]);
  307. $x += $font_size;
  308. }
  309. }
  310. // Create the border
  311. imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $colors['border']);
  312. // -----------------------------------
  313. // Generate the image
  314. // -----------------------------------
  315. if (isset($img_filename))
  316. {
  317. $img_src = rtrim($img_url, '/').'/'.$img_filename;
  318. imagepng($im, $img_path.$img_filename);
  319. }
  320. else
  321. {
  322. // I don't see an easier way to get the image contents without writing to file
  323. $buffer = fopen('php://memory', 'wb+');
  324. imagepng($im, $buffer);
  325. rewind($buffer);
  326. $img_src = '';
  327. // fread() will return an empty string (not FALSE) after the entire contents are read
  328. while (strlen($read = fread($buffer, 4096)))
  329. {
  330. $img_src .= $read;
  331. }
  332. fclose($buffer);
  333. $img_src = 'data:image/png;base64,'.base64_encode($img_src);
  334. }
  335. $img_class = trim($img_class);
  336. $img_class = (bool) strlen($img_class) ? 'class="'.$img_class.'" ' : '';
  337. $img = '<img '.($img_id === '' ? '' : 'id="'.$img_id.'"').' src="'.$img_src.'" style="width: '.$img_width.'px; height: '.$img_height .'px; border: 0;" '.$img_class.'alt="'.$img_alt.'" />';
  338. ImageDestroy($im);
  339. return array('word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename);
  340. }
  341. }