WecomCenterSave.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. <?php declare(strict_types = 0);
  2. /*
  3. ** WeCom Center - POST controller. Dispatches actions and redirects back.
  4. */
  5. namespace Modules\WecomCenter\Actions;
  6. use CController;
  7. use CControllerResponseRedirect;
  8. use CUrl;
  9. use CWebUser;
  10. use Exception;
  11. use Modules\WecomCenter\Lib\Helper;
  12. use Modules\WecomCenter\Lib\I18n;
  13. class WecomCenterSave extends CController {
  14. protected function init() {
  15. $this->disableCsrfValidation();
  16. }
  17. protected function checkInput() {
  18. return true;
  19. }
  20. protected function checkPermissions() {
  21. return CWebUser::getType() == USER_TYPE_SUPER_ADMIN;
  22. }
  23. protected function doAction() {
  24. $mediatypeid = (string) ($_REQUEST['mediatypeid'] ?? '');
  25. try {
  26. // Strategy apply buttons are submitted as name="apply_strategy" value=<preset>.
  27. if (isset($_REQUEST['apply_strategy'])) {
  28. $this->applyStrategy($mediatypeid, (string) $_REQUEST['apply_strategy']);
  29. }
  30. else {
  31. $op = (string) ($_REQUEST['op'] ?? '');
  32. switch ($op) {
  33. case 'save_alert': $this->saveAlert($mediatypeid); break;
  34. case 'save_triggers': $this->saveTriggers(); break;
  35. case 'save_robot': $this->saveRobot($mediatypeid); break;
  36. case 'test_robot': $this->testRobot($mediatypeid); break;
  37. case 'import_template': $this->importTemplate(); break;
  38. case 'save_map': $this->saveMap(); break;
  39. default: error(I18n::t('msg.unknown_op'));
  40. }
  41. }
  42. }
  43. catch (Exception $e) {
  44. error($e->getMessage());
  45. }
  46. $url = (new CUrl('zabbix.php'))->setArgument('action', 'wecom.center.view');
  47. if ($mediatypeid !== '') {
  48. $url->setArgument('mediatypeid', $mediatypeid);
  49. }
  50. $this->setResponse(new CControllerResponseRedirect($url));
  51. }
  52. private function applyStrategy(string $mediatypeid, string $key): void {
  53. if (!isset(Helper::STRATEGY_PRESETS[$key])) {
  54. throw new Exception(I18n::t('msg.bad_scheme'));
  55. }
  56. $tid = Helper::templateHostid();
  57. if ($tid === null) {
  58. throw new Exception(I18n::t('msg.no_template_host'));
  59. }
  60. $preset = Helper::STRATEGY_PRESETS[$key];
  61. // 1) threshold on the media (global "how severe still notifies")
  62. if ($mediatypeid !== '') {
  63. $user = Helper::ensureRobotUser('wecomrobot');
  64. $mask = Helper::severityMaskFromMin((int) $preset['min']);
  65. Helper::applyMedia($user['userid'], $mediatypeid, $mask, 0);
  66. }
  67. // 2) classify + write severities
  68. $res = Helper::applyStrategy($tid, $preset['targets']);
  69. Helper::saveStrategyKey($key);
  70. info(I18n::t('msg.strategy_applied', [
  71. I18n::t($preset['label']),
  72. $res['trigger'],
  73. $res['prototype'],
  74. $res['discovered']
  75. ]));
  76. }
  77. private function saveAlert(string $mediatypeid): void {
  78. $active = isset($_REQUEST['enabled']) ? 0 : 1; // media: 0=enabled, 1=disabled
  79. $indices = [];
  80. for ($i = 1; $i <= 6; $i++) {
  81. if (isset($_REQUEST['sev_'.$i])) {
  82. $indices[] = $i;
  83. }
  84. }
  85. $mask = Helper::severityMask($indices);
  86. if ($mask === 0 && $active === 0) {
  87. $mask = 2;
  88. }
  89. $user = Helper::ensureRobotUser('wecomrobot');
  90. Helper::applyMedia($user['userid'], $mediatypeid, $mask, $active);
  91. info(I18n::t('msg.saved'));
  92. }
  93. private function saveRobot(string $mediatypeid): void {
  94. $url = trim((string) ($_REQUEST['webhook_url'] ?? ''));
  95. if ($url !== '') {
  96. Helper::setWebhookKey($url);
  97. }
  98. $user = Helper::ensureRobotUser('wecomrobot');
  99. $cur = Helper::currentMedia($user, $mediatypeid);
  100. $mask = $cur['severity'] ?? 48;
  101. $active = $cur['active'] ?? 0;
  102. Helper::applyMedia($user['userid'], $mediatypeid, $mask, $active);
  103. info(I18n::t('msg.robot_saved'));
  104. }
  105. private function testRobot(string $mediatypeid): void {
  106. $mt = Helper::getMediatype($mediatypeid);
  107. if (!$mt) {
  108. throw new Exception(I18n::t('msg.no_mediatype'));
  109. }
  110. $url = Helper::webhookUrl($mt);
  111. if ($url === '') {
  112. throw new Exception(I18n::t('msg.no_url'));
  113. }
  114. $text = '['.I18n::t('page.title').'] Test OK - '.date('Y-m-d H:i:s');
  115. $res = Helper::testWebhook($url, $text);
  116. $body = (string) $res['body'];
  117. $ok = (strpos($body, '"errcode":0') !== false) || (strpos($body, '"errcode": 0') !== false);
  118. if ($ok) {
  119. info(I18n::t('msg.tested'));
  120. }
  121. else {
  122. error(I18n::t('msg.test_failed', [$res['status'], $body]));
  123. }
  124. }
  125. private function importTemplate(): void {
  126. $file = (string) ($_REQUEST['template_file'] ?? '');
  127. if ($file === '') {
  128. throw new Exception(I18n::t('msg.no_template'));
  129. }
  130. $module_dir = dirname(__DIR__);
  131. $res = Helper::importTemplate($module_dir, $file);
  132. $n = isset($res['templates']) && is_array($res['templates']) ? count($res['templates']) : 0;
  133. info(I18n::t('msg.imported', [$n]));
  134. }
  135. private function saveTriggers(): void {
  136. $ids = (string) ($_REQUEST['trig_ids'] ?? '');
  137. $ids = array_filter(array_map('trim', explode(',', $ids)));
  138. if (!$ids) {
  139. throw new Exception(I18n::t('msg.no_triggers'));
  140. }
  141. $map = [];
  142. foreach ($ids as $id) {
  143. $id = (string) (int) $id;
  144. if ($id === '' || $id === '0') {
  145. continue;
  146. }
  147. $map[$id] = isset($_REQUEST['trig_'.$id]) ? 0 : 1;
  148. }
  149. $n = Helper::setTriggersStatus($map);
  150. info(I18n::t('msg.triggers_saved', [$n]));
  151. }
  152. private function saveMap(): void {
  153. $hostid = (string) ($_REQUEST['hostid'] ?? '');
  154. $lat = trim((string) ($_REQUEST['lat'] ?? ''));
  155. $lon = trim((string) ($_REQUEST['lon'] ?? ''));
  156. if ($hostid === '') {
  157. throw new Exception(I18n::t('msg.no_host'));
  158. }
  159. Helper::setHostLocation($hostid, $lat, $lon);
  160. info(I18n::t('msg.map_saved'));
  161. }
  162. }