1
0

BxAntispamPerspectiveAPI.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup Antispam Antispam
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. /**
  12. * Toxicity detection based on the message content and logged in user info - http://www.perspectiveapi.com
  13. */
  14. define('BX_ANTISPAM_PERSPECTIVE_API_URL', 'https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze');
  15. class BxAntispamPerspectiveAPI extends BxDol
  16. {
  17. private $_sAPIKey;
  18. private $_iThreshold;
  19. public function __construct()
  20. {
  21. parent::__construct();
  22. $this->_sAPIKey = getParam('bx_antispam_toxicity_filter_api_key');
  23. $this->_iThreshold = getParam('bx_antispam_toxicity_filter_threshold');
  24. }
  25. public function isToxic ($s)
  26. {
  27. if (!$this->_sAPIKey || !$this->_iThreshold)
  28. return false;
  29. $aRequest = [
  30. 'comment' => ['text' => $s],
  31. 'doNotStore' => true,
  32. 'requestedAttributes' => [
  33. 'TOXICITY' => [],
  34. ],
  35. ];
  36. $sResponse = bx_file_get_contents(
  37. bx_append_url_params(BX_ANTISPAM_PERSPECTIVE_API_URL, ['key' => $this->_sAPIKey]),
  38. $aRequest,
  39. 'post-json-object'
  40. );
  41. $aResponse = [];
  42. if ($sResponse) $aResponse = json_decode($sResponse, true);
  43. // if we get any score then compare it with a threshold
  44. if ($aResponse && isset($aResponse['attributeScores']) && isset($aResponse['attributeScores']['TOXICITY']) && isset($aResponse['attributeScores']['TOXICITY']['summaryScore'])) {
  45. return $aResponse['attributeScores']['TOXICITY']['summaryScore']['value'] >= $this->_iThreshold/100;
  46. }
  47. // in any other case consider this text as non toxic
  48. return false;
  49. }
  50. public function onPositiveDetection ($sExtraData = '')
  51. {
  52. $o = bx_instance('DNSBlacklists', array(), 'bx_antispam');
  53. $o->onPositiveDetection (getVisitorIP(), $sExtraData, 'toxicity_filter');
  54. }
  55. }
  56. /** @} */