ReCaptcha.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. /**
  3. * This is a PHP library that handles calling reCAPTCHA.
  4. *
  5. * @copyright Copyright (c) 2015, Google Inc.
  6. * @link https://www.google.com/recaptcha
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. namespace ReCaptcha;
  27. /**
  28. * reCAPTCHA client.
  29. */
  30. class ReCaptcha
  31. {
  32. /**
  33. * Version of this client library.
  34. * @const string
  35. */
  36. const VERSION = 'php_1.2.1';
  37. /**
  38. * URL for reCAPTCHA sitevrerify API
  39. * @const string
  40. */
  41. const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
  42. /**
  43. * Invalid JSON received
  44. * @const string
  45. */
  46. const E_INVALID_JSON = 'invalid-json';
  47. /**
  48. * Could not connect to service
  49. * @const string
  50. */
  51. const E_CONNECTION_FAILED = 'connection-failed';
  52. /**
  53. * Did not receive a 200 from the service
  54. * @const string
  55. */
  56. const E_BAD_RESPONSE = 'bad-response';
  57. /**
  58. * Not a success, but no error codes received!
  59. * @const string
  60. */
  61. const E_UNKNOWN_ERROR = 'unknown-error';
  62. /**
  63. * ReCAPTCHA response not provided
  64. * @const string
  65. */
  66. const E_MISSING_INPUT_RESPONSE = 'missing-input-response';
  67. /**
  68. * Expected hostname did not match
  69. * @const string
  70. */
  71. const E_HOSTNAME_MISMATCH = 'hostname-mismatch';
  72. /**
  73. * Expected APK package name did not match
  74. * @const string
  75. */
  76. const E_APK_PACKAGE_NAME_MISMATCH = 'apk_package_name-mismatch';
  77. /**
  78. * Expected action did not match
  79. * @const string
  80. */
  81. const E_ACTION_MISMATCH = 'action-mismatch';
  82. /**
  83. * Score threshold not met
  84. * @const string
  85. */
  86. const E_SCORE_THRESHOLD_NOT_MET = 'score-threshold-not-met';
  87. /**
  88. * Challenge timeout
  89. * @const string
  90. */
  91. const E_CHALLENGE_TIMEOUT = 'challenge-timeout';
  92. /**
  93. * Shared secret for the site.
  94. * @var string
  95. */
  96. private $secret;
  97. /**
  98. * Method used to communicate with service. Defaults to POST request.
  99. * @var RequestMethod
  100. */
  101. private $requestMethod;
  102. /**
  103. * Create a configured instance to use the reCAPTCHA service.
  104. *
  105. * @param string $secret The shared key between your site and reCAPTCHA.
  106. * @param RequestMethod $requestMethod method used to send the request. Defaults to POST.
  107. * @throws \RuntimeException if $secret is invalid
  108. */
  109. public function __construct($secret, RequestMethod $requestMethod = null)
  110. {
  111. if (empty($secret)) {
  112. throw new \RuntimeException('No secret provided');
  113. }
  114. if (!is_string($secret)) {
  115. throw new \RuntimeException('The provided secret must be a string');
  116. }
  117. $this->secret = $secret;
  118. $this->requestMethod = (is_null($requestMethod)) ? new RequestMethod\Post() : $requestMethod;
  119. }
  120. /**
  121. * Calls the reCAPTCHA siteverify API to verify whether the user passes
  122. * CAPTCHA test and additionally runs any specified additional checks
  123. *
  124. * @param string $response The user response token provided by reCAPTCHA, verifying the user on your site.
  125. * @param string $remoteIp The end user's IP address.
  126. * @return Response Response from the service.
  127. */
  128. public function verify($response, $remoteIp = null)
  129. {
  130. // Discard empty solution submissions
  131. if (empty($response)) {
  132. $recaptchaResponse = new Response(false, array(self::E_MISSING_INPUT_RESPONSE));
  133. return $recaptchaResponse;
  134. }
  135. $params = new RequestParameters($this->secret, $response, $remoteIp, self::VERSION);
  136. $rawResponse = $this->requestMethod->submit($params);
  137. $initialResponse = Response::fromJson($rawResponse);
  138. $validationErrors = array();
  139. if (isset($this->hostname) && strcasecmp($this->hostname, $initialResponse->getHostname()) !== 0) {
  140. $validationErrors[] = self::E_HOSTNAME_MISMATCH;
  141. }
  142. if (isset($this->apkPackageName) && strcasecmp($this->apkPackageName, $initialResponse->getApkPackageName()) !== 0) {
  143. $validationErrors[] = self::E_APK_PACKAGE_NAME_MISMATCH;
  144. }
  145. if (isset($this->action) && strcasecmp($this->action, $initialResponse->getAction()) !== 0) {
  146. $validationErrors[] = self::E_ACTION_MISMATCH;
  147. }
  148. if (isset($this->threshold) && $this->threshold > $initialResponse->getScore()) {
  149. $validationErrors[] = self::E_SCORE_THRESHOLD_NOT_MET;
  150. }
  151. if (isset($this->timeoutSeconds)) {
  152. $challengeTs = strtotime($initialResponse->getChallengeTs());
  153. if ($challengeTs > 0 && time() - $challengeTs > $this->timeoutSeconds) {
  154. $validationErrors[] = self::E_CHALLENGE_TIMEOUT;
  155. }
  156. }
  157. if (empty($validationErrors)) {
  158. return $initialResponse;
  159. }
  160. return new Response(
  161. false,
  162. array_merge($initialResponse->getErrorCodes(), $validationErrors),
  163. $initialResponse->getHostname(),
  164. $initialResponse->getChallengeTs(),
  165. $initialResponse->getApkPackageName(),
  166. $initialResponse->getScore(),
  167. $initialResponse->getAction()
  168. );
  169. }
  170. /**
  171. * Provide a hostname to match against in verify()
  172. * This should be without a protocol or trailing slash, e.g. www.google.com
  173. *
  174. * @param string $hostname Expected hostname
  175. * @return ReCaptcha Current instance for fluent interface
  176. */
  177. public function setExpectedHostname($hostname)
  178. {
  179. $this->hostname = $hostname;
  180. return $this;
  181. }
  182. /**
  183. * Provide an APK package name to match against in verify()
  184. *
  185. * @param string $apkPackageName Expected APK package name
  186. * @return ReCaptcha Current instance for fluent interface
  187. */
  188. public function setExpectedApkPackageName($apkPackageName)
  189. {
  190. $this->apkPackageName = $apkPackageName;
  191. return $this;
  192. }
  193. /**
  194. * Provide an action to match against in verify()
  195. * This should be set per page.
  196. *
  197. * @param string $action Expected action
  198. * @return ReCaptcha Current instance for fluent interface
  199. */
  200. public function setExpectedAction($action)
  201. {
  202. $this->action = $action;
  203. return $this;
  204. }
  205. /**
  206. * Provide a threshold to meet or exceed in verify()
  207. * Threshold should be a float between 0 and 1 which will be tested as response >= threshold.
  208. *
  209. * @param float $threshold Expected threshold
  210. * @return ReCaptcha Current instance for fluent interface
  211. */
  212. public function setScoreThreshold($threshold)
  213. {
  214. $this->threshold = floatval($threshold);
  215. return $this;
  216. }
  217. /**
  218. * Provide a timeout in seconds to test against the challenge timestamp in verify()
  219. *
  220. * @param int $timeoutSeconds Expected hostname
  221. * @return ReCaptcha Current instance for fluent interface
  222. */
  223. public function setChallengeTimeout($timeoutSeconds)
  224. {
  225. $this->timeoutSeconds = $timeoutSeconds;
  226. return $this;
  227. }
  228. }