Config.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace app\admin\controller\sms;
  3. use app\common\controller\Backend;
  4. use think\facade\Config as sysConfig;
  5. class Config extends Backend
  6. {
  7. static $smsConfigFile = 'sms.php';
  8. public function getConfigKey()
  9. {
  10. $name = $this->request->get('name', '');
  11. if (!$name) {
  12. $this->error(__('Parameter error'));
  13. }
  14. if ($name == 'base') {
  15. $this->success('', [
  16. 'timeout' => sysConfig::get('sms.timeout'),
  17. 'strategy' => sysConfig::get('sms.default.strategy'),
  18. 'gateways' => sysConfig::get('sms.default.gateways'),
  19. ]);
  20. }
  21. $config = sysConfig::get('sms.gateways.' . $name);
  22. $this->success('', [
  23. 'config' => $config,
  24. ]);
  25. }
  26. public function saveConfig()
  27. {
  28. $type = $this->request->get('type', '');
  29. $data = $this->request->post();
  30. if (!$type) {
  31. $this->error(__('Parameter error'));
  32. }
  33. $sms = sysConfig::get('sms');
  34. $smsConfigPath = config_path() . self::$smsConfigFile;
  35. $smsConfigContent = @file_get_contents($smsConfigPath);
  36. if ($type == 'base') {
  37. $timeout = (int)$data['timeout'];
  38. $strategy = $data['strategy'] == 'order' ? 'Overtrue\EasySms\Strategies\OrderStrategy' : 'Overtrue\EasySms\Strategies\RandomStrategy';
  39. $sms['default']['strategy'] = str_replace('\\', '\\\\', $sms['default']['strategy']);
  40. $gatewaysText = '[';
  41. if ($data['gateways']) {
  42. foreach ($data['gateways'] as $gateway) {
  43. $gatewaysText .= "'$gateway', ";
  44. }
  45. }
  46. $gatewaysText = rtrim($gatewaysText, ', ');
  47. $gatewaysText .= ']';
  48. $smsConfigContent = preg_replace("/'timeout'(\s+)=>(\s+)'{$sms['timeout']}'/", "'timeout'\$1=>\$2'$timeout'", $smsConfigContent);
  49. $smsConfigContent = preg_replace("/'strategy'(\s+)=>(\s+)'{$sms['default']['strategy']}'/", "'strategy'\$1=>\$2'$strategy'", $smsConfigContent);
  50. $smsConfigContent = preg_replace("/'gateways'(\s+)=>(\s+)\[.*?]/", "'gateways'\$1=>\$2$gatewaysText", $smsConfigContent);
  51. } elseif ($type == 'gateway') {
  52. $name = $this->request->get('name', '');
  53. if (!isset($sms['gateways'][$name]) || !is_array($sms['gateways'][$name])) {
  54. $this->error(__('Parameter error'));
  55. }
  56. foreach ($sms['gateways'][$name] as $key => $item) {
  57. $smsConfigContent = preg_replace("/'$key'(\s+)=>(\s+)'$item',#$name#/", "'$key'\$1=>\$2'{$data[$key]}',#$name#", $smsConfigContent);
  58. }
  59. }
  60. $result = @file_put_contents($smsConfigPath, $smsConfigContent);
  61. if (!$result) {
  62. $this->error(__('Configuration write failed: %s', ['config/' . self::$smsConfigFile]));
  63. }
  64. $this->success();
  65. }
  66. }