DefaultModel.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Captcha\Model;
  7. use Magento\Captcha\Helper\Data;
  8. /**
  9. * Implementation of \Zend\Captcha\Image
  10. *
  11. * @api
  12. * @since 100.0.2
  13. */
  14. class DefaultModel extends \Zend\Captcha\Image implements \Magento\Captcha\Model\CaptchaInterface
  15. {
  16. /**
  17. * Key in session for captcha code
  18. */
  19. const SESSION_WORD = 'word';
  20. /**
  21. * Min captcha lengths default value
  22. */
  23. const DEFAULT_WORD_LENGTH_FROM = 3;
  24. /**
  25. * Max captcha lengths default value
  26. */
  27. const DEFAULT_WORD_LENGTH_TO = 5;
  28. /**
  29. * @var Data
  30. * @since 100.2.0
  31. */
  32. protected $captchaData;
  33. /**
  34. * Captcha expire time
  35. * @var int
  36. * @since 100.2.0
  37. */
  38. protected $expiration;
  39. /**
  40. * Override default value to prevent a captcha cut off
  41. * @var int
  42. * @see \Zend\Captcha\Image::$fsize
  43. * @since 100.2.0
  44. */
  45. protected $fsize = 22;
  46. /**
  47. * Captcha form id
  48. * @var string
  49. * @since 100.2.0
  50. */
  51. protected $formId;
  52. /**
  53. * @var \Magento\Captcha\Model\ResourceModel\LogFactory
  54. * @since 100.2.0
  55. */
  56. protected $resLogFactory;
  57. /**
  58. * Overrides parent parameter as session comes in constructor.
  59. *
  60. * @var bool
  61. * @since 100.2.0
  62. */
  63. protected $keepSession = true;
  64. /**
  65. * @var \Magento\Framework\Session\SessionManagerInterface
  66. * @since 100.2.0
  67. */
  68. protected $session;
  69. /**
  70. * @var string
  71. */
  72. private $words;
  73. /**
  74. * @param \Magento\Framework\Session\SessionManagerInterface $session
  75. * @param \Magento\Captcha\Helper\Data $captchaData
  76. * @param ResourceModel\LogFactory $resLogFactory
  77. * @param string $formId
  78. * @throws \Zend\Captcha\Exception\ExtensionNotLoadedException
  79. */
  80. public function __construct(
  81. \Magento\Framework\Session\SessionManagerInterface $session,
  82. \Magento\Captcha\Helper\Data $captchaData,
  83. \Magento\Captcha\Model\ResourceModel\LogFactory $resLogFactory,
  84. $formId
  85. ) {
  86. parent::__construct();
  87. $this->session = $session;
  88. $this->captchaData = $captchaData;
  89. $this->resLogFactory = $resLogFactory;
  90. $this->formId = $formId;
  91. }
  92. /**
  93. * Returns key with respect of current form ID
  94. *
  95. * @param string $key
  96. * @return string
  97. */
  98. private function getFormIdKey($key)
  99. {
  100. return $this->formId . '_' . $key;
  101. }
  102. /**
  103. * Get Block Name
  104. *
  105. * @return string
  106. */
  107. public function getBlockName()
  108. {
  109. return \Magento\Captcha\Block\Captcha\DefaultCaptcha::class;
  110. }
  111. /**
  112. * Whether captcha is required to be inserted to this form
  113. *
  114. * @param null|string $login
  115. * @return bool
  116. */
  117. public function isRequired($login = null)
  118. {
  119. if (($this->isUserAuth()
  120. && !$this->isShownToLoggedInUser())
  121. || !$this->isEnabled()
  122. || !in_array(
  123. $this->formId,
  124. $this->getTargetForms()
  125. )
  126. ) {
  127. return false;
  128. }
  129. return $this->isShowAlways()
  130. || $this->isOverLimitAttempts($login)
  131. || $this->session->getData($this->getFormIdKey('show_captcha'));
  132. }
  133. /**
  134. * Check if CAPTCHA has to be shown to logged in user on this form
  135. *
  136. * @return bool
  137. */
  138. public function isShownToLoggedInUser()
  139. {
  140. $forms = (array)$this->captchaData->getConfig('shown_to_logged_in_user');
  141. foreach ($forms as $formId => $isShownToLoggedIn) {
  142. if ($isShownToLoggedIn && $this->formId == $formId) {
  143. return true;
  144. }
  145. }
  146. return false;
  147. }
  148. /**
  149. * Check is over limit attempts
  150. *
  151. * @param string $login
  152. * @return bool
  153. */
  154. private function isOverLimitAttempts($login)
  155. {
  156. return $this->isOverLimitIpAttempt() || $this->isOverLimitLoginAttempts($login);
  157. }
  158. /**
  159. * Returns number of allowed attempts for same login
  160. *
  161. * @return int
  162. */
  163. private function getAllowedAttemptsForSameLogin()
  164. {
  165. return (int)$this->captchaData->getConfig('failed_attempts_login');
  166. }
  167. /**
  168. * Returns number of allowed attempts from same IP
  169. *
  170. * @return int
  171. */
  172. private function getAllowedAttemptsFromSameIp()
  173. {
  174. return (int)$this->captchaData->getConfig('failed_attempts_ip');
  175. }
  176. /**
  177. * Check is over limit saved attempts from one ip
  178. *
  179. * @return bool
  180. */
  181. private function isOverLimitIpAttempt()
  182. {
  183. $countAttemptsByIp = $this->getResourceModel()->countAttemptsByRemoteAddress();
  184. return $countAttemptsByIp >= $this->getAllowedAttemptsFromSameIp();
  185. }
  186. /**
  187. * Is Over Limit Login Attempts
  188. *
  189. * @param string $login
  190. * @return bool
  191. */
  192. private function isOverLimitLoginAttempts($login)
  193. {
  194. if ($login != false) {
  195. $countAttemptsByLogin = $this->getResourceModel()->countAttemptsByUserLogin($login);
  196. return $countAttemptsByLogin >= $this->getAllowedAttemptsForSameLogin();
  197. }
  198. return false;
  199. }
  200. /**
  201. * Check is user auth
  202. *
  203. * @return bool
  204. */
  205. private function isUserAuth()
  206. {
  207. return $this->session->isLoggedIn();
  208. }
  209. /**
  210. * Whether to respect case while checking the answer
  211. *
  212. * @return bool
  213. */
  214. public function isCaseSensitive()
  215. {
  216. return (string)$this->captchaData->getConfig('case_sensitive');
  217. }
  218. /**
  219. * Get font to use when generating captcha
  220. *
  221. * @return string
  222. */
  223. public function getFont()
  224. {
  225. $font = (string)$this->captchaData->getConfig('font');
  226. $fonts = $this->captchaData->getFonts();
  227. if (isset($fonts[$font])) {
  228. $fontPath = $fonts[$font]['path'];
  229. } else {
  230. $fontData = array_shift($fonts);
  231. $fontPath = $fontData['path'];
  232. }
  233. return $fontPath;
  234. }
  235. /**
  236. * After this time isCorrect() is going to return FALSE even if word was guessed correctly
  237. *
  238. * @return int
  239. */
  240. public function getExpiration()
  241. {
  242. if (!$this->expiration) {
  243. /**
  244. * as "timeout" configuration parameter specifies timeout in minutes - we multiply it on 60 to set
  245. * expiration in seconds
  246. */
  247. $this->expiration = (int)$this->captchaData->getConfig('timeout') * 60;
  248. }
  249. return $this->expiration;
  250. }
  251. /**
  252. * Get timeout for session token
  253. *
  254. * @return int
  255. */
  256. public function getTimeout()
  257. {
  258. return $this->getExpiration();
  259. }
  260. /**
  261. * Get captcha image directory
  262. *
  263. * @return string
  264. */
  265. public function getImgDir()
  266. {
  267. return $this->captchaData->getImgDir();
  268. }
  269. /**
  270. * Get captcha image base URL
  271. *
  272. * @return string
  273. */
  274. public function getImgUrl()
  275. {
  276. return $this->captchaData->getImgUrl();
  277. }
  278. /**
  279. * Checks whether captcha was guessed correctly by user
  280. *
  281. * @param string $word
  282. * @return bool
  283. */
  284. public function isCorrect($word)
  285. {
  286. $storedWords = $this->getWords();
  287. $this->clearWord();
  288. if (!$word || !$storedWords) {
  289. return false;
  290. }
  291. if (!$this->isCaseSensitive()) {
  292. $storedWords = strtolower($storedWords);
  293. $word = strtolower($word);
  294. }
  295. return in_array($word, explode(',', $storedWords));
  296. }
  297. /**
  298. * Return full URL to captcha image
  299. *
  300. * @return string
  301. */
  302. public function getImgSrc()
  303. {
  304. return $this->getImgUrl() . $this->getId() . $this->getSuffix();
  305. }
  306. /**
  307. * Log attempt
  308. *
  309. * @param string $login
  310. * @return $this
  311. */
  312. public function logAttempt($login)
  313. {
  314. if ($this->isEnabled() && in_array($this->formId, $this->getTargetForms())) {
  315. $this->getResourceModel()->logAttempt($login);
  316. if ($this->isOverLimitLoginAttempts($login)) {
  317. $this->setShowCaptchaInSession(true);
  318. }
  319. }
  320. return $this;
  321. }
  322. /**
  323. * Set show_captcha flag in session
  324. *
  325. * @param bool $value
  326. * @return void
  327. * @since 100.1.0
  328. */
  329. public function setShowCaptchaInSession($value = true)
  330. {
  331. if ($value !== true) {
  332. $value = false;
  333. }
  334. $this->session->setData($this->getFormIdKey('show_captcha'), $value);
  335. }
  336. /**
  337. * Generate word used for captcha render
  338. *
  339. * @return string
  340. * @throws \Magento\Framework\Exception\LocalizedException
  341. * @since 100.2.0
  342. */
  343. protected function generateWord()
  344. {
  345. $word = '';
  346. $symbols = $this->getSymbols();
  347. $wordLen = $this->getWordLen();
  348. for ($i = 0; $i < $wordLen; $i++) {
  349. $word .= $symbols[array_rand($symbols)];
  350. }
  351. return $word;
  352. }
  353. /**
  354. * Get symbols array to use for word generation
  355. *
  356. * @return array
  357. */
  358. private function getSymbols()
  359. {
  360. return str_split((string)$this->captchaData->getConfig('symbols'));
  361. }
  362. /**
  363. * Returns length for generating captcha word. This value may be dynamic.
  364. *
  365. * @return int
  366. * @throws \Magento\Framework\Exception\LocalizedException
  367. * @since 100.2.0
  368. */
  369. public function getWordLen()
  370. {
  371. $from = 0;
  372. $to = 0;
  373. $length = (string)$this->captchaData->getConfig('length');
  374. if (!is_numeric($length)) {
  375. if (preg_match('/(\d+)-(\d+)/', $length, $matches)) {
  376. $from = (int)$matches[1];
  377. $to = (int)$matches[2];
  378. }
  379. } else {
  380. $from = (int)$length;
  381. $to = (int)$length;
  382. }
  383. if ($to < $from || $from < 1 || $to < 1) {
  384. $from = self::DEFAULT_WORD_LENGTH_FROM;
  385. $to = self::DEFAULT_WORD_LENGTH_TO;
  386. }
  387. return \Magento\Framework\Math\Random::getRandomNumber($from, $to);
  388. }
  389. /**
  390. * Whether to show captcha for this form every time
  391. *
  392. * @return bool
  393. */
  394. private function isShowAlways()
  395. {
  396. $captchaMode = (string)$this->captchaData->getConfig('mode');
  397. if ($captchaMode === Data::MODE_ALWAYS) {
  398. return true;
  399. }
  400. if ($captchaMode === Data::MODE_AFTER_FAIL
  401. && $this->getAllowedAttemptsForSameLogin() === 0
  402. ) {
  403. return true;
  404. }
  405. $alwaysFor = $this->captchaData->getConfig('always_for');
  406. foreach ($alwaysFor as $nodeFormId => $isAlwaysFor) {
  407. if ($isAlwaysFor && $this->formId == $nodeFormId) {
  408. return true;
  409. }
  410. }
  411. return false;
  412. }
  413. /**
  414. * Whether captcha is enabled at this area
  415. *
  416. * @return bool
  417. */
  418. private function isEnabled()
  419. {
  420. return (string)$this->captchaData->getConfig('enable');
  421. }
  422. /**
  423. * Retrieve list of forms where captcha must be shown
  424. *
  425. * For frontend this list is based on current website
  426. *
  427. * @return array
  428. */
  429. private function getTargetForms()
  430. {
  431. $formsString = (string)$this->captchaData->getConfig('forms');
  432. return explode(',', $formsString);
  433. }
  434. /**
  435. * Get captcha word
  436. *
  437. * @return string|null
  438. */
  439. public function getWord()
  440. {
  441. $sessionData = $this->session->getData($this->getFormIdKey(self::SESSION_WORD));
  442. return time() < $sessionData['expires'] ? $sessionData['data'] : null;
  443. }
  444. /**
  445. * Get captcha words
  446. *
  447. * @return string|null
  448. */
  449. private function getWords()
  450. {
  451. $sessionData = $this->session->getData($this->getFormIdKey(self::SESSION_WORD));
  452. return time() < $sessionData['expires'] ? $sessionData['words'] : null;
  453. }
  454. /**
  455. * Set captcha word
  456. *
  457. * @param string $word
  458. * @return $this
  459. * @since 100.2.0
  460. */
  461. protected function setWord($word)
  462. {
  463. $this->words = $this->words ? $this->words . ',' . $word : $word;
  464. $this->session->setData(
  465. $this->getFormIdKey(self::SESSION_WORD),
  466. ['data' => $word, 'words' => $this->words, 'expires' => time() + $this->getTimeout()]
  467. );
  468. $this->word = $word;
  469. return $this;
  470. }
  471. /**
  472. * Set captcha word
  473. *
  474. * @return $this
  475. */
  476. private function clearWord()
  477. {
  478. $this->session->unsetData($this->getFormIdKey(self::SESSION_WORD));
  479. $this->word = null;
  480. return $this;
  481. }
  482. /**
  483. * Override function to generate less curly captcha that will not cut off
  484. *
  485. * @see \Zend\Captcha\Image::_randomSize()
  486. * @return int
  487. * @throws \Magento\Framework\Exception\LocalizedException
  488. * @since 100.2.0
  489. */
  490. protected function randomSize()
  491. {
  492. return \Magento\Framework\Math\Random::getRandomNumber(280, 300) / 100;
  493. }
  494. /**
  495. * Overlap of the parent method
  496. *
  497. * @return void
  498. *
  499. * Now deleting old captcha images make crontab script
  500. * @see \Magento\Captcha\Cron\DeleteExpiredImages::execute
  501. *
  502. * Added SuppressWarnings since this method is declared in parent class and we can not use other method name.
  503. * @SuppressWarnings(PHPMD.ShortMethodName)
  504. * @since 100.2.0
  505. */
  506. protected function gc()
  507. {
  508. //do nothing
  509. }
  510. /**
  511. * Get resource model
  512. *
  513. * @return \Magento\Captcha\Model\ResourceModel\Log
  514. */
  515. private function getResourceModel()
  516. {
  517. return $this->resLogFactory->create();
  518. }
  519. }