You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

341 lines
9.3 KiB

7 years ago
  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 - 2017, 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 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://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/user_guide/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
  56. * @param string $img_url URL to the CAPTCHA image folder
  57. * @param string $font_path server path to font
  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. 'font_path' => '',
  69. 'expiration' => 7200,
  70. 'word_length' => 8,
  71. 'font_size' => 16,
  72. 'img_id' => '',
  73. 'pool' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  74. 'colors' => array(
  75. 'background' => array(255,255,255),
  76. 'border' => array(153,102,102),
  77. 'text' => array(204,153,153),
  78. 'grid' => array(255,182,182)
  79. )
  80. );
  81. foreach ($defaults as $key => $val)
  82. {
  83. if ( ! is_array($data) && empty($$key))
  84. {
  85. $$key = $val;
  86. }
  87. else
  88. {
  89. $$key = isset($data[$key]) ? $data[$key] : $val;
  90. }
  91. }
  92. if ($img_path === '' OR $img_url === ''
  93. OR ! is_dir($img_path) OR ! is_really_writable($img_path)
  94. OR ! extension_loaded('gd'))
  95. {
  96. return FALSE;
  97. }
  98. // -----------------------------------
  99. // Remove old images
  100. // -----------------------------------
  101. $now = microtime(TRUE);
  102. $current_dir = @opendir($img_path);
  103. while ($filename = @readdir($current_dir))
  104. {
  105. if (in_array(substr($filename, -4), array('.jpg', '.png'))
  106. && (str_replace(array('.jpg', '.png'), '', $filename) + $expiration) < $now)
  107. {
  108. @unlink($img_path.$filename);
  109. }
  110. }
  111. @closedir($current_dir);
  112. // -----------------------------------
  113. // Do we have a "word" yet?
  114. // -----------------------------------
  115. if (empty($word))
  116. {
  117. $word = '';
  118. $pool_length = strlen($pool);
  119. $rand_max = $pool_length - 1;
  120. // PHP7 or a suitable polyfill
  121. if (function_exists('random_int'))
  122. {
  123. try
  124. {
  125. for ($i = 0; $i < $word_length; $i++)
  126. {
  127. $word .= $pool[random_int(0, $rand_max)];
  128. }
  129. }
  130. catch (Exception $e)
  131. {
  132. // This means fallback to the next possible
  133. // alternative to random_int()
  134. $word = '';
  135. }
  136. }
  137. }
  138. if (empty($word))
  139. {
  140. // Nobody will have a larger character pool than
  141. // 256 characters, but let's handle it just in case ...
  142. //
  143. // No, I do not care that the fallback to mt_rand() can
  144. // handle it; if you trigger this, you're very obviously
  145. // trying to break it. -- Narf
  146. if ($pool_length > 256)
  147. {
  148. return FALSE;
  149. }
  150. // We'll try using the operating system's PRNG first,
  151. // which we can access through CI_Security::get_random_bytes()
  152. $security = get_instance()->security;
  153. // To avoid numerous get_random_bytes() calls, we'll
  154. // just try fetching as much bytes as we need at once.
  155. if (($bytes = $security->get_random_bytes($pool_length)) !== FALSE)
  156. {
  157. $byte_index = $word_index = 0;
  158. while ($word_index < $word_length)
  159. {
  160. // Do we have more random data to use?
  161. // It could be exhausted by previous iterations
  162. // ignoring bytes higher than $rand_max.
  163. if ($byte_index === $pool_length)
  164. {
  165. // No failures should be possible if the
  166. // first get_random_bytes() call didn't
  167. // return FALSE, but still ...
  168. for ($i = 0; $i < 5; $i++)
  169. {
  170. if (($bytes = $security->get_random_bytes($pool_length)) === FALSE)
  171. {
  172. continue;
  173. }
  174. $byte_index = 0;
  175. break;
  176. }
  177. if ($bytes === FALSE)
  178. {
  179. // Sadly, this means fallback to mt_rand()
  180. $word = '';
  181. break;
  182. }
  183. }
  184. list(, $rand_index) = unpack('C', $bytes[$byte_index++]);
  185. if ($rand_index > $rand_max)
  186. {
  187. continue;
  188. }
  189. $word .= $pool[$rand_index];
  190. $word_index++;
  191. }
  192. }
  193. }
  194. if (empty($word))
  195. {
  196. for ($i = 0; $i < $word_length; $i++)
  197. {
  198. $word .= $pool[mt_rand(0, $rand_max)];
  199. }
  200. }
  201. elseif ( ! is_string($word))
  202. {
  203. $word = (string) $word;
  204. }
  205. // -----------------------------------
  206. // Determine angle and position
  207. // -----------------------------------
  208. $length = strlen($word);
  209. $angle = ($length >= 6) ? mt_rand(-($length-6), ($length-6)) : 0;
  210. $x_axis = mt_rand(6, (360/$length)-16);
  211. $y_axis = ($angle >= 0) ? mt_rand($img_height, $img_width) : mt_rand(6, $img_height);
  212. // Create image
  213. // PHP.net recommends imagecreatetruecolor(), but it isn't always available
  214. $im = function_exists('imagecreatetruecolor')
  215. ? imagecreatetruecolor($img_width, $img_height)
  216. : imagecreate($img_width, $img_height);
  217. // -----------------------------------
  218. // Assign colors
  219. // ----------------------------------
  220. is_array($colors) OR $colors = $defaults['colors'];
  221. foreach (array_keys($defaults['colors']) as $key)
  222. {
  223. // Check for a possible missing value
  224. is_array($colors[$key]) OR $colors[$key] = $defaults['colors'][$key];
  225. $colors[$key] = imagecolorallocate($im, $colors[$key][0], $colors[$key][1], $colors[$key][2]);
  226. }
  227. // Create the rectangle
  228. ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $colors['background']);
  229. // -----------------------------------
  230. // Create the spiral pattern
  231. // -----------------------------------
  232. $theta = 1;
  233. $thetac = 7;
  234. $radius = 16;
  235. $circles = 20;
  236. $points = 32;
  237. for ($i = 0, $cp = ($circles * $points) - 1; $i < $cp; $i++)
  238. {
  239. $theta += $thetac;
  240. $rad = $radius * ($i / $points);
  241. $x = ($rad * cos($theta)) + $x_axis;
  242. $y = ($rad * sin($theta)) + $y_axis;
  243. $theta += $thetac;
  244. $rad1 = $radius * (($i + 1) / $points);
  245. $x1 = ($rad1 * cos($theta)) + $x_axis;
  246. $y1 = ($rad1 * sin($theta)) + $y_axis;
  247. imageline($im, $x, $y, $x1, $y1, $colors['grid']);
  248. $theta -= $thetac;
  249. }
  250. // -----------------------------------
  251. // Write the text
  252. // -----------------------------------
  253. $use_font = ($font_path !== '' && file_exists($font_path) && function_exists('imagettftext'));
  254. if ($use_font === FALSE)
  255. {
  256. ($font_size > 5) && $font_size = 5;
  257. $x = mt_rand(0, $img_width / ($length / 3));
  258. $y = 0;
  259. }
  260. else
  261. {
  262. ($font_size > 30) && $font_size = 30;
  263. $x = mt_rand(0, $img_width / ($length / 1.5));
  264. $y = $font_size + 2;
  265. }
  266. for ($i = 0; $i < $length; $i++)
  267. {
  268. if ($use_font === FALSE)
  269. {
  270. $y = mt_rand(0 , $img_height / 2);
  271. imagestring($im, $font_size, $x, $y, $word[$i], $colors['text']);
  272. $x += ($font_size * 2);
  273. }
  274. else
  275. {
  276. $y = mt_rand($img_height / 2, $img_height - 3);
  277. imagettftext($im, $font_size, $angle, $x, $y, $colors['text'], $font_path, $word[$i]);
  278. $x += $font_size;
  279. }
  280. }
  281. // Create the border
  282. imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $colors['border']);
  283. // -----------------------------------
  284. // Generate the image
  285. // -----------------------------------
  286. $img_url = rtrim($img_url, '/').'/';
  287. if (function_exists('imagejpeg'))
  288. {
  289. $img_filename = $now.'.jpg';
  290. imagejpeg($im, $img_path.$img_filename);
  291. }
  292. elseif (function_exists('imagepng'))
  293. {
  294. $img_filename = $now.'.png';
  295. imagepng($im, $img_path.$img_filename);
  296. }
  297. else
  298. {
  299. return FALSE;
  300. }
  301. $img = '<img '.($img_id === '' ? '' : 'id="'.$img_id.'"').' src="'.$img_url.$img_filename.'" style="width: '.$img_width.'; height: '.$img_height .'; border: 0;" alt=" " />';
  302. ImageDestroy($im);
  303. return array('word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename);
  304. }
  305. }