helpers.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php
  2. /**
  3. * This file is part of webman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. use support\Request;
  15. use support\Response;
  16. use support\Translation;
  17. use support\Container;
  18. use support\view\Raw;
  19. use support\view\Blade;
  20. use support\view\ThinkPHP;
  21. use support\view\Twig;
  22. use Workerman\Worker;
  23. use Webman\App;
  24. use Webman\Config;
  25. use Webman\Route;
  26. // Phar support.
  27. if (is_phar()) {
  28. define('BASE_PATH', dirname(__DIR__));
  29. } else {
  30. define('BASE_PATH', realpath(__DIR__ . '/../'));
  31. }
  32. define('WEBMAN_VERSION', '1.3.0');
  33. /**
  34. * @param $return_phar
  35. * @return false|string
  36. */
  37. function base_path($return_phar = true)
  38. {
  39. static $real_path = '';
  40. if (!$real_path) {
  41. $real_path = is_phar() ? dirname(Phar::running(false)) : BASE_PATH;
  42. }
  43. return $return_phar ? BASE_PATH : $real_path;
  44. }
  45. /**
  46. * @return string
  47. */
  48. function app_path()
  49. {
  50. return BASE_PATH . DIRECTORY_SEPARATOR . 'app';
  51. }
  52. /**
  53. * @return string
  54. */
  55. function public_path()
  56. {
  57. static $path = '';
  58. if (!$path) {
  59. $path = config('app.public_path', BASE_PATH . DIRECTORY_SEPARATOR . 'public');
  60. }
  61. return $path;
  62. }
  63. /**
  64. * @return string
  65. */
  66. function config_path()
  67. {
  68. return BASE_PATH . DIRECTORY_SEPARATOR . 'config';
  69. }
  70. /**
  71. * Phar support.
  72. * Compatible with the 'realpath' function in the phar file.
  73. *
  74. * @return string
  75. */
  76. function runtime_path()
  77. {
  78. static $path = '';
  79. if (!$path) {
  80. $path = config('app.runtime_path', BASE_PATH . DIRECTORY_SEPARATOR . 'runtime');
  81. }
  82. return $path;
  83. }
  84. /**
  85. * @param int $status
  86. * @param array $headers
  87. * @param string $body
  88. * @return Response
  89. */
  90. function response($body = '', $status = 200, $headers = array())
  91. {
  92. return new Response($status, $headers, $body);
  93. }
  94. /**
  95. * @param $data
  96. * @param int $options
  97. * @return Response
  98. */
  99. function json($data, $options = JSON_UNESCAPED_UNICODE)
  100. {
  101. return new Response(200, ['Content-Type' => 'application/json'], json_encode($data, $options));
  102. }
  103. /**
  104. * Notes:api成功返回参数
  105. * @param $result
  106. * @param string $message
  107. * @param int $options
  108. * @return Response
  109. * User: yym
  110. * Date: 2022/7/26
  111. */
  112. function json_success($result, $message = '成功', $options = JSON_UNESCAPED_UNICODE)
  113. {
  114. $data = array(
  115. 'code' => 200,
  116. 'msg' => $message,
  117. 'data' => $result
  118. );
  119. return new Response(200, ['Content-Type' => 'application/json'], json_encode($data, $options));
  120. }
  121. /**
  122. * @param $xml
  123. * @return Response
  124. */
  125. function xml($xml)
  126. {
  127. if ($xml instanceof SimpleXMLElement) {
  128. $xml = $xml->asXML();
  129. }
  130. return new Response(200, ['Content-Type' => 'text/xml'], $xml);
  131. }
  132. /**
  133. * @param $data
  134. * @param string $callback_name
  135. * @return Response
  136. */
  137. function jsonp($data, $callback_name = 'callback')
  138. {
  139. if (!is_scalar($data) && null !== $data) {
  140. $data = json_encode($data);
  141. }
  142. return new Response(200, [], "$callback_name($data)");
  143. }
  144. /**
  145. * @param $location
  146. * @param int $status
  147. * @param array $headers
  148. * @return Response
  149. */
  150. function redirect($location, $status = 302, $headers = [])
  151. {
  152. $response = new Response($status, ['Location' => $location]);
  153. if (!empty($headers)) {
  154. $response->withHeaders($headers);
  155. }
  156. return $response;
  157. }
  158. /**
  159. * @param $template
  160. * @param array $vars
  161. * @param null $app
  162. * @return Response
  163. */
  164. function view($template, $vars = [], $app = null)
  165. {
  166. static $handler;
  167. if (null === $handler) {
  168. $handler = config('view.handler');
  169. }
  170. return new Response(200, [], $handler::render($template, $vars, $app));
  171. }
  172. /**
  173. * @param $template
  174. * @param array $vars
  175. * @param null $app
  176. * @return Response
  177. */
  178. function raw_view($template, $vars = [], $app = null)
  179. {
  180. return new Response(200, [], Raw::render($template, $vars, $app));
  181. }
  182. /**
  183. * @param $template
  184. * @param array $vars
  185. * @param null $app
  186. * @return Response
  187. */
  188. function blade_view($template, $vars = [], $app = null)
  189. {
  190. return new Response(200, [], Blade::render($template, $vars, $app));
  191. }
  192. /**
  193. * @param $template
  194. * @param array $vars
  195. * @param null $app
  196. * @return Response
  197. */
  198. function think_view($template, $vars = [], $app = null)
  199. {
  200. return new Response(200, [], ThinkPHP::render($template, $vars, $app));
  201. }
  202. /**
  203. * @param $template
  204. * @param array $vars
  205. * @param null $app
  206. * @return Response
  207. */
  208. function twig_view($template, $vars = [], $app = null)
  209. {
  210. return new Response(200, [], Twig::render($template, $vars, $app));
  211. }
  212. /**
  213. * @return Request
  214. */
  215. function request()
  216. {
  217. return App::request();
  218. }
  219. /**
  220. * @param $key
  221. * @param null $default
  222. * @return mixed
  223. */
  224. function config($key = null, $default = null)
  225. {
  226. return Config::get($key, $default);
  227. }
  228. /**
  229. * @param $name
  230. * @param ...$parameters
  231. * @return string
  232. */
  233. function route($name, ...$parameters)
  234. {
  235. $route = Route::getByName($name);
  236. if (!$route) {
  237. return '';
  238. }
  239. if (!$parameters) {
  240. return $route->url();
  241. }
  242. if (is_array(current($parameters))) {
  243. $parameters = current($parameters);
  244. }
  245. return $route->url($parameters);
  246. }
  247. /**
  248. * @param mixed $key
  249. * @param mixed $default
  250. * @return mixed
  251. */
  252. function session($key = null, $default = null)
  253. {
  254. $session = request()->session();
  255. if (null === $key) {
  256. return $session;
  257. }
  258. if (\is_array($key)) {
  259. $session->put($key);
  260. return null;
  261. }
  262. if (\strpos($key, '.')) {
  263. $key_array = \explode('.', $key);
  264. $value = $session->all();
  265. foreach ($key_array as $index) {
  266. if (!isset($value[$index])) {
  267. return $default;
  268. }
  269. $value = $value[$index];
  270. }
  271. return $value;
  272. }
  273. return $session->get($key, $default);
  274. }
  275. /**
  276. * @param null|string $id
  277. * @param array $parameters
  278. * @param string|null $domain
  279. * @param string|null $locale
  280. * @return string
  281. */
  282. function trans(string $id, array $parameters = [], string $domain = null, string $locale = null)
  283. {
  284. $res = Translation::trans($id, $parameters, $domain, $locale);
  285. return $res === '' ? $id : $res;
  286. }
  287. /**
  288. * @param null|string $locale
  289. * @return string
  290. */
  291. function locale(string $locale = null)
  292. {
  293. if (!$locale) {
  294. return Translation::getLocale();
  295. }
  296. Translation::setLocale($locale);
  297. }
  298. /**
  299. * 404 not found
  300. *
  301. * @return Response
  302. */
  303. function not_found()
  304. {
  305. return new Response(404, [], file_get_contents(public_path() . '/404.html'));
  306. }
  307. /**
  308. * Copy dir.
  309. * @param $source
  310. * @param $dest
  311. * @param bool $overwrite
  312. * @return void
  313. */
  314. function copy_dir($source, $dest, $overwrite = false)
  315. {
  316. if (is_dir($source)) {
  317. if (!is_dir($dest)) {
  318. mkdir($dest);
  319. }
  320. $files = scandir($source);
  321. foreach ($files as $file) {
  322. if ($file !== "." && $file !== "..") {
  323. copy_dir("$source/$file", "$dest/$file");
  324. }
  325. }
  326. } else if (file_exists($source) && ($overwrite || !file_exists($dest))) {
  327. copy($source, $dest);
  328. }
  329. }
  330. /**
  331. * Remove dir.
  332. * @param $dir
  333. * @return bool
  334. */
  335. function remove_dir($dir)
  336. {
  337. if (is_link($dir) || is_file($dir)) {
  338. return unlink($dir);
  339. }
  340. $files = array_diff(scandir($dir), array('.', '..'));
  341. foreach ($files as $file) {
  342. (is_dir("$dir/$file") && !is_link($dir)) ? remove_dir("$dir/$file") : unlink("$dir/$file");
  343. }
  344. return rmdir($dir);
  345. }
  346. /**
  347. * @param $worker
  348. * @param $class
  349. */
  350. function worker_bind($worker, $class)
  351. {
  352. $callback_map = [
  353. 'onConnect',
  354. 'onMessage',
  355. 'onClose',
  356. 'onError',
  357. 'onBufferFull',
  358. 'onBufferDrain',
  359. 'onWorkerStop',
  360. 'onWebSocketConnect'
  361. ];
  362. foreach ($callback_map as $name) {
  363. if (method_exists($class, $name)) {
  364. $worker->$name = [$class, $name];
  365. }
  366. }
  367. if (method_exists($class, 'onWorkerStart')) {
  368. call_user_func([$class, 'onWorkerStart'], $worker);
  369. }
  370. }
  371. /**
  372. * @param $process_name
  373. * @param $config
  374. * @return void
  375. */
  376. function worker_start($process_name, $config)
  377. {
  378. $worker = new Worker($config['listen'] ?? null, $config['context'] ?? []);
  379. $property_map = [
  380. 'count',
  381. 'user',
  382. 'group',
  383. 'reloadable',
  384. 'reusePort',
  385. 'transport',
  386. 'protocol',
  387. ];
  388. $worker->name = $process_name;
  389. foreach ($property_map as $property) {
  390. if (isset($config[$property])) {
  391. $worker->$property = $config[$property];
  392. }
  393. }
  394. $worker->onWorkerStart = function ($worker) use ($config) {
  395. require_once base_path() . '/support/bootstrap.php';
  396. foreach ($config['services'] ?? [] as $server) {
  397. if (!class_exists($server['handler'])) {
  398. echo "process error: class {$server['handler']} not exists\r\n";
  399. continue;
  400. }
  401. $listen = new Worker($server['listen'] ?? null, $server['context'] ?? []);
  402. if (isset($server['listen'])) {
  403. echo "listen: {$server['listen']}\n";
  404. }
  405. $instance = Container::make($server['handler'], $server['constructor'] ?? []);
  406. worker_bind($listen, $instance);
  407. $listen->listen();
  408. }
  409. if (isset($config['handler'])) {
  410. if (!class_exists($config['handler'])) {
  411. echo "process error: class {$config['handler']} not exists\r\n";
  412. return;
  413. }
  414. $instance = Container::make($config['handler'], $config['constructor'] ?? []);
  415. worker_bind($worker, $instance);
  416. }
  417. };
  418. }
  419. /**
  420. * Phar support.
  421. * Compatible with the 'realpath' function in the phar file.
  422. *
  423. * @param string $file_path
  424. * @return string
  425. */
  426. function get_realpath(string $file_path): string
  427. {
  428. if (strpos($file_path, 'phar://') === 0) {
  429. return $file_path;
  430. } else {
  431. return realpath($file_path);
  432. }
  433. }
  434. /**
  435. * @return bool
  436. */
  437. function is_phar()
  438. {
  439. return class_exists(\Phar::class, false) && Phar::running();
  440. }
  441. /**
  442. * @return int
  443. */
  444. function cpu_count()
  445. {
  446. // Windows does not support the number of processes setting.
  447. if (\DIRECTORY_SEPARATOR === '\\') {
  448. return 1;
  449. }
  450. $count = 4;
  451. if (is_callable('shell_exec')) {
  452. if (strtolower(PHP_OS) === 'darwin') {
  453. $count = (int)shell_exec('sysctl -n machdep.cpu.core_count');
  454. } else {
  455. $count = (int)shell_exec('nproc');
  456. }
  457. }
  458. return $count > 0 ? $count : 4;
  459. }
  460. if (!function_exists('events')) {
  461. /**
  462. * 触发事件
  463. * @param string $list_name 事件名(
  464. * @param array $args 参数
  465. * @return mixed
  466. */
  467. function events($list_name, $args = array())
  468. {
  469. $config = config('plugin.tinywan.event.app.event.listener');
  470. if(!isset($config[$list_name]))
  471. {
  472. return false;
  473. }
  474. $event = new $config[$list_name]($args);
  475. return \Tinywan\Event::trigger($event, $list_name);
  476. }
  477. }
  478. /**
  479. * Notes:图片路径处理
  480. * @param string $path 图片路径
  481. * @param string $default //默认显示图片
  482. * @return string
  483. * User: yym
  484. * Date: 2022/8/5
  485. */
  486. function get_image_path(string $path, string $default = '')
  487. {
  488. if(empty($path))
  489. {
  490. return $default;
  491. }
  492. if(strstr($path, 'http') !== false || strstr($path, 'https') !== false)
  493. {
  494. return $path;
  495. }
  496. // if(!file_exists(public_path() . $path))
  497. // {
  498. // return $default;
  499. // }
  500. $config = config('plugin.tinywan.storage.app.storage');
  501. $host_url = $config[$config['default']]['domain'];
  502. return $host_url . $path;
  503. }
  504. /**解密
  505. * @param string $string 需要解密的字符串
  506. * @param string $key 密钥
  507. * @return string
  508. */
  509. function decrypt($string, $key = 'b5b84e8b3b55c6daaf60825ff1a95c46')
  510. {
  511. // 对接java,服务商做的AES加密通过SHA1PRNG算法(只要password一样,每次生成的数组都是一样的),Java的加密源码翻译php如下:
  512. $string = base64_decode($string);
  513. $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
  514. $decrypted = openssl_decrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
  515. return $decrypted;
  516. }
  517. if (!function_exists('get_ip')) {
  518. /**
  519. * Notes:获取客户端ip
  520. * @return string
  521. * User: yym
  522. * Date: 2022/9/14
  523. */
  524. function get_ip()
  525. {
  526. return request()->getRealIp();
  527. }
  528. }