Index.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. <?php
  2. namespace app\admin\controller;
  3. use think\Hook;
  4. use think\Db;
  5. use COM;
  6. use Exception;
  7. use ip_limit\IpLocationQuery;
  8. class Index extends Base
  9. {
  10. public function __construct()
  11. {
  12. parent::__construct();
  13. }
  14. public function login()
  15. {
  16. if (Request()->isPost()) {
  17. $data = input('post.');
  18. $res = model('Admin')->login($data);
  19. if ($res['code'] > 1) {
  20. return $this->error($res['msg']);
  21. }
  22. return $this->success($res['msg']);
  23. }
  24. Hook::listen("admin_login_init", $this->request);
  25. return $this->fetch('admin@index/login');
  26. }
  27. public function logout()
  28. {
  29. $res = model('Admin')->logout();
  30. $this->redirect('index/login');
  31. }
  32. public function index()
  33. {
  34. $menus = @include MAC_ADMIN_COMM . 'auth.php';
  35. $version = config('version');
  36. foreach ($menus as $k1 => $v1) {
  37. foreach ($v1['sub'] as $k2 => $v2) {
  38. if ($v2['show'] == 1) {
  39. if (strpos($v2['action'], 'javascript') !== false) {
  40. $url = $v2['action'];
  41. } else {
  42. $url = url('admin/' . $v2['controller'] . '/' . $v2['action']);
  43. }
  44. if (!empty($v2['param'])) {
  45. $url .= '?' . $v2['param'];
  46. }
  47. if ($this->check_auth($v2['controller'], $v2['action'])) {
  48. $menus[$k1]['sub'][$k2]['url'] = $url;
  49. } else {
  50. unset($menus[$k1]['sub'][$k2]);
  51. }
  52. } else {
  53. unset($menus[$k1]['sub'][$k2]);
  54. }
  55. }
  56. if (empty($menus[$k1]['sub'])) {
  57. unset($menus[$k1]);
  58. }
  59. }
  60. $quickmenu = config('quickmenu');
  61. if (empty($quickmenu)) {
  62. $quickmenu = mac_read_file(APP_PATH . 'data/config/quickmenu.txt');
  63. $quickmenu = explode(chr(13), $quickmenu);
  64. }
  65. if (!empty($quickmenu)) {
  66. $menus[1]['sub'][13] = ['name' => lang('admin/index/quick_tit'), 'url' => 'javascript:void(0);return false;', 'controller' => '', 'action' => ''];
  67. foreach ($quickmenu as $k => $v) {
  68. if (empty($v)) {
  69. continue;
  70. }
  71. $one = explode(',', trim($v));
  72. if (substr($one[1], 0, 4) == 'http' || substr($one[1], 0, 2) == '//') {
  73. } elseif (substr($one[1], 0, 1) == '/') {
  74. } elseif (strpos($one[1], '###') !== false || strpos($one[1], 'javascript:') !== false) {
  75. } else {
  76. $one[1] = url($one[1]);
  77. }
  78. $menus[1]['sub'][14 + $k] = ['name' => $one[0], 'url' => $one[1], 'controller' => '', 'action' => ''];
  79. }
  80. }
  81. $langs = glob('./application/lang/*.php');
  82. foreach ($langs as $k => &$v) {
  83. $v = str_replace(['./application/lang/','.php'],['',''],$v);
  84. }
  85. $config = config('maccms');
  86. $this->assign('config', $config);
  87. $this->assign('langs', $langs);
  88. $this->assign('version', $version);
  89. $this->assign('menus', $menus);
  90. $this->assign('title', lang('admin/index/title'));
  91. $ipQuery = new IpLocationQuery();
  92. $country_code = $ipQuery->queryProvince(mac_get_client_ip());
  93. if($country_code == ""){
  94. $country_code = "其它";
  95. }
  96. $this->assign('ip_location', $country_code);
  97. return $this->fetch('admin@index/index');
  98. }
  99. public function welcome()
  100. {
  101. $version = config('version');
  102. $update_sql = file_exists('./application/data/update/database.php');
  103. $this->assign('spider_data', $this->botlist());
  104. $this->assign('os_data', $this->get_system_status());
  105. $this->assign('version', $version);
  106. $this->assign('update_sql', $update_sql);
  107. $this->assign('mac_lang', config('default_lang'));
  108. $this->assign('dashboard_data', $this->getAdminDashboardData());
  109. $this->assign('admin', $this->_admin);
  110. $this->assign('title', lang('admin/index/welcome/title'));
  111. return $this->fetch('admin@index/welcome');
  112. }
  113. public function quickmenu()
  114. {
  115. if (Request()->isPost()) {
  116. $param = input();
  117. $validate = \think\Loader::validate('Token');
  118. if (!$validate->check($param)) {
  119. return $this->error($validate->getError());
  120. }
  121. $quickmenu = input('post.quickmenu');
  122. $quickmenu = str_replace(chr(10), '', $quickmenu);
  123. $menu_arr = explode(chr(13), $quickmenu);
  124. $res = mac_arr2file(APP_PATH . 'extra/quickmenu.php', $menu_arr);
  125. if ($res === false) {
  126. return $this->error(lang('save_err'));
  127. }
  128. return $this->success(lang('save_ok'));
  129. } else {
  130. $config_menu = config('quickmenu');
  131. if (empty($config_menu)) {
  132. $quickmenu = mac_read_file(APP_PATH . 'data/config/quickmenu.txt');
  133. } else {
  134. $quickmenu = array_values($config_menu);
  135. $quickmenu = join(chr(13), $quickmenu);
  136. }
  137. $this->assign('quickmenu', $quickmenu);
  138. $this->assign('title', lang('admin/index/quickmenu/title'));
  139. return $this->fetch('admin@index/quickmenu');
  140. }
  141. }
  142. public function checkcache()
  143. {
  144. $res = 'no';
  145. $r = cache('cache_data');
  146. if ($r == '1') {
  147. $res = 'haved';
  148. }
  149. echo $res;
  150. }
  151. public function clear()
  152. {
  153. $res = $this->_cache_clear();
  154. //运行缓存
  155. if (!$res) {
  156. $this->error(lang('admin/index/clear_err'));
  157. }
  158. // 搜索缓存结果清理
  159. model('VodSearch')->clearOldResult(true);
  160. return $this->success(lang('admin/index/clear_ok'));
  161. }
  162. public function iframe()
  163. {
  164. $val = input('post.val', 0);
  165. if ($val != 0 && $val != 1) {
  166. return $this->error(lang('admin/index/clear_ok'));
  167. }
  168. if ($val == 1) {
  169. cookie('is_iframe', 'yes');
  170. } else {
  171. cookie('is_iframe', null);
  172. }
  173. return $this->success(lang('admin/index/iframe'));
  174. }
  175. public function unlocked()
  176. {
  177. $param = input();
  178. $password = $param['password'];
  179. if ($this->_admin['admin_pwd'] != md5($password)) {
  180. return $this->error(lang('admin/index/pass_err'));
  181. }
  182. return $this->success(lang('admin/index/unlock_ok'));
  183. }
  184. public function check_back_link()
  185. {
  186. $param = input();
  187. $res = mac_check_back_link($param['url']);
  188. return json($res);
  189. }
  190. public function select()
  191. {
  192. $param = input();
  193. $tpl = $param['tpl'];
  194. $tab = $param['tab'];
  195. $col = $param['col'];
  196. $ids = $param['ids'];
  197. $url = $param['url'];
  198. $val = $param['val'];
  199. $refresh = $param['refresh'];
  200. if (empty($tpl) || empty($tab) || empty($col) || empty($ids) || empty($url)) {
  201. return $this->error(lang('param_err'));
  202. }
  203. if (is_array($ids)) {
  204. $ids = join(',', $ids);
  205. }
  206. if (empty($refresh)) {
  207. $refresh = 'yes';
  208. }
  209. $url = url($url);
  210. $mid = 1;
  211. if ($tab == 'art') {
  212. $mid = 2;
  213. } elseif ($tab == 'actor') {
  214. $mid = 8;
  215. } elseif ($tab == 'website') {
  216. $mid = 11;
  217. }
  218. $this->assign('mid', $mid);
  219. if ($tpl == 'select_type') {
  220. $type_tree = model('Type')->getCache('type_tree');
  221. $this->assign('type_tree', $type_tree);
  222. } elseif ($tpl == 'select_level') {
  223. $level_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  224. $this->assign('level_list', $level_list);
  225. }
  226. $this->assign('refresh', $refresh);
  227. $this->assign('url', $url);
  228. $this->assign('tab', $tab);
  229. $this->assign('col', $col);
  230. $this->assign('ids', $ids);
  231. $this->assign('val', $val);
  232. return $this->fetch('admin@public/' . $tpl);
  233. }
  234. public function get_system_status()
  235. {
  236. //判斷系統
  237. $os_name = PHP_OS;
  238. $os_data = [];
  239. $os_data['os_name'] = $os_name;
  240. if (strtoupper(substr($os_name, 0, 3)) === 'WIN') {
  241. // Windows系统
  242. $os_data['os_name'] = 'WINDOWS';
  243. $os_data['disk_datas'] = $this->get_spec_disk('all');
  244. $os_data['cpu_usage'] = $this->getCpuUsage();
  245. $mem_arr = $this->getMemoryUsage();
  246. $os_data['mem_usage'] = $mem_arr['usage'];
  247. $os_data['mem_total'] = round($mem_arr['TotalVisibleMemorySize'] / 1024, 2);
  248. $os_data['mem_used'] = $os_data['mem_total'] - round($mem_arr['FreePhysicalMemory'] / 1024, 2);
  249. } else {
  250. // Linux和FreeBSD的处理逻辑
  251. $os_data['os_name'] = strtoupper($os_name);
  252. // 获取磁盘信息
  253. $totalSpace = 0;
  254. $freeSpace = 0;
  255. if (function_exists('disk_total_space') && function_exists('disk_free_space')) {
  256. $totalSpace = @disk_total_space('/');
  257. $freeSpace = @disk_free_space('/');
  258. }
  259. if ($totalSpace > 0) {
  260. $totalSpaceGB = round($totalSpace / (1024 * 1024 * 1024), 2);
  261. $freeSpaceGB = round($freeSpace / (1024 * 1024 * 1024), 2);
  262. $usedSpaceGB = round($totalSpaceGB - $freeSpaceGB, 2);
  263. $tmp_disk_data = [];
  264. $tmp_disk_data[0] = $usedSpaceGB;
  265. $tmp_disk_data[1] = $totalSpaceGB;
  266. $tmp_disk_data[2] = round(100 - ($freeSpaceGB / $totalSpaceGB * 100), 2);
  267. $os_data['disk_datas']['/'] = $tmp_disk_data;
  268. } else {
  269. $os_data['disk_datas']['/'] = [0, 0, 0];
  270. }
  271. // 获取内存和CPU信息
  272. $mem_arr = $this->get_unix_server_memory_usage();
  273. $os_data['cpu_usage'] = $this->get_unix_server_cpu_usage();
  274. $os_data['mem_usage'] = $mem_arr['usage'];
  275. $os_data['mem_used'] = $mem_arr['used'];
  276. $os_data['mem_total'] = $mem_arr['total'];
  277. }
  278. return $os_data;
  279. }
  280. private function byte_format($size, $dec = 2)
  281. {
  282. if ($size == 0) {
  283. return "0 B";
  284. }
  285. $a = array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
  286. $pos = 0;
  287. while ($size >= 1024) {
  288. $size /= 1024;
  289. $pos++;
  290. }
  291. return round($size, $dec);
  292. }
  293. private function get_disk_space($letter)
  294. {
  295. // 添加函数存在性检查
  296. if (!function_exists('disk_total_space') || !function_exists('disk_free_space')) {
  297. return [];
  298. }
  299. // 获取磁盘信息
  300. $diskct = 0;
  301. $disk = array();
  302. $diskz = 0; //磁盘总容量
  303. $diskk = 0; //磁盘剩余容量
  304. $is_disk = $letter . ':';
  305. if (@\disk_total_space($is_disk) != NULL) {
  306. $diskct++;
  307. $total_space = @\disk_total_space($is_disk);
  308. $free_space = @\disk_free_space($is_disk);
  309. // 转换为GB并保留两位小数
  310. $total_space_gb = round($total_space / (1024 * 1024 * 1024), 2);
  311. $free_space_gb = round($free_space / (1024 * 1024 * 1024), 2);
  312. $disk[$letter][0] = round($this->byte_format($free_space), 2);
  313. $disk[$letter][1] = round($this->byte_format($total_space), 2);
  314. if ($total_space > 0) {
  315. $disk[$letter][2] = round(100 - ($free_space_gb / $total_space_gb * 100), 2);
  316. } else {
  317. $disk[$letter][2] = 0;
  318. }
  319. $diskk += round($this->byte_format($free_space), 2);
  320. $diskz += round($this->byte_format($total_space), 2);
  321. }
  322. return $disk;
  323. }
  324. private function get_spec_disk($type = 'system')
  325. {
  326. $disk = array();
  327. switch ($type) {
  328. case 'system':
  329. //strrev(array_pop(explode(':',strrev(getenv_info('SystemRoot')))));//取得系统盘符
  330. $disk = $this->get_disk_space(strrev(array_pop(explode(':', strrev(getenv('SystemRoot'))))));
  331. break;
  332. case 'all':
  333. foreach (range('b', 'z') as $letter) {
  334. $disk = array_merge($disk, $this->get_disk_space(strtoupper($letter)));
  335. }
  336. break;
  337. default:
  338. $disk = $this->get_disk_space($type);
  339. break;
  340. }
  341. return $disk;
  342. }
  343. private function isComAvailable()
  344. {
  345. return extension_loaded('com_dotnet');
  346. }
  347. private function getCpuUsage()
  348. {
  349. if (!$this->isComAvailable()) {
  350. if (!function_exists('shell_exec')) {
  351. return 0;
  352. }
  353. try {
  354. $cmd = "wmic cpu get loadpercentage";
  355. $output = shell_exec($cmd);
  356. if ($output) {
  357. preg_match('/\d+/', $output, $matches);
  358. if (isset($matches[0])) {
  359. return (float)$matches[0];
  360. }
  361. }
  362. } catch (Exception $e) {
  363. return 0;
  364. }
  365. return 0;
  366. }
  367. try {
  368. $wmi = new \COM('WinMgmts:\\\\.');
  369. $cpus = $wmi->ExecQuery('SELECT LoadPercentage FROM Win32_Processor');
  370. $cpu_load = 0;
  371. $cpu_count = 0;
  372. foreach ($cpus as $cpu) {
  373. $cpu_load += $cpu->LoadPercentage;
  374. $cpu_count++;
  375. }
  376. return $cpu_count > 0 ? round($cpu_load / $cpu_count, 2) : 0;
  377. } catch (Exception $e) {
  378. if (!function_exists('shell_exec')) {
  379. return 0;
  380. }
  381. try {
  382. $cmd = "wmic cpu get loadpercentage";
  383. $output = shell_exec($cmd);
  384. if ($output) {
  385. preg_match('/\d+/', $output, $matches);
  386. if (isset($matches[0])) {
  387. return (float)$matches[0];
  388. }
  389. }
  390. } catch (Exception $e) {
  391. return 0;
  392. }
  393. return 0;
  394. }
  395. }
  396. private function getMemoryUsage()
  397. {
  398. if (!$this->isComAvailable()) {
  399. if (!function_exists('shell_exec')) {
  400. return [
  401. 'TotalVisibleMemorySize' => 0,
  402. 'FreePhysicalMemory' => 0,
  403. 'usage' => 0
  404. ];
  405. }
  406. try {
  407. $cmd = "wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /Value";
  408. $output = shell_exec($cmd);
  409. if ($output) {
  410. preg_match('/TotalVisibleMemorySize=(\d+)/i', $output, $total);
  411. preg_match('/FreePhysicalMemory=(\d+)/i', $output, $free);
  412. if (isset($total[1]) && isset($free[1])) {
  413. $total_mem = (float)$total[1];
  414. $free_mem = (float)$free[1];
  415. $used_mem = $total_mem - $free_mem;
  416. return [
  417. 'TotalVisibleMemorySize' => $total_mem,
  418. 'FreePhysicalMemory' => $free_mem,
  419. 'usage' => $total_mem > 0 ? round(($used_mem / $total_mem) * 100, 2) : 0
  420. ];
  421. }
  422. }
  423. } catch (Exception $e) {
  424. return [
  425. 'TotalVisibleMemorySize' => 0,
  426. 'FreePhysicalMemory' => 0,
  427. 'usage' => 0
  428. ];
  429. }
  430. }
  431. try {
  432. $wmi = new \COM('WinMgmts:\\\\.');
  433. $os = $wmi->ExecQuery('SELECT TotalVisibleMemorySize,FreePhysicalMemory FROM Win32_OperatingSystem');
  434. foreach ($os as $item) {
  435. $total = $item->TotalVisibleMemorySize;
  436. $free = $item->FreePhysicalMemory;
  437. $used = $total - $free;
  438. return [
  439. 'TotalVisibleMemorySize' => $total,
  440. 'FreePhysicalMemory' => $free,
  441. 'usage' => $total > 0 ? round(($used / $total) * 100, 2) : 0
  442. ];
  443. }
  444. } catch (Exception $e) {
  445. if (!function_exists('shell_exec')) {
  446. return [
  447. 'TotalVisibleMemorySize' => 0,
  448. 'FreePhysicalMemory' => 0,
  449. 'usage' => 0
  450. ];
  451. }
  452. try {
  453. $cmd = "wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /Value";
  454. $output = shell_exec($cmd);
  455. if ($output) {
  456. preg_match('/TotalVisibleMemorySize=(\d+)/i', $output, $total);
  457. preg_match('/FreePhysicalMemory=(\d+)/i', $output, $free);
  458. if (isset($total[1]) && isset($free[1])) {
  459. $total_mem = (float)$total[1];
  460. $free_mem = (float)$free[1];
  461. $used_mem = $total_mem - $free_mem;
  462. return [
  463. 'TotalVisibleMemorySize' => $total_mem,
  464. 'FreePhysicalMemory' => $free_mem,
  465. 'usage' => $total_mem > 0 ? round(($used_mem / $total_mem) * 100, 2) : 0
  466. ];
  467. }
  468. }
  469. } catch (Exception $e) {
  470. return [
  471. 'TotalVisibleMemorySize' => 0,
  472. 'FreePhysicalMemory' => 0,
  473. 'usage' => 0
  474. ];
  475. }
  476. }
  477. }
  478. private function get_unix_server_memory_usage()
  479. {
  480. // 首先尝试使用通用的 sysinfo 方法
  481. if (function_exists('sysinfo')) {
  482. $si = sysinfo();
  483. if ($si) {
  484. $total_mem = $si['totalram'] * $si['mem_unit'] / 1024 / 1024;
  485. $free_mem = $si['freeram'] * $si['mem_unit'] / 1024 / 1024;
  486. $used_mem = $total_mem - $free_mem;
  487. $usage = ($total_mem > 0) ? ($used_mem / $total_mem) * 100 : 0;
  488. return [
  489. 'total' => round($total_mem, 2),
  490. 'used' => round($used_mem, 2),
  491. 'usage' => round($usage, 2)
  492. ];
  493. }
  494. }
  495. // 尝试不同的内存信息获取方法
  496. $methods = [
  497. // Linux free 命令
  498. 'free' => function() {
  499. if (!function_exists('shell_exec')) {
  500. return null;
  501. }
  502. $free = shell_exec('free');
  503. if ($free) {
  504. $free = (string)trim($free);
  505. $free_arr = explode("\n", $free);
  506. $mem = explode(" ", $free_arr[1]);
  507. $mem = array_filter($mem);
  508. $mem = array_merge($mem);
  509. if (count($mem) >= 3 && !empty($mem[1])) {
  510. return [
  511. 'total' => round($mem[1] / 1024, 2),
  512. 'used' => round($mem[2] / 1024, 2),
  513. 'usage' => round($mem[2] / $mem[1] * 100, 2)
  514. ];
  515. }
  516. }
  517. return null;
  518. },
  519. // FreeBSD/Unix sysctl 命令
  520. 'sysctl' => function() {
  521. if (!function_exists('shell_exec')) {
  522. return null;
  523. }
  524. $sysctl = shell_exec('/sbin/sysctl -n hw.physmem hw.pagesize vm.stats.vm.v_free_count 2>/dev/null');
  525. if ($sysctl) {
  526. $lines = explode("\n", trim($sysctl));
  527. if (count($lines) >= 3 && !empty($lines[0])) {
  528. $total_mem = $lines[0] / 1024 / 1024;
  529. $page_size = $lines[1];
  530. $free_pages = $lines[2];
  531. $free_mem = ($free_pages * $page_size) / 1024 / 1024;
  532. $used_mem = $total_mem - $free_mem;
  533. $usage = $total_mem > 0 ? ($used_mem / $total_mem) * 100 : 0;
  534. return [
  535. 'total' => round($total_mem, 2),
  536. 'used' => round($used_mem, 2),
  537. 'usage' => round($usage, 2)
  538. ];
  539. }
  540. }
  541. return null;
  542. },
  543. // /proc/meminfo 文件读取
  544. 'proc' => function() {
  545. if (!is_readable('/proc/meminfo')) {
  546. return null;
  547. }
  548. $meminfo = file_get_contents('/proc/meminfo');
  549. if ($meminfo) {
  550. preg_match('/MemTotal:\s+(\d+)/i', $meminfo, $total);
  551. preg_match('/MemFree:\s+(\d+)/i', $meminfo, $free);
  552. preg_match('/Cached:\s+(\d+)/i', $meminfo, $cached);
  553. preg_match('/Buffers:\s+(\d+)/i', $meminfo, $buffers);
  554. if (isset($total[1]) && isset($free[1])) {
  555. $total_mem = $total[1] / 1024;
  556. $free_mem = ($free[1] + (isset($cached[1]) ? $cached[1] : 0) + (isset($buffers[1]) ? $buffers[1] : 0)) / 1024;
  557. $used_mem = $total_mem - $free_mem;
  558. $usage = ($total_mem > 0) ? ($used_mem / $total_mem) * 100 : 0;
  559. return [
  560. 'total' => round($total_mem, 2),
  561. 'used' => round($used_mem, 2),
  562. 'usage' => round($usage, 2)
  563. ];
  564. }
  565. }
  566. return null;
  567. }
  568. ];
  569. // 依次尝试各种方法
  570. foreach ($methods as $method) {
  571. $result = $method();
  572. if ($result !== null) {
  573. return $result;
  574. }
  575. }
  576. // 如果所有方法都失败,返回默认值
  577. return [
  578. 'total' => 0,
  579. 'used' => 0,
  580. 'usage' => 0
  581. ];
  582. }
  583. private function get_unix_server_cpu_usage()
  584. {
  585. // 首先尝试使用通用的方法
  586. $methods = [
  587. // top 命令 (Linux)
  588. 'top_linux' => function() {
  589. if (!function_exists('shell_exec')) {
  590. return null;
  591. }
  592. $cpu_load = shell_exec("top -bn1 | grep 'Cpu(s)' 2>/dev/null");
  593. if (!empty($cpu_load)) {
  594. if (preg_match('/(\d+[.,]\d+).*?us/', $cpu_load, $matches)) {
  595. return round((float)str_replace(',', '.', $matches[1]), 2);
  596. }
  597. }
  598. return null;
  599. },
  600. // top 命令 (FreeBSD)
  601. 'top_bsd' => function() {
  602. if (!function_exists('shell_exec')) {
  603. return null;
  604. }
  605. $cpu_load = shell_exec("top -d2 -n1 | grep 'CPU:' 2>/dev/null");
  606. if (!empty($cpu_load)) {
  607. if (preg_match('/(\d+\.\d+)%\s+user/', $cpu_load, $matches)) {
  608. return round((float)$matches[1], 2);
  609. }
  610. }
  611. return null;
  612. },
  613. // sysctl (FreeBSD/Unix)
  614. 'sysctl' => function() {
  615. if (!function_exists('shell_exec')) {
  616. return null;
  617. }
  618. $cpu_load = shell_exec('/sbin/sysctl -n kern.cp_time 2>/dev/null');
  619. if (!empty($cpu_load)) {
  620. $times = explode(" ", trim($cpu_load));
  621. if (count($times) >= 5) {
  622. $total = array_sum($times);
  623. $idle = $times[4];
  624. return $total > 0 ? round(100 - ($idle * 100 / $total), 2) : 0;
  625. }
  626. }
  627. return null;
  628. },
  629. // /proc/stat 文件读取
  630. 'proc' => function() {
  631. if (is_readable('/proc/stat')) {
  632. $stats1 = file_get_contents('/proc/stat');
  633. usleep(100000); // 等待100ms
  634. $stats2 = file_get_contents('/proc/stat');
  635. if ($stats1 && $stats2) {
  636. $stats_arr1 = explode(' ', trim(explode("\n", $stats1)[0]));
  637. $stats_arr2 = explode(' ', trim(explode("\n", $stats2)[0]));
  638. if (count($stats_arr1) >= 5 && count($stats_arr2) >= 5) {
  639. $cpu1 = array_sum(array_slice($stats_arr1, 1));
  640. $cpu2 = array_sum(array_slice($stats_arr2, 1));
  641. $idle1 = $stats_arr1[4];
  642. $idle2 = $stats_arr2[4];
  643. $diff_cpu = $cpu2 - $cpu1;
  644. $diff_idle = $idle2 - $idle1;
  645. if ($diff_cpu > 0) {
  646. return round(100 * (1 - $diff_idle / $diff_cpu), 2);
  647. }
  648. }
  649. }
  650. }
  651. return null;
  652. }
  653. ];
  654. // 依次尝试各种方法
  655. foreach ($methods as $method) {
  656. $result = $method();
  657. if ($result !== null) {
  658. return $result;
  659. }
  660. }
  661. return 0;
  662. }
  663. private function _getServerLoadLinuxData()
  664. {
  665. if (is_readable("/proc/stat")) {
  666. $stats = @file_get_contents("/proc/stat");
  667. if ($stats !== false) {
  668. // Remove double spaces to make it easier to extract values with explode()
  669. $stats = preg_replace("/[[:blank:]]+/", " ", $stats);
  670. // Separate lines
  671. $stats = str_replace(array("\r\n", "\n\r", "\r"), "\n", $stats);
  672. $stats = explode("\n", $stats);
  673. // Separate values and find line for main CPU load
  674. foreach ($stats as $statLine) {
  675. $statLineData = explode(" ", trim($statLine));
  676. // Found!
  677. if (
  678. (count($statLineData) >= 5) &&
  679. ($statLineData[0] == "cpu")
  680. ) {
  681. return array(
  682. $statLineData[1],
  683. $statLineData[2],
  684. $statLineData[3],
  685. $statLineData[4],
  686. );
  687. }
  688. }
  689. }
  690. }
  691. return null;
  692. }
  693. private function getAdminDashboardData()
  694. {
  695. $result = [];
  696. //已注册总用户数量
  697. $result['user_count'] = model('User')->count();
  698. $result['user_count'] = number_format($result['user_count'], 0, '.', ',');
  699. //已审核用户数量
  700. $result['user_active_count'] = model('User')->where('user_status', 1)->count();
  701. $result['user_active_count'] = number_format($result['user_active_count'], 0, '.', ',');
  702. $today_start = strtotime(date('Y-m-d 00:00:00'));
  703. $today_end = $today_start + 86399;
  704. //本日来客量
  705. $result['today_visit_count'] = model('Visit')->where('visit_time', 'between', $today_start . ',' . $today_end)->count();
  706. $result['today_visit_count'] = number_format($result['today_visit_count'], 0, '.', ',');
  707. //本日总入金
  708. $result['today_money_get'] = model('Order')->where('order_time', 'between', $today_start . ',' . $today_end)->where('order_status', 1)->sum('order_price');
  709. $result['today_money_get'] = number_format($result['today_money_get'], 2, '.', ',');
  710. //前七天 每日用户访问数
  711. $tmp_arr = Db::query("select FROM_UNIXTIME(visit_time, '%Y-%c-%d' ) days,count(*) count from (SELECT * from ".config('database.prefix')."visit where visit_time >= (unix_timestamp(CURDATE())-604800)) as temp group by days");
  712. $result['seven_day_visit_day'] = [];
  713. $result['seven_day_visit_count'] = [];
  714. $result['raise_visit_user_today'] = 0;
  715. if (is_array($tmp_arr) && count($tmp_arr) > 1 && (strtotime(end($tmp_arr)['days']) == strtotime(date('Y-m-d')))) {
  716. $yesterday_visit_count = $tmp_arr[count($tmp_arr) - 2]['count'];
  717. $lastday_visit_count = end($tmp_arr)['count'];
  718. if ($yesterday_visit_count != 0) {
  719. $result['raise_visit_user_today'] = number_format((($lastday_visit_count - $yesterday_visit_count) / $yesterday_visit_count) * 100, 2, '.', ',');
  720. } else {
  721. $result['raise_visit_user_today'] = 0;
  722. }
  723. }
  724. foreach ($tmp_arr as $data) {
  725. array_push($result['seven_day_visit_day'], $data['days']);
  726. array_push($result['seven_day_visit_count'], $data['count']);
  727. }
  728. //近七日用户访问总量
  729. $result['seven_day_visit_total_count'] = 0;
  730. foreach ($result['seven_day_visit_data'] as $k => $value) {
  731. $result['seven_day_visit_total_count'] = $result['seven_day_visit_total_count'] + $value['count'];
  732. }
  733. $result['seven_day_visit_total_count'] = number_format($result['seven_day_visit_total_count'], 0, '.', ',');
  734. //前七天 每日用户注册数
  735. $result['seven_day_reg_data'] = Db::query("select FROM_UNIXTIME(user_reg_time, '%Y-%c-%d' ) days,count(*) count from (SELECT * from ".config('database.prefix')."user where user_reg_time >= (unix_timestamp(CURDATE())-604800)) as tmp group by days");
  736. //近七日用户注册总量
  737. $result['seven_day_reg_total_count'] = 0;
  738. $result['seven_day_reg_day'] = [];
  739. $result['seven_day_reg_count'] = [];
  740. foreach ($result['seven_day_reg_data'] as $k => $value) {
  741. array_push($result['seven_day_reg_day'], $value['days']);
  742. array_push($result['seven_day_reg_count'], $value['count']);
  743. $result['seven_day_reg_total_count'] = $result['seven_day_reg_total_count'] + $value['count'];
  744. }
  745. //比較前一天的註冊量漲幅
  746. $result['raise_reg_user_today'] = 0;
  747. if (is_array($result['seven_day_reg_data']) && count($result['seven_day_reg_data']) > 1 && (strtotime(end($result['seven_day_reg_data'])['days']) == strtotime(date('Y-m-d')))) {
  748. $yesterday_reg_count = $result['seven_day_reg_data'][count($result['seven_day_reg_data']) - 2]['count'];
  749. $lastday_reg_count = end($result['seven_day_reg_data'])['count'];
  750. if ($yesterday_reg_count != 0) {
  751. $result['raise_reg_user_today'] = number_format((($lastday_reg_count - $yesterday_reg_count) / $yesterday_reg_count) * 100, 2, '.', ',');
  752. } else {
  753. $result['raise_reg_user_today'] = 0;
  754. }
  755. }
  756. $result['seven_day_reg_total_count'] = number_format($result['seven_day_reg_total_count'], 0, '.', ',');
  757. return $result;
  758. }
  759. public function rangeDateDailyVisit()
  760. {
  761. $range_daily_visit_data = Db::query("select FROM_UNIXTIME(visit_time, '%Y-%c-%d' ) days,count(*) count from (SELECT * from ".config('database.prefix')."visit where visit_time >= " . strtotime($_POST['startDate']) . "&& visit_time <= " . strtotime($_POST['endDate']) . " ) as temp group by days");
  762. $result = [];
  763. $range_visit_day = [];
  764. $range_visit_count = [];
  765. $range_visit_sum = 0;
  766. foreach ($range_daily_visit_data as $data) {
  767. $range_visit_sum = $range_visit_sum + $data['count'];
  768. array_push($range_visit_day, $data['days']);
  769. array_push($range_visit_count, $data['count']);
  770. }
  771. $result['days'] = $range_visit_day;
  772. $result['count'] = $range_visit_count;
  773. $result['sum'] = $range_visit_sum;
  774. return json_encode($result);
  775. }
  776. public function botlist()
  777. {
  778. $day_arr = [];
  779. //列出最近10天的日期
  780. for ($i = 0; $i < 7; $i++) {
  781. $day_arr[$i] = date('Y-m-d', time() - $i * 60 * 60 * 24);
  782. }
  783. $google_arr = [];
  784. $baidu_arr = [];
  785. $sogou_arr = [];
  786. $soso_arr = [];
  787. $yahoo_arr = [];
  788. $msn_arr = [];
  789. $msn_bot_arr = [];
  790. $sohu_arr = [];
  791. $yodao_arr = [];
  792. $twiceler_arr = [];
  793. $alexa_arr = [];
  794. $bot_list = [];
  795. foreach ($day_arr as $day_vo) {
  796. if (file_exists(ROOT_PATH . 'runtime/log/bot/' . $day_vo . '.txt')) {
  797. $bot_content = file_get_contents(ROOT_PATH . 'runtime/log/bot/' . $day_vo . '.txt');
  798. } else {
  799. $bot_content = '';
  800. }
  801. $google_arr[$day_vo] = substr_count($bot_content, 'Google');
  802. $baidu_arr[$day_vo] = substr_count($bot_content, 'Baidu');
  803. $sogou_arr[$day_vo] = substr_count($bot_content, 'Sogou');
  804. $soso_arr[$day_vo] = substr_count($bot_content, 'SOSO');
  805. $yahoo_arr[$day_vo] = substr_count($bot_content, 'Yahoo');
  806. $msn_arr[$day_vo] = substr_count($bot_content, 'MSN');
  807. $msn_bot_arr[$day_vo] = substr_count($bot_content, 'msnbot');
  808. $sohu_arr[$day_vo] = substr_count($bot_content, 'Sohu');
  809. $yodao_arr[$day_vo] = substr_count($bot_content, 'Yodao');
  810. $twiceler_arr[$day_vo] = substr_count($bot_content, 'Twiceler');
  811. $alexa_arr[$day_vo] = substr_count($bot_content, 'Alexa');
  812. }
  813. $bot_list['Google']['key'] = array_keys($google_arr);
  814. $bot_list['Google']['values'] = array_values($google_arr);
  815. $bot_list['Baidu']['keys'] = array_keys($baidu_arr);
  816. $bot_list['Baidu']['values'] = array_values($baidu_arr);
  817. $bot_list['Sogou']['keys'] = array_keys($sogou_arr);
  818. $bot_list['Sogou']['values'] = array_values($sogou_arr);
  819. $bot_list['SOSO']['keys'] = array_keys($soso_arr);
  820. $bot_list['SOSO']['values'] = array_values($soso_arr);
  821. $bot_list['Yahoo']['keys'] = array_keys($yahoo_arr);
  822. $bot_list['Yahoo']['values'] = array_values($yahoo_arr);
  823. $bot_list['MSN']['keys'] = array_keys($msn_arr);
  824. $bot_list['MSN']['values'] = array_values($msn_arr);
  825. $bot_list['msnbot']['keys'] = array_keys($msn_bot_arr);
  826. $bot_list['msnbot']['values'] = array_values($msn_bot_arr);
  827. $bot_list['Sohu']['keys'] = array_keys($sohu_arr);
  828. $bot_list['Sohu']['values'] = array_values($sohu_arr);
  829. $bot_list['Yodao']['keys'] = array_keys($yodao_arr);
  830. $bot_list['Yodao']['values'] = array_values($yodao_arr);
  831. $bot_list['Twiceler']['keys'] = array_keys($twiceler_arr);
  832. $bot_list['Twiceler']['values'] = array_values($twiceler_arr);
  833. $bot_list['Alexa']['keys'] = array_keys($alexa_arr);
  834. $bot_list['Alexa']['values'] = array_values($alexa_arr);
  835. if (!empty($_POST['category'])) {
  836. return $bot_list[$_POST['category']];
  837. } else {
  838. return $bot_list;
  839. }
  840. }
  841. public function botlog()
  842. {
  843. $parm = input();
  844. $data = $parm['data'];
  845. $bot_content = file_get_contents(ROOT_PATH . 'runtime/log/bot/' . $data . '.txt');
  846. $bot_list = array_slice(array_reverse(explode("\r\n", trim($bot_content))), 0, 20);
  847. $this->assign('bot_list', $bot_list);
  848. return $this->fetch('admin@others/botlog');
  849. }
  850. }