WecomCenterSave.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. case 'apply_switch': $this->applySwitch(); break;
  40. default: error(I18n::t('msg.unknown_op'));
  41. }
  42. }
  43. }
  44. catch (Exception $e) {
  45. error($e->getMessage());
  46. }
  47. $url = (new CUrl('zabbix.php'))->setArgument('action', 'wecom.center.view');
  48. if ($mediatypeid !== '') {
  49. $url->setArgument('mediatypeid', $mediatypeid);
  50. }
  51. $this->setResponse(new CControllerResponseRedirect($url));
  52. }
  53. private function applyStrategy(string $mediatypeid, string $key): void {
  54. if (!isset(Helper::STRATEGY_PRESETS[$key])) {
  55. throw new Exception(I18n::t('msg.bad_scheme'));
  56. }
  57. $tid = Helper::templateHostid();
  58. if ($tid === null) {
  59. throw new Exception(I18n::t('msg.no_template_host'));
  60. }
  61. $preset = Helper::STRATEGY_PRESETS[$key];
  62. // 1) threshold on the media (global "how severe still notifies")
  63. if ($mediatypeid !== '') {
  64. $user = Helper::ensureRobotUser('wecomrobot');
  65. $mask = Helper::severityMaskFromMin((int) $preset['min']);
  66. Helper::applyMedia($user['userid'], $mediatypeid, $mask, 0);
  67. }
  68. // 2) classify + write severities
  69. $res = Helper::applyStrategy($tid, $preset['targets']);
  70. Helper::saveStrategyKey($key);
  71. info(I18n::t('msg.strategy_applied', [
  72. I18n::t($preset['label']),
  73. $res['trigger'],
  74. $res['prototype'],
  75. $res['discovered']
  76. ]));
  77. }
  78. private function saveAlert(string $mediatypeid): void {
  79. $active = isset($_REQUEST['enabled']) ? 0 : 1; // media: 0=enabled, 1=disabled
  80. $indices = [];
  81. for ($i = 1; $i <= 6; $i++) {
  82. if (isset($_REQUEST['sev_'.$i])) {
  83. $indices[] = $i;
  84. }
  85. }
  86. $mask = Helper::severityMask($indices);
  87. if ($mask === 0 && $active === 0) {
  88. $mask = 2;
  89. }
  90. $user = Helper::ensureRobotUser('wecomrobot');
  91. Helper::applyMedia($user['userid'], $mediatypeid, $mask, $active);
  92. info(I18n::t('msg.saved'));
  93. }
  94. private function saveRobot(string $mediatypeid): void {
  95. $url = trim((string) ($_REQUEST['webhook_url'] ?? ''));
  96. if ($url !== '') {
  97. Helper::setWebhookKey($url);
  98. }
  99. $user = Helper::ensureRobotUser('wecomrobot');
  100. $cur = Helper::currentMedia($user, $mediatypeid);
  101. $mask = $cur['severity'] ?? 48;
  102. $active = $cur['active'] ?? 0;
  103. Helper::applyMedia($user['userid'], $mediatypeid, $mask, $active);
  104. info(I18n::t('msg.robot_saved'));
  105. }
  106. private function testRobot(string $mediatypeid): void {
  107. $mt = Helper::getMediatype($mediatypeid);
  108. if (!$mt) {
  109. throw new Exception(I18n::t('msg.no_mediatype'));
  110. }
  111. $url = Helper::webhookUrl($mt);
  112. if ($url === '') {
  113. throw new Exception(I18n::t('msg.no_url'));
  114. }
  115. $text = '['.I18n::t('page.title').'] Test OK - '.date('Y-m-d H:i:s');
  116. $res = Helper::testWebhook($url, $text);
  117. $body = (string) $res['body'];
  118. $ok = (strpos($body, '"errcode":0') !== false) || (strpos($body, '"errcode": 0') !== false);
  119. if ($ok) {
  120. info(I18n::t('msg.tested'));
  121. }
  122. else {
  123. error(I18n::t('msg.test_failed', [$res['status'], $body]));
  124. }
  125. }
  126. private function importTemplate(): void {
  127. $file = (string) ($_REQUEST['template_file'] ?? '');
  128. if ($file === '') {
  129. throw new Exception(I18n::t('msg.no_template'));
  130. }
  131. $module_dir = dirname(__DIR__);
  132. $res = Helper::importTemplate($module_dir, $file);
  133. $n = isset($res['templates']) && is_array($res['templates']) ? count($res['templates']) : 0;
  134. info(I18n::t('msg.imported', [$n]));
  135. }
  136. private function saveTriggers(): void {
  137. $ids = (string) ($_REQUEST['trig_ids'] ?? '');
  138. $ids = array_filter(array_map('trim', explode(',', $ids)));
  139. if (!$ids) {
  140. throw new Exception(I18n::t('msg.no_triggers'));
  141. }
  142. $map = [];
  143. foreach ($ids as $id) {
  144. $id = (string) (int) $id;
  145. if ($id === '' || $id === '0') {
  146. continue;
  147. }
  148. $map[$id] = isset($_REQUEST['trig_'.$id]) ? 0 : 1;
  149. }
  150. $n = Helper::setTriggersStatus($map);
  151. info(I18n::t('msg.triggers_saved', [$n]));
  152. }
  153. private function saveMap(): void {
  154. $hostid = (string) ($_REQUEST['hostid'] ?? '');
  155. $lat = trim((string) ($_REQUEST['lat'] ?? ''));
  156. $lon = trim((string) ($_REQUEST['lon'] ?? ''));
  157. if ($hostid === '') {
  158. throw new Exception(I18n::t('msg.no_host'));
  159. }
  160. Helper::setHostLocation($hostid, $lat, $lon);
  161. info(I18n::t('msg.map_saved'));
  162. }
  163. private function applySwitch(): void {
  164. $src = (string) ($_REQUEST['switch_src'] ?? '');
  165. $dst = (string) ($_REQUEST['switch_dst'] ?? '');
  166. if ($src === '' || $dst === '') {
  167. throw new Exception(I18n::t('msg.need_both'));
  168. }
  169. if ($src === $dst) {
  170. throw new Exception(I18n::t('msg.same_tpl'));
  171. }
  172. $n = Helper::switchApply($src, $dst);
  173. info(I18n::t('msg.switch_applied', [$n]));
  174. }
  175. }