BxDolAiTriggerAlert.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 UnaCore UNA Core
  7. * @{
  8. */
  9. class BxDolAiTriggerAlert extends BxDolAiTrigger
  10. {
  11. protected $_sType = 'alert';
  12. protected function usesSenderChatHistory()
  13. {
  14. return true;
  15. }
  16. /**
  17. * Sync: mutate alert extras from the model JSON. Async: background job.
  18. */
  19. public function handle($mixed = null)
  20. {
  21. $oAlert = $mixed;
  22. if (!$oAlert || !BxDolAi::getInstance())
  23. return false;
  24. $aAgents = $this->getAgentsByUnitAndAction($oAlert->sUnit, $oAlert->sAction);
  25. if (!$aAgents)
  26. return false;
  27. foreach ($aAgents as $a) {
  28. $aParams = [
  29. 'trigger' => $this->getType(),
  30. 'object_id' => $oAlert->iObject,
  31. 'sender_profile_id' => $oAlert->iSender,
  32. 'unit' => $oAlert->sUnit,
  33. 'action' => $oAlert->sAction,
  34. 'extra' => $oAlert->aExtras,
  35. ];
  36. if (!empty($a['async'])) {
  37. $this->enqueue($a, $aParams);
  38. continue;
  39. }
  40. $this->applyExtraMutation($oAlert, $this->call($a, $aParams));
  41. }
  42. return true;
  43. }
  44. public function getAgentsByUnitAndAction($sUnit, $sAction)
  45. {
  46. $aAgents = [];
  47. $oDb = new BxDolAiQuery();
  48. foreach ($oDb->getAgentsWithAlert() as $r) {
  49. $aAlert = explode(':', $r['alert']); // TODO: remake to concantenate $sUnit and $sAction and then compare
  50. if (count($aAlert) == 2 && $aAlert[0] == $sUnit && $aAlert[1] == $sAction)
  51. $aAgents[] = $r;
  52. }
  53. return $aAgents;
  54. }
  55. protected function applyExtraMutation($oAlert, $sExtraJSON)
  56. {
  57. $aExtra = [];
  58. if ($sExtraJSON && 0 === bx_mb_strpos($sExtraJSON, '{'))
  59. $aExtra = json_decode($sExtraJSON, true);
  60. if (!$aExtra || !is_array($aExtra))
  61. return;
  62. foreach ($aExtra as $k => $v) {
  63. if (isset($oAlert->aExtras[$k]))
  64. $oAlert->aExtras[$k] = $v;
  65. }
  66. }
  67. }
  68. /** @} */