WecomCenterSave.php 5.9 KB

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