diff --git a/app/Command/DailyMail.php b/app/Command/DailyMail.php index ad8e76c7..828f6217 100644 --- a/app/Command/DailyMail.php +++ b/app/Command/DailyMail.php @@ -17,45 +17,45 @@ class DailyMail { $users = User::all(); $logs = Ann::orderBy('id', 'desc')->get(); - $text1=""; - + $text1 = ""; + foreach ($logs as $log) { - if (strpos($log->content, "Links")===false) { - $text1=$text1.$log->content."

"; + if (strpos($log->content, "Links") === false) { + $text1 = $text1 . $log->content . "

"; } } - + $lastday_total = 0; - + foreach ($users as $user) { - $lastday = (($user->u+$user->d)-$user->last_day_t)/1024/1024; - $lastday_total += (($user->u+$user->d)-$user->last_day_t); - - if ($user->sendDailyMail==1) { - echo "Send daily mail to user: ".$user->id; - $subject = Config::get('appName')."-每日流量报告以及公告"; + $lastday = (($user->u + $user->d) - $user->last_day_t) / 1024 / 1024; + $lastday_total += (($user->u + $user->d) - $user->last_day_t); + + if ($user->sendDailyMail == 1) { + echo "Send daily mail to user: " . $user->id; + $subject = Config::get('appName') . "-每日流量报告以及公告"; $to = $user->email; - $text = "下面是系统中目前的公告:

".$text1."

晚安!"; - + $text = "下面是系统中目前的公告:

" . $text1 . "

晚安!"; + try { Mail::send($to, $subject, 'news/daily-traffic-report.tpl', [ - "user" => $user,"text" => $text,"lastday"=>$lastday + "user" => $user, "text" => $text, "lastday" => $lastday ], [ ]); } catch (\Exception $e) { echo $e->getMessage(); } - $text=""; + $text = ""; } } - + $sts = new Analytics(); - - Telegram::Send("各位老爷少奶奶,我来为大家报告一下系统今天的运行状况哈~". - PHP_EOL. - "今日签到人数:".$sts->getTodayCheckinUser().PHP_EOL. - "今日使用总流量:".Tools::flowAutoShow($lastday_total).PHP_EOL. - "晚安~" + + Telegram::Send("各位老爷少奶奶,我来为大家报告一下系统今天的运行状况哈~" . + PHP_EOL . + "今日签到人数:" . $sts->getTodayCheckinUser() . PHP_EOL . + "今日使用总流量:" . Tools::flowAutoShow($lastday_total) . PHP_EOL . + "晚安~" ); } @@ -64,7 +64,7 @@ class DailyMail { $users = User::all(); foreach ($users as $user) { - $user->last_day_t=($user->u+$user->d); + $user->last_day_t = ($user->u + $user->d); $user->save(); } } diff --git a/app/Command/ExtMail.php b/app/Command/ExtMail.php index a9fbd9be..1c650a87 100644 --- a/app/Command/ExtMail.php +++ b/app/Command/ExtMail.php @@ -13,16 +13,16 @@ class ExtMail { $users = User::all(); foreach ($users as $user) { - if ($user->t==0) { - echo "Send daily mail to user: ".$user->id; - $subject = Config::get('appName')."-期待您的回归"; + if ($user->t == 0) { + echo "Send daily mail to user: " . $user->id; + $subject = Config::get('appName') . "-期待您的回归"; $to = $user->email; - $text = "似乎您在".Config::get('appName')."上的流量一直是 0 呢(P.S:也可能是您没有使用 ss 而使用了其他还不能计入流量的方式....),如果您在使用上遇到了任何困难,请不要犹豫,登录到".Config::get('appName').",您就会知道如何使用了,特别是对于 iOS 用户,最近在使用的优化上大家都付出了很多的努力。期待您的回归~" ; + $text = "似乎您在" . Config::get('appName') . "上的流量一直是 0 呢(P.S:也可能是您没有使用 ss 而使用了其他还不能计入流量的方式....),如果您在使用上遇到了任何困难,请不要犹豫,登录到" . Config::get('appName') . ",您就会知道如何使用了,特别是对于 iOS 用户,最近在使用的优化上大家都付出了很多的努力。期待您的回归~"; try { Mail::send($to, $subject, 'ext/back.tpl', [ - "user" => $user,"text" => $text - ], [ - ]); + "user" => $user, "text" => $text + ], [ + ]); } catch (\Exception $e) { echo $e->getMessage(); } @@ -34,14 +34,14 @@ class ExtMail { $users = User::all(); foreach ($users as $user) { - if ($user->t!=0&&$user->t<1451577599) { - echo "Send daily mail to user: ".$user->id; - $subject = Config::get('appName')."-期待您的回归"; + if ($user->t != 0 && $user->t < 1451577599) { + echo "Send daily mail to user: " . $user->id; + $subject = Config::get('appName') . "-期待您的回归"; $to = $user->email; - $text = "似乎您在 2017 年以来就没有使用过".Config::get('appName')."了呢,如果您在使用上遇到了任何困难,请不要犹豫,登录到".Config::get('appName').",您就会知道如何使用了,特别是对于 iOS 用户,最近在使用的优化上大家都付出了很多的努力。期待您的回归~" ; + $text = "似乎您在 2017 年以来就没有使用过" . Config::get('appName') . "了呢,如果您在使用上遇到了任何困难,请不要犹豫,登录到" . Config::get('appName') . ",您就会知道如何使用了,特别是对于 iOS 用户,最近在使用的优化上大家都付出了很多的努力。期待您的回归~"; try { Mail::send($to, $subject, 'ext/back.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { diff --git a/app/Command/FinanceMail.php b/app/Command/FinanceMail.php index 85f3c5eb..f8e65922 100644 --- a/app/Command/FinanceMail.php +++ b/app/Command/FinanceMail.php @@ -19,205 +19,205 @@ class FinanceMail { public static function sendFinanceMail_day() { - $datatables = new Datatables(new DatatablesHelper()); + $datatables = new Datatables(new DatatablesHelper()); $datatables->query( - 'select code.number, code.userid, code.usedatetime from code + 'select code.number, code.userid, code.usedatetime from code where TO_DAYS(NOW()) - TO_DAYS(code.usedatetime) = 1 and code.type = -1 and code.isused= 1'); - $text_json=$datatables->generate(); - $text_array=json_decode($text_json,true); - $codes=$text_array['data']; - $text_html=''; - $income_count=0; - $income_total=0.00; - foreach($codes as $code){ - $text_html.=''; - $text_html.=''; - $text_html.=''; - $user=User::find($code['userid']); - $text_html.=''; - $text_html.=''; - $text_html.=''; - $income_count+=1; - $income_total+=$code['number']; - } - //易付通的单独表 - $datatables2 = new Datatables(new DatatablesHelper()); - $datatables2->query('select COUNT(*) as "count_yft" from INFORMATION_SCHEMA.TABLES where TABLE_NAME = "yft_order_info"'); - $count_yft=$datatables2->generate(); - if(strpos($count_yft,'"count_yft":1')){ - $datatables2->query( - 'select yft_order_info.price, yft_order_info.user_id, yft_order_info.create_time from yft_order_info + $text_json = $datatables->generate(); + $text_array = json_decode($text_json, true); + $codes = $text_array['data']; + $text_html = '
金额用户ID用户名充值时间
'.$code['number'].''.$code['userid'].''.$user->user_name.''.$code['usedatetime'].'
'; + $income_count = 0; + $income_total = 0.00; + foreach ($codes as $code) { + $text_html .= ''; + $text_html .= ''; + $text_html .= ''; + $user = User::find($code['userid']); + $text_html .= ''; + $text_html .= ''; + $text_html .= ''; + $income_count += 1; + $income_total += $code['number']; + } + //易付通的单独表 + $datatables2 = new Datatables(new DatatablesHelper()); + $datatables2->query('select COUNT(*) as "count_yft" from INFORMATION_SCHEMA.TABLES where TABLE_NAME = "yft_order_info"'); + $count_yft = $datatables2->generate(); + if (strpos($count_yft, '"count_yft":1')) { + $datatables2->query( + 'select yft_order_info.price, yft_order_info.user_id, yft_order_info.create_time from yft_order_info where TO_DAYS(NOW()) - TO_DAYS(yft_order_info.create_time) = 1 and yft_order_info.state= 1'); - $text_json2=$datatables2->generate(); - $text_array2=json_decode($text_json2,true); - $codes2=$text_array2['data']; - foreach($codes2 as $code2){ - $text_html.=''; - $text_html.=''; - $text_html.=''; - $user=User::find($code2['user_id']); - $text_html.=''; - $text_html.=''; - $text_html.=''; - $income_count+=1; - $income_total+=$code['price']; - } - } - $text_html.='
金额用户ID用户名充值时间
' . $code['number'] . '' . $code['userid'] . '' . $user->user_name . '' . $code['usedatetime'] . '
'.$code2['price'].''.$code2['user_id'].''.$user->user_name.''.$code2['create_time'].'
'; - $text_html.='
昨日总收入笔数:'.$income_count.'
昨日总收入金额:'.$income_total; + $text_json2 = $datatables2->generate(); + $text_array2 = json_decode($text_json2, true); + $codes2 = $text_array2['data']; + foreach ($codes2 as $code2) { + $text_html .= ''; + $text_html .= '' . $code2['price'] . ''; + $text_html .= '' . $code2['user_id'] . ''; + $user = User::find($code2['user_id']); + $text_html .= '' . $user->user_name . ''; + $text_html .= '' . $code2['create_time'] . ''; + $text_html .= ''; + $income_count += 1; + $income_total += $code['price']; + } + } + $text_html .= ''; + $text_html .= '
昨日总收入笔数:' . $income_count . '
昨日总收入金额:' . $income_total; $adminUser = User::where("is_admin", "=", "1")->get(); foreach ($adminUser as $user) { - echo "Send offline mail to user: ".$user->id; - $subject = Config::get('appName')."-财务日报"; - $to = $user->email; - $title='财务日报'; - $text = $text_html; - try { - Mail::send($to, $subject, 'news/finance.tpl', [ - "user" => $user,"title"=>$title,"text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } - } - - if (Config::get("finance_public")=="true") { - $sts = new Analytics(); - Telegram::Send( - "新鲜出炉的财务日报~".PHP_EOL. - "昨日总收入笔数:".$income_count.PHP_EOL. - "昨日总收入金额:".$income_total.PHP_EOL. - "凌晨也在努力工作~" - ); - } + echo "Send offline mail to user: " . $user->id; + $subject = Config::get('appName') . "-财务日报"; + $to = $user->email; + $title = '财务日报'; + $text = $text_html; + try { + Mail::send($to, $subject, 'news/finance.tpl', [ + "user" => $user, "title" => $title, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + } + + if (Config::get("finance_public") == "true") { + $sts = new Analytics(); + Telegram::Send( + "新鲜出炉的财务日报~" . PHP_EOL . + "昨日总收入笔数:" . $income_count . PHP_EOL . + "昨日总收入金额:" . $income_total . PHP_EOL . + "凌晨也在努力工作~" + ); + } } - public static function sendFinanceMail_week() - { - $datatables = new Datatables(new DatatablesHelper()); + public static function sendFinanceMail_week() + { + $datatables = new Datatables(new DatatablesHelper()); $datatables->query( - 'SELECT code.number FROM code + 'SELECT code.number FROM code WHERE DATEDIFF(NOW(),code.usedatetime) <=7 AND DATEDIFF(NOW(),code.usedatetime) >=1 AND code.isused = 1'); - //每周的第一天是周日,因此统计周日~周六的七天 - $text_json=$datatables->generate(); - $text_array=json_decode($text_json,true); - $codes=$text_array['data']; - $text_html=''; - $income_count=0; - $income_total=0.00; - foreach($codes as $code){ - $income_count+=1; - $income_total+=$code['number']; - } - //易付通的单独表 - $datatables2 = new Datatables(new DatatablesHelper()); - $datatables2->query('select COUNT(*) as "count_yft" from INFORMATION_SCHEMA.TABLES where TABLE_NAME = "yft_order_info"'); - $count_yft=$datatables2->generate(); - if(strpos($count_yft,'"count_yft":1')){ - $datatables2->query( - 'select yft_order_info.price from yft_order_info + //每周的第一天是周日,因此统计周日~周六的七天 + $text_json = $datatables->generate(); + $text_array = json_decode($text_json, true); + $codes = $text_array['data']; + $text_html = ''; + $income_count = 0; + $income_total = 0.00; + foreach ($codes as $code) { + $income_count += 1; + $income_total += $code['number']; + } + //易付通的单独表 + $datatables2 = new Datatables(new DatatablesHelper()); + $datatables2->query('select COUNT(*) as "count_yft" from INFORMATION_SCHEMA.TABLES where TABLE_NAME = "yft_order_info"'); + $count_yft = $datatables2->generate(); + if (strpos($count_yft, '"count_yft":1')) { + $datatables2->query( + 'select yft_order_info.price from yft_order_info where yearweek(date_format(yft_order_info.create_time,\'%Y-%m-%d\')) = yearweek(now())-1 and yft_order_info.state= 1'); - //每周的第一天是周日,因此统计周日~周六的七天 - $text_json2=$datatables2->generate(); - $text_array2=json_decode($text_json2,true); - $codes2=$text_array2['data']; - foreach($codes2 as $code2){ - $income_count+=1; - $income_total+=$code2['price']; - } - } + //每周的第一天是周日,因此统计周日~周六的七天 + $text_json2 = $datatables2->generate(); + $text_array2 = json_decode($text_json2, true); + $codes2 = $text_array2['data']; + foreach ($codes2 as $code2) { + $income_count += 1; + $income_total += $code2['price']; + } + } - $text_html.='
上周总收入笔数:'.$income_count.'
上周总收入金额:'.$income_total; + $text_html .= '
上周总收入笔数:' . $income_count . '
上周总收入金额:' . $income_total; $adminUser = User::where("is_admin", "=", "1")->get(); foreach ($adminUser as $user) { - echo "Send offline mail to user: ".$user->id; - $subject = Config::get('appName').'-财务周报'; - $to = $user->email; - $title='财务周报'; - $text = $text_html; - try { - Mail::send($to, $subject, 'news/finance.tpl', [ - "user" => $user,"title"=>$title,"text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } - } - - if (Config::get("finance_public")=="true") { - $sts = new Analytics(); - Telegram::Send( - "新鲜出炉的财务周报~".PHP_EOL. - "上周总收入笔数:".$income_count.PHP_EOL. - "上周总收入金额:".$income_total.PHP_EOL. - "周末也在努力工作~" - ); - } - } + echo "Send offline mail to user: " . $user->id; + $subject = Config::get('appName') . '-财务周报'; + $to = $user->email; + $title = '财务周报'; + $text = $text_html; + try { + Mail::send($to, $subject, 'news/finance.tpl', [ + "user" => $user, "title" => $title, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + } + + if (Config::get("finance_public") == "true") { + $sts = new Analytics(); + Telegram::Send( + "新鲜出炉的财务周报~" . PHP_EOL . + "上周总收入笔数:" . $income_count . PHP_EOL . + "上周总收入金额:" . $income_total . PHP_EOL . + "周末也在努力工作~" + ); + } + } - public static function sendFinanceMail_month() - { - $datatables = new Datatables(new DatatablesHelper()); + public static function sendFinanceMail_month() + { + $datatables = new Datatables(new DatatablesHelper()); $datatables->query( - 'select code.number from code + 'select code.number from code where date_format(code.usedatetime,\'%Y-%m\')=date_format(date_sub(curdate(), interval 1 month),\'%Y-%m\') and code.type = -1 and code.isused= 1'); - $text_json=$datatables->generate(); - $text_array=json_decode($text_json,true); - $codes=$text_array['data']; - $text_html=''; - $income_count=0; - $income_total=0.00; - foreach($codes as $code){ - $income_count+=1; - $income_total+=$code['number']; - } - $datatables2 = new Datatables(new DatatablesHelper()); - $datatables2->query('select COUNT(*) as "count_yft" from INFORMATION_SCHEMA.TABLES where TABLE_NAME = "yft_order_info"'); - $count_yft=$datatables2->generate(); - if(strpos($count_yft,'"count_yft":1')){ - $datatables2->query( - 'select yft_order_info.price from yft_order_info + $text_json = $datatables->generate(); + $text_array = json_decode($text_json, true); + $codes = $text_array['data']; + $text_html = ''; + $income_count = 0; + $income_total = 0.00; + foreach ($codes as $code) { + $income_count += 1; + $income_total += $code['number']; + } + $datatables2 = new Datatables(new DatatablesHelper()); + $datatables2->query('select COUNT(*) as "count_yft" from INFORMATION_SCHEMA.TABLES where TABLE_NAME = "yft_order_info"'); + $count_yft = $datatables2->generate(); + if (strpos($count_yft, '"count_yft":1')) { + $datatables2->query( + 'select yft_order_info.price from yft_order_info where date_format(yft_order_info.create_time,\'%Y-%m\') =date_format(date_sub(curdate(), interval 1 month),\'%Y-%m\') and yft_order_info.state= 1'); - //每周的第一天是周日,因此统计周日~周六的七天 - $text_json2=$datatables2->generate(); - $text_array2=json_decode($text_json2,true); - $codes2=$text_array2['data']; - foreach($codes2 as $code2){ - $income_count+=1; - $income_total+=$code2['price']; - } - } - $text_html.='
上月总收入笔数:'.$income_count.'
上月总收入金额:'.$income_total; + //每周的第一天是周日,因此统计周日~周六的七天 + $text_json2 = $datatables2->generate(); + $text_array2 = json_decode($text_json2, true); + $codes2 = $text_array2['data']; + foreach ($codes2 as $code2) { + $income_count += 1; + $income_total += $code2['price']; + } + } + $text_html .= '
上月总收入笔数:' . $income_count . '
上月总收入金额:' . $income_total; $adminUser = User::where("is_admin", "=", "1")->get(); foreach ($adminUser as $user) { - echo "Send offline mail to user: ".$user->id; - $subject = Config::get('appName').'-财务月报'; - $to = $user->email; - $title='财务月报'; - $text = $text_html; - try { - Mail::send($to, $subject, 'news/finance.tpl', [ - "user" => $user,"title"=>$title,"text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } - } - - if (Config::get("finance_public")=="true") { - $sts = new Analytics(); - Telegram::Send( - "新鲜出炉的财务月报~".PHP_EOL. - "上月总收入笔数:".$income_count.PHP_EOL. - "上月总收入金额:".$income_total.PHP_EOL. - "月初也在努力工作~" - ); - } - } + echo "Send offline mail to user: " . $user->id; + $subject = Config::get('appName') . '-财务月报'; + $to = $user->email; + $title = '财务月报'; + $text = $text_html; + try { + Mail::send($to, $subject, 'news/finance.tpl', [ + "user" => $user, "title" => $title, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + } + + if (Config::get("finance_public") == "true") { + $sts = new Analytics(); + Telegram::Send( + "新鲜出炉的财务月报~" . PHP_EOL . + "上月总收入笔数:" . $income_count . PHP_EOL . + "上月总收入金额:" . $income_total . PHP_EOL . + "月初也在努力工作~" + ); + } + } } diff --git a/app/Command/Job.php b/app/Command/Job.php index 341f215d..9d068f6c 100644 --- a/app/Command/Job.php +++ b/app/Command/Job.php @@ -49,31 +49,30 @@ class Job } } - public static function backup($full=false) + public static function backup($full = false) { - $to = Config::get('auto_backup_email'); - if($to==null){ - return false; - } + $to = Config::get('auto_backup_email'); + if ($to == null) { + return false; + } mkdir('/tmp/ssmodbackup/'); $db_address_array = explode(':', Config::get('db_host')); - if($full){ - system('mysqldump --user='.Config::get('db_username').' --password='.Config::get('db_password').' --host='.$db_address_array[0].' '.(isset($db_address_array[1])?'-P '.$db_address_array[1]:'').' '.Config::get('db_database').' > /tmp/ssmodbackup/mod.sql'); - } - else{ - system('mysqldump --user='.Config::get('db_username').' --password='.Config::get('db_password').' --host='.$db_address_array[0].' '.(isset($db_address_array[1])?'-P '.$db_address_array[1]:'').' '.Config::get('db_database').' announcement auto blockip bought code coupon disconnect_ip link login_ip payback radius_ban shop speedtest ss_invite_code ss_node ss_password_reset ticket unblockip user user_token email_verify detect_list relay paylist> /tmp/ssmodbackup/mod.sql', $ret); - system('mysqldump --opt --user='.Config::get('db_username').' --password='.Config::get('db_password').' --host='.$db_address_array[0].' '.(isset($db_address_array[1])?'-P '.$db_address_array[1]:'').' -d '.Config::get('db_database').' alive_ip ss_node_info ss_node_online_log user_traffic_log detect_log telegram_session >> /tmp/ssmodbackup/mod.sql', $ret); - if (Config::get('enable_radius')=='true') { - $db_address_array = explode(':', Config::get('radius_db_host')); - system('mysqldump --user='.Config::get('radius_db_user').' --password='.Config::get('radius_db_password').' --host='.$db_address_array[0].' '.(isset($db_address_array[1])?'-P '.$db_address_array[1]:'').''.Config::get('radius_db_database').'> /tmp/ssmodbackup/radius.sql', $ret); - } - } - - system("cp ".BASE_PATH."/config/.config.php /tmp/ssmodbackup/configbak.php", $ret); + if ($full) { + system('mysqldump --user=' . Config::get('db_username') . ' --password=' . Config::get('db_password') . ' --host=' . $db_address_array[0] . ' ' . (isset($db_address_array[1]) ? '-P ' . $db_address_array[1] : '') . ' ' . Config::get('db_database') . ' > /tmp/ssmodbackup/mod.sql'); + } else { + system('mysqldump --user=' . Config::get('db_username') . ' --password=' . Config::get('db_password') . ' --host=' . $db_address_array[0] . ' ' . (isset($db_address_array[1]) ? '-P ' . $db_address_array[1] : '') . ' ' . Config::get('db_database') . ' announcement auto blockip bought code coupon disconnect_ip link login_ip payback radius_ban shop speedtest ss_invite_code ss_node ss_password_reset ticket unblockip user user_token email_verify detect_list relay paylist> /tmp/ssmodbackup/mod.sql', $ret); + system('mysqldump --opt --user=' . Config::get('db_username') . ' --password=' . Config::get('db_password') . ' --host=' . $db_address_array[0] . ' ' . (isset($db_address_array[1]) ? '-P ' . $db_address_array[1] : '') . ' -d ' . Config::get('db_database') . ' alive_ip ss_node_info ss_node_online_log user_traffic_log detect_log telegram_session >> /tmp/ssmodbackup/mod.sql', $ret); + if (Config::get('enable_radius') == 'true') { + $db_address_array = explode(':', Config::get('radius_db_host')); + system('mysqldump --user=' . Config::get('radius_db_user') . ' --password=' . Config::get('radius_db_password') . ' --host=' . $db_address_array[0] . ' ' . (isset($db_address_array[1]) ? '-P ' . $db_address_array[1] : '') . '' . Config::get('radius_db_database') . '> /tmp/ssmodbackup/radius.sql', $ret); + } + } + + system("cp " . BASE_PATH . "/config/.config.php /tmp/ssmodbackup/configbak.php", $ret); echo $ret; - system("zip -r /tmp/ssmodbackup.zip /tmp/ssmodbackup/* -P ".Config::get('auto_backup_passwd'), $ret); - $subject = Config::get('appName')."-备份成功"; - $text = "您好,系统已经为您自动备份,请查看附件,用您设定的密码解压。" ; + system("zip -r /tmp/ssmodbackup.zip /tmp/ssmodbackup/* -P " . Config::get('auto_backup_passwd'), $ret); + $subject = Config::get('appName') . "-备份成功"; + $text = "您好,系统已经为您自动备份,请查看附件,用您设定的密码解压。"; try { Mail::send($to, $subject, 'news/backup.tpl', [ "text" => $text @@ -85,9 +84,9 @@ class Job system("rm -rf /tmp/ssmodbackup", $ret); system("rm /tmp/ssmodbackup.zip", $ret); - if(Config::get('backup_notify')=='true'){ - Telegram::Send("备份完毕了喵~今天又是安全祥和的一天呢。"); - } + if (Config::get('backup_notify') == 'true') { + Telegram::Send("备份完毕了喵~今天又是安全祥和的一天呢。"); + } } public static function UserGa() @@ -97,7 +96,7 @@ class Job $ga = new GA(); $secret = $ga->createSecret(); - $user->ga_token=$secret; + $user->ga_token = $secret; $user->save(); } echo "ok"; @@ -107,10 +106,10 @@ class Job { $nodes = Node::all(); foreach ($nodes as $node) { - $rule = preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$node->server); + $rule = preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $node->server); if (!$rule && (!$node->sort || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) { - $ip=gethostbyname($node->server); - $node->node_ip=$ip; + $ip = gethostbyname($node->server); + $node->node_ip = $ip; $node->save(); Radius::AddNas($node->node_ip, $node->server); @@ -122,65 +121,65 @@ class Job { $nodes = Node::all(); foreach ($nodes as $node) { - if ($node->sort == 0 || $node->sort == 10 || $node->sort == 11 ||$node->sort ==12 ||$node->sort==13) { - if (date("d")==$node->bandwidthlimit_resetday) { - $node->node_bandwidth=0; + if ($node->sort == 0 || $node->sort == 10 || $node->sort == 11 || $node->sort == 12 || $node->sort == 13) { + if (date("d") == $node->bandwidthlimit_resetday) { + $node->node_bandwidth = 0; $node->save(); } } } - NodeInfoLog::where("log_time", "<", time()-86400*3)->delete(); - NodeOnlineLog::where("log_time", "<", time()-86400*3)->delete(); - TrafficLog::where("log_time", "<", time()-86400*3)->delete(); - DetectLog::where("datetime", "<", time()-86400*3)->delete(); - Speedtest::where("datetime", "<", time()-86400*3)->delete(); - EmailVerify::where("expire_in", "<", time()-86400*3)->delete(); - system("rm ".BASE_PATH."/storage/*.png", $ret); + NodeInfoLog::where("log_time", "<", time() - 86400 * 3)->delete(); + NodeOnlineLog::where("log_time", "<", time() - 86400 * 3)->delete(); + TrafficLog::where("log_time", "<", time() - 86400 * 3)->delete(); + DetectLog::where("datetime", "<", time() - 86400 * 3)->delete(); + Speedtest::where("datetime", "<", time() - 86400 * 3)->delete(); + EmailVerify::where("expire_in", "<", time() - 86400 * 3)->delete(); + system("rm " . BASE_PATH . "/storage/*.png", $ret); Telegram::Send("姐姐姐姐,数据库被清理了,感觉身体被掏空了呢~"); //auto reset - $boughts=Bought::all(); + $boughts = Bought::all(); $boughted_users = array(); foreach ($boughts as $bought) { - $user=User::where("id", $bought->userid)->first(); + $user = User::where("id", $bought->userid)->first(); if ($user == null) { $bought->delete(); continue; } - $shop=Shop::where("id", $bought->shopid)->first(); + $shop = Shop::where("id", $bought->shopid)->first(); if ($shop == null) { $bought->delete(); continue; } - if($shop->reset() != 0 && $shop->reset_value() != 0 && $shop->reset_exp() != 0) { - $boughted_users[]=$bought->userid; - if(time() - $shop->reset_exp() * 86400 < $bought->datetime) { - if(intval((time() - $bought->datetime) / 86400) % $shop->reset() == 0 && intval((time() - $bought->datetime) / 86400) != 0) { - echo("流量重置-".$user->id."\n"); - $user->transfer_enable = Tools::toGB($shop->reset_value()); - $user->u = 0; - $user->d = 0; - $user->last_day_t = 0; - $user->save(); - - $subject = Config::get('appName')."-您的流量被重置了"; - $to = $user->email; - $text = "您好,根据您所订购的订单 ID:".$bought->id.",流量已经被重置为".$shop->reset_value().'GB' ; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } + if ($shop->reset() != 0 && $shop->reset_value() != 0 && $shop->reset_exp() != 0) { + $boughted_users[] = $bought->userid; + if (time() - $shop->reset_exp() * 86400 < $bought->datetime) { + if (intval((time() - $bought->datetime) / 86400) % $shop->reset() == 0 && intval((time() - $bought->datetime) / 86400) != 0) { + echo("流量重置-" . $user->id . "\n"); + $user->transfer_enable = Tools::toGB($shop->reset_value()); + $user->u = 0; + $user->d = 0; + $user->last_day_t = 0; + $user->save(); + + $subject = Config::get('appName') . "-您的流量被重置了"; + $to = $user->email; + $text = "您好,根据您所订购的订单 ID:" . $bought->id . ",流量已经被重置为" . $shop->reset_value() . 'GB'; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + } } - } } } @@ -188,24 +187,24 @@ class Job $users = User::all(); foreach ($users as $user) { - $user->last_day_t=($user->u+$user->d); + $user->last_day_t = ($user->u + $user->d); $user->save(); - if (in_array($user->id,$boughted_users)){ + if (in_array($user->id, $boughted_users)) { continue; } if (date("d") == $user->auto_reset_day) { $user->u = 0; $user->d = 0; $user->last_day_t = 0; - $user->transfer_enable = $user->auto_reset_bandwidth*1024*1024*1024; + $user->transfer_enable = $user->auto_reset_bandwidth * 1024 * 1024 * 1024; $user->save(); - $subject = Config::get('appName')."-您的流量被重置了"; + $subject = Config::get('appName') . "-您的流量被重置了"; $to = $user->email; - $text = "您好,根据管理员的设置,流量已经被重置为".$user->auto_reset_bandwidth.'GB' ; + $text = "您好,根据管理员的设置,流量已经被重置为" . $user->auto_reset_bandwidth . 'GB'; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -217,7 +216,6 @@ class Job } - #https://github.com/shuax/QQWryUpdate/blob/master/update.php $copywrite = file_get_contents("http://update.cz88.net/ip/copywrite.rar"); @@ -225,22 +223,22 @@ class Job $adminUser = User::where("is_admin", "=", "1")->get(); $newmd5 = md5($copywrite); - $oldmd5 = file_get_contents(BASE_PATH."/storage/qqwry.md5"); + $oldmd5 = file_get_contents(BASE_PATH . "/storage/qqwry.md5"); if ($newmd5 != $oldmd5) { - file_put_contents(BASE_PATH."/storage/qqwry.md5", $newmd5); + file_put_contents(BASE_PATH . "/storage/qqwry.md5", $newmd5); $qqwry = file_get_contents("http://update.cz88.net/ip/qqwry.rar"); if ($qqwry != "") { $key = unpack("V6", $copywrite)[6]; - for ($i=0; $i<0x200; $i++) { + for ($i = 0; $i < 0x200; $i++) { $key *= 0x805; - $key ++; + $key++; $key = $key & 0xFF; $qqwry[$i] = chr(ord($qqwry[$i]) ^ $key); } $qqwry = gzuncompress($qqwry); - rename(BASE_PATH."/storage/qqwry.dat", BASE_PATH."/storage/qqwry.dat.bak"); - $fp = fopen(BASE_PATH."/storage/qqwry.dat", "wb"); + rename(BASE_PATH . "/storage/qqwry.dat", BASE_PATH . "/storage/qqwry.dat.bak"); + $fp = fopen(BASE_PATH . "/storage/qqwry.dat", "wb"); if ($fp) { fwrite($fp, $qqwry); fclose($fp); @@ -249,21 +247,22 @@ class Job } $iplocation = new QQWry(); - $location=$iplocation->getlocation("8.8.8.8"); + $location = $iplocation->getlocation("8.8.8.8"); $Userlocation = $location['country']; - if (iconv('gbk', 'utf-8//IGNORE', $Userlocation)!="美国") { - unlink(BASE_PATH."/storage/qqwry.dat"); - rename(BASE_PATH."/storage/qqwry.dat.bak", BASE_PATH."/storage/qqwry.dat"); + if (iconv('gbk', 'utf-8//IGNORE', $Userlocation) != "美国") { + unlink(BASE_PATH . "/storage/qqwry.dat"); + rename(BASE_PATH . "/storage/qqwry.dat.bak", BASE_PATH . "/storage/qqwry.dat"); } Job::updatedownload(); - + } + // 定时任务开启的情况下,每天自动检测有没有最新版的后端,github源来自Miku - public static function updatedownload() - { - system('cd '.BASE_PATH."/public/ssr-download/ && git pull https://github.com/xcxnig/ssr-download.git"); - } + public static function updatedownload() + { + system('cd ' . BASE_PATH . "/public/ssr-download/ && git pull https://github.com/xcxnig/ssr-download.git"); + } public static function CheckJob() @@ -271,14 +270,14 @@ class Job //在线人数检测 $users = User::where('node_connector', '>', 0)->get(); - $full_alive_ips = Ip::where("datetime", ">=", time()-60)->orderBy("ip")->get(); + $full_alive_ips = Ip::where("datetime", ">=", time() - 60)->orderBy("ip")->get(); $alive_ipset = array(); foreach ($full_alive_ips as $full_alive_ip) { $full_alive_ip->ip = Tools::getRealIp($full_alive_ip->ip); $is_node = Node::where("node_ip", $full_alive_ip->ip)->first(); - if($is_node) { + if ($is_node) { continue; } @@ -290,14 +289,14 @@ class Job } foreach ($users as $user) { - $alive_ips = (isset($alive_ipset[$user->id])?$alive_ipset[$user->id]:new \ArrayObject()); + $alive_ips = (isset($alive_ipset[$user->id]) ? $alive_ipset[$user->id] : new \ArrayObject()); $ips = array(); $disconnected_ips = explode(",", $user->disconnect_ip); foreach ($alive_ips as $alive_ip) { if (!isset($ips[$alive_ip->ip]) && !in_array($alive_ip->ip, $disconnected_ips)) { - $ips[$alive_ip->ip]=1; + $ips[$alive_ip->ip] = 1; if ($user->node_connector < count($ips)) { //暂时封禁 $isDisconnect = Disconnect::where('id', '=', $alive_ip->ip)->where('userid', '=', $user->id)->first(); @@ -309,10 +308,10 @@ class Job $disconnect->datetime = time(); $disconnect->save(); - if ($user->disconnect_ip == null||$user->disconnect_ip == "") { + if ($user->disconnect_ip == null || $user->disconnect_ip == "") { $user->disconnect_ip = $alive_ip->ip; } else { - $user->disconnect_ip .= ",".$alive_ip->ip; + $user->disconnect_ip .= "," . $alive_ip->ip; } $user->save(); } @@ -322,7 +321,7 @@ class Job } //解封 - $disconnecteds = Disconnect::where("datetime", "<", time()-300)->get(); + $disconnecteds = Disconnect::where("datetime", "<", time() - 300)->get(); foreach ($disconnecteds as $disconnected) { $user = User::where('id', '=', $disconnected->userid)->first(); @@ -336,7 +335,7 @@ class Job $new_ips .= $ip; $first = 0; } else { - $new_ips .= ",".$ip; + $new_ips .= "," . $ip; } } } @@ -353,76 +352,76 @@ class Job } //自动续费 - $boughts=Bought::where("renew", "<", time())->where("renew", "<>", 0)->get(); + $boughts = Bought::where("renew", "<", time())->where("renew", "<>", 0)->get(); foreach ($boughts as $bought) { - $user=User::where("id", $bought->userid)->first(); + $user = User::where("id", $bought->userid)->first(); if ($user == null) { $bought->delete(); continue; } - $shop=Shop::where("id", $bought->shopid)->first(); - if ($shop == null) { + $shop = Shop::where("id", $bought->shopid)->first(); + if ($shop == null) { $bought->delete(); - $subject = Config::get('appName')."-续费失败"; - $to = $user->email; - $text = "您好,系统为您自动续费商品时,发现该商品已被下架,为能继续正常使用,建议您登录用户面板购买新的商品。" ; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } + $subject = Config::get('appName') . "-续费失败"; + $to = $user->email; + $text = "您好,系统为您自动续费商品时,发现该商品已被下架,为能继续正常使用,建议您登录用户面板购买新的商品。"; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } continue; } - if ($user->money >= $shop->price) { - $user->money=$user->money - $shop->price; + if ($user->money >= $shop->price) { + $user->money = $user->money - $shop->price; $user->save(); $shop->buy($user, 1); - $bought->renew=0; + $bought->renew = 0; $bought->save(); - $bought_new=new Bought(); - $bought_new->userid=$user->id; - $bought_new->shopid=$shop->id; - $bought_new->datetime=time(); - $bought_new->renew=time()+$shop->auto_renew*86400; - $bought_new->price=$shop->price; - $bought_new->coupon=""; + $bought_new = new Bought(); + $bought_new->userid = $user->id; + $bought_new->shopid = $shop->id; + $bought_new->datetime = time(); + $bought_new->renew = time() + $shop->auto_renew * 86400; + $bought_new->price = $shop->price; + $bought_new->coupon = ""; $bought_new->save(); - $subject = Config::get('appName')."-续费成功"; + $subject = Config::get('appName') . "-续费成功"; $to = $user->email; - $text = "您好,系统已经为您自动续费,商品名:".$shop->name.",金额:".$shop->price." 元。" ; + $text = "您好,系统已经为您自动续费,商品名:" . $shop->name . ",金额:" . $shop->price . " 元。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { echo $e->getMessage(); } - if (file_exists(BASE_PATH."/storage/".$bought->id.".renew")) { - unlink(BASE_PATH."/storage/".$bought->id.".renew"); + if (file_exists(BASE_PATH . "/storage/" . $bought->id . ".renew")) { + unlink(BASE_PATH . "/storage/" . $bought->id . ".renew"); } } else { - if (!file_exists(BASE_PATH."/storage/".$bought->id.".renew")) { - $subject = Config::get('appName')."-续费失败"; + if (!file_exists(BASE_PATH . "/storage/" . $bought->id . ".renew")) { + $subject = Config::get('appName') . "-续费失败"; $to = $user->email; - $text = "您好,系统为您自动续费商品名:".$shop->name.",金额:".$shop->price." 元 时,发现您余额不足,请及时充值。充值后请稍等系统便会自动为您续费。" ; + $text = "您好,系统为您自动续费商品名:" . $shop->name . ",金额:" . $shop->price . " 元 时,发现您余额不足,请及时充值。充值后请稍等系统便会自动为您续费。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { echo $e->getMessage(); } - $myfile = fopen(BASE_PATH."/storage/".$bought->id.".renew", "w+") or die("Unable to open file!"); + $myfile = fopen(BASE_PATH . "/storage/" . $bought->id . ".renew", "w+") or die("Unable to open file!"); $txt = "1"; fwrite($myfile, $txt); fclose($myfile); @@ -430,163 +429,160 @@ class Job } } - Ip::where("datetime", "<", time()-300)->delete(); - UnblockIp::where("datetime", "<", time()-300)->delete(); - BlockIp::where("datetime", "<", time()-86400)->delete(); - TelegramSession::where("datetime", "<", time()-900)->delete(); + Ip::where("datetime", "<", time() - 300)->delete(); + UnblockIp::where("datetime", "<", time() - 300)->delete(); + BlockIp::where("datetime", "<", time() - 86400)->delete(); + TelegramSession::where("datetime", "<", time() - 900)->delete(); $adminUser = User::where("is_admin", "=", "1")->get(); - - //节点掉线检测 - if (Config::get("enable_detect_offline")=="true") { + + //节点掉线检测 + if (Config::get("enable_detect_offline") == "true") { $nodes = Node::all(); foreach ($nodes as $node) { - if ($node->isNodeOnline() === false && !file_exists(BASE_PATH."/storage/".$node->id.".offline")) { + if ($node->isNodeOnline() === false && !file_exists(BASE_PATH . "/storage/" . $node->id . ".offline")) { foreach ($adminUser as $user) { - echo "Send offline mail to user: ".$user->id; - $subject = Config::get('appName')."-系统警告"; + echo "Send offline mail to user: " . $user->id; + $subject = Config::get('appName') . "-系统警告"; $to = $user->email; - $text = "管理员您好,系统发现节点 ".$node->name." 掉线了,请您及时处理。" ; + $text = "管理员您好,系统发现节点 " . $node->name . " 掉线了,请您及时处理。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { echo $e->getMessage(); } - if (Config::get('enable_cloudxns')=='true' && ($node->sort==0 || $node->sort==10 ||$node->sort==12||$node->sort==13)) { - $api=new Api(); + if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) { + $api = new Api(); $api->setApiKey(Config::get("cloudxns_apikey"));//修改成自己API KEY $api->setSecretKey(Config::get("cloudxns_apisecret"));//修改成自己的SECERET KEY $api->setProtocol(true); - $domain_json=json_decode($api->domain->domainList()); + $domain_json = json_decode($api->domain->domainList()); foreach ($domain_json->data as $domain) { - if (strpos($domain->domain, Config::get('cloudxns_domain'))!==false) { - $domain_id=$domain->id; + if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) { + $domain_id = $domain->id; } } - $record_json=json_decode($api->record->recordList($domain_id, 0, 0, 2000)); + $record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000)); foreach ($record_json->data as $record) { - if (($record->host.".".Config::get('cloudxns_domain'))==$node->server) { - $record_id=$record->record_id; + if (($record->host . "." . Config::get('cloudxns_domain')) == $node->server) { + $record_id = $record->record_id; - $Temp_node=Node::where('node_class', '<=', $node->node_class)->where( + $Temp_node = Node::where('node_class', '<=', $node->node_class)->where( function ($query) use ($node) { $query->where("node_group", "=", $node->node_group) ->orWhere("node_group", "=", 0); } )->whereRaw('UNIX_TIMESTAMP()-`node_heartbeat`<300')->first(); - if ($Temp_node!=null) { + if ($Temp_node != null) { $api->record->recordUpdate($domain_id, $record->host, $Temp_node->server, 'CNAME', 55, 60, 1, '', $record_id); } - $notice_text = "喵喵喵~ ".$node->name." 节点掉线了喵~域名解析被切换到了 ".$Temp_node->name." 上了喵~"; + $notice_text = "喵喵喵~ " . $node->name . " 节点掉线了喵~域名解析被切换到了 " . $Temp_node->name . " 上了喵~"; } } } else { - $notice_text = "喵喵喵~ ".$node->name." 节点掉线了喵~"; + $notice_text = "喵喵喵~ " . $node->name . " 节点掉线了喵~"; } } Telegram::Send($notice_text); - $myfile = fopen(BASE_PATH."/storage/".$node->id.".offline", "w+") or die("Unable to open file!"); + $myfile = fopen(BASE_PATH . "/storage/" . $node->id . ".offline", "w+") or die("Unable to open file!"); $txt = "1"; fwrite($myfile, $txt); fclose($myfile); - } + } elseif ($node->isNodeOnline() === true && file_exists(BASE_PATH . "/storage/" . $node->id . ".offline")) { + foreach ($adminUser as $user) { + echo "Send offline mail to user: " . $user->id; + $subject = Config::get('appName') . "-系统提示"; + $to = $user->email; + $text = "管理员您好,系统发现节点 " . $node->name . " 恢复上线了。"; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } - elseif ($node->isNodeOnline() === true && file_exists(BASE_PATH."/storage/".$node->id.".offline")) { - foreach ($adminUser as $user) { - echo "Send offline mail to user: ".$user->id; - $subject = Config::get('appName')."-系统提示"; - $to = $user->email; - $text = "管理员您好,系统发现节点 ".$node->name." 恢复上线了。" ; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } + if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) { + $api = new Api(); + $api->setApiKey(Config::get("cloudxns_apikey"));//修改成自己API KEY + $api->setSecretKey(Config::get("cloudxns_apisecret"));//修改成自己的SECERET KEY + $api->setProtocol(true); + + $domain_json = json_decode($api->domain->domainList()); - if (Config::get('enable_cloudxns')=='true'&& ($node->sort==0 || $node->sort==10||$node->sort==12||$node->sort==13)) { - $api=new Api(); - $api->setApiKey(Config::get("cloudxns_apikey"));//修改成自己API KEY - $api->setSecretKey(Config::get("cloudxns_apisecret"));//修改成自己的SECERET KEY - $api->setProtocol(true); - - $domain_json=json_decode($api->domain->domainList()); - - foreach ($domain_json->data as $domain) { - if (strpos($domain->domain, Config::get('cloudxns_domain'))!==false) { - $domain_id=$domain->id; + foreach ($domain_json->data as $domain) { + if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) { + $domain_id = $domain->id; + } } - } - $record_json=json_decode($api->record->recordList($domain_id, 0, 0, 2000)); + $record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000)); - foreach ($record_json->data as $record) { - if (($record->host.".".Config::get('cloudxns_domain'))==$node->server) { - $record_id=$record->record_id; + foreach ($record_json->data as $record) { + if (($record->host . "." . Config::get('cloudxns_domain')) == $node->server) { + $record_id = $record->record_id; - $api->record->recordUpdate($domain_id, $record->host, $node->getNodeIp(), 'A', 55, 600, 1, '', $record_id); + $api->record->recordUpdate($domain_id, $record->host, $node->getNodeIp(), 'A', 55, 600, 1, '', $record_id); + } } - } - - $notice_text = "喵喵喵~ ".$node->name." 节点恢复了喵~域名解析被切换回来了喵~"; + + $notice_text = "喵喵喵~ " . $node->name . " 节点恢复了喵~域名解析被切换回来了喵~"; } else { - $notice_text = "喵喵喵~ ".$node->name." 节点恢复了喵~"; + $notice_text = "喵喵喵~ " . $node->name . " 节点恢复了喵~"; } } Telegram::Send($notice_text); - unlink(BASE_PATH."/storage/".$node->id.".offline"); - } + unlink(BASE_PATH . "/storage/" . $node->id . ".offline"); + } } } - //登录地检测 - if (Config::get("login_warn")=="true") { + if (Config::get("login_warn") == "true") { $iplocation = new QQWry(); - $Logs = LoginIp::where("datetime", ">", time()-60)->get(); + $Logs = LoginIp::where("datetime", ">", time() - 60)->get(); foreach ($Logs as $log) { - $UserLogs=LoginIp::where("userid", "=", $log->userid)->orderBy("id", "desc")->take(2)->get(); - if ($UserLogs->count()==2) { + $UserLogs = LoginIp::where("userid", "=", $log->userid)->orderBy("id", "desc")->take(2)->get(); + if ($UserLogs->count() == 2) { $i = 0; $Userlocation = ""; foreach ($UserLogs as $userlog) { if ($i == 0) { - $location=$iplocation->getlocation($userlog->ip); - $ip=$userlog->ip; + $location = $iplocation->getlocation($userlog->ip); + $ip = $userlog->ip; $Userlocation = $location['country']; $i++; } else { - $location=$iplocation->getlocation($userlog->ip); - $nodes=Node::where("node_ip", "LIKE", $ip.'%')->first(); - $nodes2=Node::where("node_ip", "LIKE", $userlog->ip.'%')->first(); - if ($Userlocation!=$location['country']&&$nodes==null&&$nodes2==null) { - $user=User::where("id", "=", $userlog->userid)->first(); - echo "Send warn mail to user: ".$user->id."-".iconv('gbk', 'utf-8//IGNORE', $Userlocation)."-".iconv('gbk', 'utf-8//IGNORE', $location['country']); - $subject = Config::get('appName')."-系统警告"; + $location = $iplocation->getlocation($userlog->ip); + $nodes = Node::where("node_ip", "LIKE", $ip . '%')->first(); + $nodes2 = Node::where("node_ip", "LIKE", $userlog->ip . '%')->first(); + if ($Userlocation != $location['country'] && $nodes == null && $nodes2 == null) { + $user = User::where("id", "=", $userlog->userid)->first(); + echo "Send warn mail to user: " . $user->id . "-" . iconv('gbk', 'utf-8//IGNORE', $Userlocation) . "-" . iconv('gbk', 'utf-8//IGNORE', $location['country']); + $subject = Config::get('appName') . "-系统警告"; $to = $user->email; - $text = "您好,系统发现您的账号在 ".iconv('gbk', 'utf-8//IGNORE', $Userlocation)." 有异常登录,请您自己自行核实登录行为。有异常请及时修改密码。" ; + $text = "您好,系统发现您的账号在 " . iconv('gbk', 'utf-8//IGNORE', $Userlocation) . " 有异常登录,请您自己自行核实登录行为。有异常请及时修改密码。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -601,116 +597,113 @@ class Job $users = User::all(); foreach ($users as $user) { - if (($user->transfer_enable<=$user->u+$user->d||$user->enable==0||(strtotime($user->expire_in)expire_in)>644447105))&&RadiusBan::where("userid", $user->id)->first()==null) { - $rb=new RadiusBan(); - $rb->userid=$user->id; + if (($user->transfer_enable <= $user->u + $user->d || $user->enable == 0 || (strtotime($user->expire_in) < time() && strtotime($user->expire_in) > 644447105)) && RadiusBan::where("userid", $user->id)->first() == null) { + $rb = new RadiusBan(); + $rb->userid = $user->id; $rb->save(); Radius::Delete($user->email); } - if (strtotime($user->expire_in) < time()&&!file_exists(BASE_PATH."/storage/".$user->id.".expire_in")) { + if (strtotime($user->expire_in) < time() && !file_exists(BASE_PATH . "/storage/" . $user->id . ".expire_in")) { $user->transfer_enable = 0; $user->u = 0; $user->d = 0; $user->last_day_t = 0; - - $subject = Config::get('appName')."-您的用户账户已经过期了"; + + $subject = Config::get('appName') . "-您的用户账户已经过期了"; $to = $user->email; $text = "您好,系统发现您的账号已经过期了。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { echo $e->getMessage(); } - $myfile = fopen(BASE_PATH."/storage/".$user->id.".expire_in", "w+") or die("Unable to open file!"); - $txt = "1"; + $myfile = fopen(BASE_PATH . "/storage/" . $user->id . ".expire_in", "w+") or die("Unable to open file!"); + $txt = "1"; fwrite($myfile, $txt); fclose($myfile); + } elseif (strtotime($user->expire_in) > time() && file_exists(BASE_PATH . "/storage/" . $user->id . ".expire_in")) { + unlink(BASE_PATH . "/storage/" . $user->id . ".expire_in"); } - elseif (strtotime($user->expire_in) > time()&&file_exists(BASE_PATH."/storage/".$user->id.".expire_in")) { - unlink(BASE_PATH."/storage/".$user->id.".expire_in"); - } - //余量不足检测 - if(!file_exists(BASE_PATH."/storage/traffic_notified/")){ - mkdir(BASE_PATH."/storage/traffic_notified/"); - } - if (Config::get('notify_limit_mode') !='false'){ + //余量不足检测 + if (!file_exists(BASE_PATH . "/storage/traffic_notified/")) { + mkdir(BASE_PATH . "/storage/traffic_notified/"); + } + if (Config::get('notify_limit_mode') != 'false') { $user_traffic_left = $user->transfer_enable - $user->u - $user->d; - $under_limit='false'; - - if($user->transfer_enable != 0){ - if (Config::get('notify_limit_mode') == 'per'&& - $user_traffic_left / $user->transfer_enable * 100 < Config::get('notify_limit_value')){ - $under_limit='true'; - $unit_text='%'; - } - } - else if(Config::get('notify_limit_mode')=='mb'&& - Tools::flowToMB($user_traffic_left) < Config::get('notify_limit_value')){ - $under_limit='true'; - $unit_text='MB'; - } - - if($under_limit=='true' && !file_exists(BASE_PATH."/storage/traffic_notified/".$user->id.".userid")){ - $subject = Config::get('appName')." - 您的剩余流量过低"; + $under_limit = 'false'; + + if ($user->transfer_enable != 0) { + if (Config::get('notify_limit_mode') == 'per' && + $user_traffic_left / $user->transfer_enable * 100 < Config::get('notify_limit_value')) { + $under_limit = 'true'; + $unit_text = '%'; + } + } else if (Config::get('notify_limit_mode') == 'mb' && + Tools::flowToMB($user_traffic_left) < Config::get('notify_limit_value')) { + $under_limit = 'true'; + $unit_text = 'MB'; + } + + if ($under_limit == 'true' && !file_exists(BASE_PATH . "/storage/traffic_notified/" . $user->id . ".userid")) { + $subject = Config::get('appName') . " - 您的剩余流量过低"; $to = $user->email; - $text = '您好,系统发现您剩余流量已经低于 '.Config::get('notify_limit_value').$unit_text.' 。' ; + $text = '您好,系统发现您剩余流量已经低于 ' . Config::get('notify_limit_value') . $unit_text . ' 。'; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); - $myfile = fopen(BASE_PATH."/storage/traffic_notified/".$user->id.".userid", "w+") or die("Unable to open file!"); - $txt = "1"; - fwrite($myfile, $txt); - fclose($myfile); + $myfile = fopen(BASE_PATH . "/storage/traffic_notified/" . $user->id . ".userid", "w+") or die("Unable to open file!"); + $txt = "1"; + fwrite($myfile, $txt); + fclose($myfile); } catch (\Exception $e) { echo $e->getMessage(); } + } else if ($under_limit == 'false') { + if (file_exists(BASE_PATH . "/storage/traffic_notified/" . $user->id . ".userid")) { + unlink(BASE_PATH . "/storage/traffic_notified/" . $user->id . ".userid"); + } } - else if($under_limit=='false'){ - if(file_exists(BASE_PATH."/storage/traffic_notified/".$user->id.".userid")){ - unlink(BASE_PATH."/storage/traffic_notified/".$user->id.".userid"); - } - } } - if (Config::get('account_expire_delete_days')>=0&& - strtotime($user->expire_in)+Config::get('account_expire_delete_days')*86400= 0 && + strtotime($user->expire_in) + Config::get('account_expire_delete_days') * 86400 < time() + ) { + $subject = Config::get('appName') . "-您的用户账户已经被删除了"; $to = $user->email; - $text = "您好,系统发现您的账户已经过期 ".Config::get('account_expire_delete_days')." 天了,帐号已经被删除。" ; + $text = "您好,系统发现您的账户已经过期 " . Config::get('account_expire_delete_days') . " 天了,帐号已经被删除。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { echo $e->getMessage(); } - - $user->kill_user(); + + $user->kill_user(); continue; } - - if (Config::get('auto_clean_uncheck_days')>0 && - max($user->last_check_in_time, strtotime($user->reg_date)) + (Config::get('auto_clean_uncheck_days')*86400) < time() && - $user->class == 0 && - $user->money <= Config::get('auto_clean_min_money') - ) { - $subject = Config::get('appName')."-您的用户账户已经被删除了"; + + if (Config::get('auto_clean_uncheck_days') > 0 && + max($user->last_check_in_time, strtotime($user->reg_date)) + (Config::get('auto_clean_uncheck_days') * 86400) < time() && + $user->class == 0 && + $user->money <= Config::get('auto_clean_min_money') + ) { + $subject = Config::get('appName') . "-您的用户账户已经被删除了"; $to = $user->email; - $text = "您好,系统发现您的账号已经 ".Config::get('auto_clean_uncheck_days')." 天没签到了,帐号已经被删除。" ; + $text = "您好,系统发现您的账号已经 " . Config::get('auto_clean_uncheck_days') . " 天没签到了,帐号已经被删除。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -720,17 +713,17 @@ class Job continue; } - if (Config::get('auto_clean_unused_days')>0 && - max($user->t, strtotime($user->reg_date)) + (Config::get('auto_clean_unused_days')*86400) < time() && - $user->class == 0 && - $user->money <= Config::get('auto_clean_min_money') - ) { - $subject = Config::get('appName')."-您的用户账户已经被删除了"; + if (Config::get('auto_clean_unused_days') > 0 && + max($user->t, strtotime($user->reg_date)) + (Config::get('auto_clean_unused_days') * 86400) < time() && + $user->class == 0 && + $user->money <= Config::get('auto_clean_min_money') + ) { + $subject = Config::get('appName') . "-您的用户账户已经被删除了"; $to = $user->email; - $text = "您好,系统发现您的账号已经 ".Config::get('auto_clean_unused_days')." 天没使用了,帐号已经被删除。" ; + $text = "您好,系统发现您的账号已经 " . Config::get('auto_clean_unused_days') . " 天没使用了,帐号已经被删除。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -740,31 +733,31 @@ class Job continue; } - if ($user->class!=0 && - strtotime($user->class_expire)class_expire) > 1420041600 - ){ - $text = '您好,系统发现您的账号等级已经过期了。'; - $reset_traffic=Config::get('class_expire_reset_traffic'); - if($reset_traffic>=0){ - $user->transfer_enable =Tools::toGB($reset_traffic); - $user->u = 0; - $user->d = 0; - $user->last_day_t = 0; - $text.='流量已经被重置为'.$reset_traffic.'GB'; - } - $subject = Config::get('appName')."-您的账户等级已经过期了"; - $to = $user->email; + if ($user->class != 0 && + strtotime($user->class_expire) < time() && + strtotime($user->class_expire) > 1420041600 + ) { + $text = '您好,系统发现您的账号等级已经过期了。'; + $reset_traffic = Config::get('class_expire_reset_traffic'); + if ($reset_traffic >= 0) { + $user->transfer_enable = Tools::toGB($reset_traffic); + $user->u = 0; + $user->d = 0; + $user->last_day_t = 0; + $text .= '流量已经被重置为' . $reset_traffic . 'GB'; + } + $subject = Config::get('appName') . "-您的账户等级已经过期了"; + $to = $user->email; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { echo $e->getMessage(); } - $user->class=0; + $user->class = 0; } $user->save(); @@ -772,161 +765,159 @@ class Job $rbusers = RadiusBan::all(); foreach ($rbusers as $sinuser) { - $user=User::find($sinuser->userid); + $user = User::find($sinuser->userid); if ($user == null) { $sinuser->delete(); continue; } - if ($user->enable==1&&(strtotime($user->expire_in)>time()||strtotime($user->expire_in)<644447105)&&$user->transfer_enable>$user->u+$user->d) { + if ($user->enable == 1 && (strtotime($user->expire_in) > time() || strtotime($user->expire_in) < 644447105) && $user->transfer_enable > $user->u + $user->d) { $sinuser->delete(); Radius::Add($user, $user->passwd); } } } - public static function detectGFW() - { - //节点被墙检测 - $last_time=file_get_contents(BASE_PATH."/storage/last_detect_gfw_time"); - for ($count=1;$count<=12;$count++){ - if(time()-$last_time>=Config::get("detect_gfw_interval")){ - $file_interval=fopen(BASE_PATH."/storage/last_detect_gfw_time","w"); - fwrite($file_interval,time()); - fclose($file_interval); - $nodes=Node::all(); - $adminUser = User::where("is_admin", "=", "1")->get(); - foreach ($nodes as $node){ - if($node->node_ip==""|| - $node->node_ip==null|| - file_exists(BASE_PATH."/storage/".$node->id."offline")==true){ - continue; - } - $api_url=Config::get("detect_gfw_url"); - $api_url=str_replace('{ip}',$node->node_ip,$api_url); - $api_url=str_replace('{port}',Config::get('detect_gfw_port'),$api_url); - //因为考虑到有v2ray之类的节点,所以不得不使用ip作为参数 - $result_tcping=false; - $detect_time=Config::get("detect_gfw_count"); - for ($i=1;$i<=$detect_time;$i++){ - $json_tcping = json_decode(file_get_contents($api_url), true); - if(eval('return '.Config::get('detect_gfw_judge').';')){ - $result_tcping=true; - break; - } - } - if($result_tcping==false){ - //被墙了 - echo($node->id.":false".PHP_EOL); - //判断有没有发送过邮件 - if(file_exists(BASE_PATH."/storage/".$node->id.".gfw")){ - continue; - } - foreach ($adminUser as $user) { - echo "Send gfw mail to user: ".$user->id."-"; - $subject = Config::get('appName')."-系统警告"; - $to = $user->email; - $text = "管理员您好,系统发现节点 ".$node->name." 被墙了,请您及时处理。" ; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text - ], [ - ]); - } - catch (\Exception $e) { - echo $e->getMessage(); - } - if (Config::get('enable_cloudxns')=='true' && ($node->sort==0 || $node->sort==10 ||$node->sort==12||$node->sort==13)) { - $api=new Api(); - $api->setApiKey(Config::get("cloudxns_apikey")); - //修改成自己API KEY - $api->setSecretKey(Config::get("cloudxns_apisecret")); - //修改成自己的SECERET KEY - $api->setProtocol(true); - $domain_json=json_decode($api->domain->domainList()); - foreach ($domain_json->data as $domain) { - if (strpos($domain->domain, Config::get('cloudxns_domain'))!==false) { - $domain_id=$domain->id; - } - } - $record_json=json_decode($api->record->recordList($domain_id, 0, 0, 2000)); - foreach ($record_json->data as $record) { - if (($record->host.".".Config::get('cloudxns_domain'))==$node->server) { - $record_id=$record->record_id; - $Temp_node=Node::where('node_class', '<=', $node->node_class)->where( - function ($query) use ($node) { - $query->where("node_group", "=", $node->node_group) - ->orWhere("node_group", "=", 0); - })->whereRaw('UNIX_TIMESTAMP()-`node_heartbeat`<300')->first(); - if ($Temp_node!=null) { - $api->record->recordUpdate($domain_id, $record->host, $Temp_node->server, 'CNAME', 55, 60, 1, '', $record_id); - } - $notice_text = "喵喵喵~ ".$node->name." 节点被墙了喵~域名解析被切换到了 ".$Temp_node->name." 上了喵~"; - } - } - } else { - $notice_text = "喵喵喵~ ".$node->name." 节点被墙了喵~"; - } - } - Telegram::Send($notice_text); - $file_node = fopen(BASE_PATH."/storage/".$node->id.".gfw", "w+"); - fclose($file_node); - } else{ - //没有被墙 - echo($node->id.":true".PHP_EOL); - if(file_exists(BASE_PATH."/storage/".$node->id.".gfw")==false){ - continue; - } - foreach ($adminUser as $user) { - echo "Send gfw mail to user: ".$user->id."-"; - $subject = Config::get('appName')."-系统提示"; - $to = $user->email; - $text = "管理员您好,系统发现节点 ".$node->name." 溜出墙了。" ; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text - ], [ - ]); - } - catch (\Exception $e) { - echo $e->getMessage(); - } - if (Config::get('enable_cloudxns')=='true'&& ($node->sort==0 || $node->sort==10||$node->sort==12||$node->sort==13)) { - $api=new Api(); - $api->setApiKey(Config::get("cloudxns_apikey")); - //修改成自己API KEY - $api->setSecretKey(Config::get("cloudxns_apisecret")); - //修改成自己的SECERET KEY - $api->setProtocol(true); - $domain_json=json_decode($api->domain->domainList()); - foreach ($domain_json->data as $domain) { - if (strpos($domain->domain, Config::get('cloudxns_domain'))!==false) { - $domain_id=$domain->id; - } - } - $record_json=json_decode($api->record->recordList($domain_id, 0, 0, 2000)); - foreach ($record_json->data as $record) { - if (($record->host.".".Config::get('cloudxns_domain'))==$node->server) { - $record_id=$record->record_id; - $api->record->recordUpdate($domain_id, $record->host, $node->getNodeIp(), 'A', 55, 600, 1, '', $record_id); - } - } - $notice_text = "喵喵喵~ ".$node->name." 节点恢复了喵~域名解析被切换回来了喵~"; - } else { - $notice_text = "喵喵喵~ ".$node->name." 节点恢复了喵~"; - } - } - Telegram::Send($notice_text); - unlink(BASE_PATH."/storage/".$node->id.".gfw"); - } - } - break; - } else{ - echo($node->id."interval skip".PHP_EOL); - sleep(3); - } - } - } + public static function detectGFW() + { + //节点被墙检测 + $last_time = file_get_contents(BASE_PATH . "/storage/last_detect_gfw_time"); + for ($count = 1; $count <= 12; $count++) { + if (time() - $last_time >= Config::get("detect_gfw_interval")) { + $file_interval = fopen(BASE_PATH . "/storage/last_detect_gfw_time", "w"); + fwrite($file_interval, time()); + fclose($file_interval); + $nodes = Node::all(); + $adminUser = User::where("is_admin", "=", "1")->get(); + foreach ($nodes as $node) { + if ($node->node_ip == "" || + $node->node_ip == null || + file_exists(BASE_PATH . "/storage/" . $node->id . "offline") == true) { + continue; + } + $api_url = Config::get("detect_gfw_url"); + $api_url = str_replace('{ip}', $node->node_ip, $api_url); + $api_url = str_replace('{port}', Config::get('detect_gfw_port'), $api_url); + //因为考虑到有v2ray之类的节点,所以不得不使用ip作为参数 + $result_tcping = false; + $detect_time = Config::get("detect_gfw_count"); + for ($i = 1; $i <= $detect_time; $i++) { + $json_tcping = json_decode(file_get_contents($api_url), true); + if (eval('return ' . Config::get('detect_gfw_judge') . ';')) { + $result_tcping = true; + break; + } + } + if ($result_tcping == false) { + //被墙了 + echo($node->id . ":false" . PHP_EOL); + //判断有没有发送过邮件 + if (file_exists(BASE_PATH . "/storage/" . $node->id . ".gfw")) { + continue; + } + foreach ($adminUser as $user) { + echo "Send gfw mail to user: " . $user->id . "-"; + $subject = Config::get('appName') . "-系统警告"; + $to = $user->email; + $text = "管理员您好,系统发现节点 " . $node->name . " 被墙了,请您及时处理。"; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) { + $api = new Api(); + $api->setApiKey(Config::get("cloudxns_apikey")); + //修改成自己API KEY + $api->setSecretKey(Config::get("cloudxns_apisecret")); + //修改成自己的SECERET KEY + $api->setProtocol(true); + $domain_json = json_decode($api->domain->domainList()); + foreach ($domain_json->data as $domain) { + if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) { + $domain_id = $domain->id; + } + } + $record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000)); + foreach ($record_json->data as $record) { + if (($record->host . "." . Config::get('cloudxns_domain')) == $node->server) { + $record_id = $record->record_id; + $Temp_node = Node::where('node_class', '<=', $node->node_class)->where( + function ($query) use ($node) { + $query->where("node_group", "=", $node->node_group) + ->orWhere("node_group", "=", 0); + })->whereRaw('UNIX_TIMESTAMP()-`node_heartbeat`<300')->first(); + if ($Temp_node != null) { + $api->record->recordUpdate($domain_id, $record->host, $Temp_node->server, 'CNAME', 55, 60, 1, '', $record_id); + } + $notice_text = "喵喵喵~ " . $node->name . " 节点被墙了喵~域名解析被切换到了 " . $Temp_node->name . " 上了喵~"; + } + } + } else { + $notice_text = "喵喵喵~ " . $node->name . " 节点被墙了喵~"; + } + } + Telegram::Send($notice_text); + $file_node = fopen(BASE_PATH . "/storage/" . $node->id . ".gfw", "w+"); + fclose($file_node); + } else { + //没有被墙 + echo($node->id . ":true" . PHP_EOL); + if (file_exists(BASE_PATH . "/storage/" . $node->id . ".gfw") == false) { + continue; + } + foreach ($adminUser as $user) { + echo "Send gfw mail to user: " . $user->id . "-"; + $subject = Config::get('appName') . "-系统提示"; + $to = $user->email; + $text = "管理员您好,系统发现节点 " . $node->name . " 溜出墙了。"; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) { + $api = new Api(); + $api->setApiKey(Config::get("cloudxns_apikey")); + //修改成自己API KEY + $api->setSecretKey(Config::get("cloudxns_apisecret")); + //修改成自己的SECERET KEY + $api->setProtocol(true); + $domain_json = json_decode($api->domain->domainList()); + foreach ($domain_json->data as $domain) { + if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) { + $domain_id = $domain->id; + } + } + $record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000)); + foreach ($record_json->data as $record) { + if (($record->host . "." . Config::get('cloudxns_domain')) == $node->server) { + $record_id = $record->record_id; + $api->record->recordUpdate($domain_id, $record->host, $node->getNodeIp(), 'A', 55, 600, 1, '', $record_id); + } + } + $notice_text = "喵喵喵~ " . $node->name . " 节点恢复了喵~域名解析被切换回来了喵~"; + } else { + $notice_text = "喵喵喵~ " . $node->name . " 节点恢复了喵~"; + } + } + Telegram::Send($notice_text); + unlink(BASE_PATH . "/storage/" . $node->id . ".gfw"); + } + } + break; + } else { + echo($node->id . "interval skip" . PHP_EOL); + sleep(3); + } + } + } } diff --git a/app/Command/SyncRadius.php b/app/Command/SyncRadius.php index 2798bb61..1a745b49 100644 --- a/app/Command/SyncRadius.php +++ b/app/Command/SyncRadius.php @@ -1,9 +1,6 @@ email; - $email=Radius::GetUserName($email); - $tempuserbox[$email]=$user->id; + $email = $user->email; + $email = Radius::GetUserName($email); + $tempuserbox[$email] = $user->id; } - + /*$tempnodebox=array(); $nodes = Node::all(); foreach($nodes as $node){ @@ -42,11 +39,10 @@ class SyncRadius $tempnodebox[$ip]=$node->id; } }*/ - - - - $logs = RadiusRadPostauth::where('authdate', '<', date("Y-m-d H:i:s"))->where('authdate', '>', date("Y-m-d H:i:s", time()-60))->get(); - + + + $logs = RadiusRadPostauth::where('authdate', '<', date("Y-m-d H:i:s"))->where('authdate', '>', date("Y-m-d H:i:s", time() - 60))->get(); + foreach ($logs as $log) { if (isset($tempuserbox[$log->username])) { $traffic = new TrafficLog(); @@ -58,16 +54,16 @@ class SyncRadius $traffic->traffic = Tools::flowAutoShow(10000); $traffic->log_time = time(); $traffic->save(); - - $user=User::find($tempuserbox[$log->username]); + + $user = User::find($tempuserbox[$log->username]); $user->t = time(); $user->u = $user->u + 0; $user->d = $user->d + 10000; $user->save(); } } - - + + /*$stmt = $db->query("SELECT * FROM `radacct` WHERE `acctstoptime`<'".date("Y-m-d H:i:s")."' AND `acctstoptime`>'".date("Y-m-d H:i:s",time()-60)."'"); $result = $stmt->fetchAll(); @@ -89,22 +85,22 @@ class SyncRadius $user->save(); } */ } - - + + public static function syncvpn() { - if (Config::get('radius_db_host')=="") { + if (Config::get('radius_db_host') == "") { return; } - - $tempuserbox=array(); + + $tempuserbox = array(); $users = User::all(); foreach ($users as $user) { - $email=$user->email; - $email=Radius::GetUserName($email); - $tempuserbox[$email]=$user->id; + $email = $user->email; + $email = Radius::GetUserName($email); + $tempuserbox[$email] = $user->id; } - + /*$tempnodebox=array(); $nodes = Node::all(); foreach($nodes as $node){ @@ -114,7 +110,7 @@ class SyncRadius $tempnodebox[$ip]=$node->id; } }*/ - + /*$stmt = $db->query("SELECT * FROM `radpostauth` WHERE `authdate`<'".date("Y-m-d H:i:s")."' AND`authdate`>'".date("Y-m-d H:i:s",time()-60)."'"); $result = $stmt->fetchAll(); @@ -139,10 +135,10 @@ class SyncRadius } } */ - - - $logs = RadiusRadAcct::where('acctstoptime', '<', date("Y-m-d H:i:s"))->where('acctstoptime', '>', date("Y-m-d H:i:s", time()-60))->get(); - + + + $logs = RadiusRadAcct::where('acctstoptime', '<', date("Y-m-d H:i:s"))->where('acctstoptime', '>', date("Y-m-d H:i:s", time() - 60))->get(); + foreach ($logs as $log) { $traffic = new TrafficLog(); $traffic->user_id = $tempuserbox[$log->username]; @@ -153,28 +149,28 @@ class SyncRadius $traffic->traffic = Tools::flowAutoShow(($log->acctinputoctets + $log->acctoutputoctets)); $traffic->log_time = time(); $traffic->save(); - - $user=User::find($tempuserbox[$log->username]); + + $user = User::find($tempuserbox[$log->username]); $user->t = time(); $user->u = $user->u + $log->acctinputoctets; $user->d = $user->d + $log->acctoutputoctets; $user->save(); } } - + public static function syncusers() { $users = User::all(); foreach ($users as $user) { Radius::Add($user, $user->passwd); - echo "Send sync mail to user: ".$user->id; - $subject = Config::get('appName')."-密码更新通知"; + echo "Send sync mail to user: " . $user->id; + $subject = Config::get('appName') . "-密码更新通知"; $to = $user->email; - $text = "您好,为了保证密码系统的统一,刚刚系统已经将您 vpn 等连接方式的用户名已经重置为:".Radius::GetUserName($user->email).",密码自动重置为您 ss 的密码:". $user->passwd." 了,以后您修改 ss 密码就会自动修改 vpn 等连接方式的密码了,感谢您的支持。 " ; + $text = "您好,为了保证密码系统的统一,刚刚系统已经将您 vpn 等连接方式的用户名已经重置为:" . Radius::GetUserName($user->email) . ",密码自动重置为您 ss 的密码:" . $user->passwd . " 了,以后您修改 ss 密码就会自动修改 vpn 等连接方式的密码了,感谢您的支持。 "; try { Mail::send($to, $subject, 'password/vpn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -182,29 +178,29 @@ class SyncRadius } } } - + public static function syncnas() { - if (Config::get('radius_db_host')!="") { - $md5txt=""; - + if (Config::get('radius_db_host') != "") { + $md5txt = ""; + $nases = RadiusNas::all(); - + foreach ($nases as $nas) { //if($row["pass"]!="") { - $md5txt=$md5txt.$nas->id.$nas->nasname.$nas->shortname.$nas->secret.$nas->description; + $md5txt = $md5txt . $nas->id . $nas->nasname . $nas->shortname . $nas->secret . $nas->description; } } - - $md5=MD5($md5txt); - - - $oldmd5=file_get_contents(BASE_PATH."/storage/nas.md5"); - - if ($oldmd5!=$md5) { + + $md5 = MD5($md5txt); + + + $oldmd5 = file_get_contents(BASE_PATH . "/storage/nas.md5"); + + if ($oldmd5 != $md5) { //Restart radius - $myfile = fopen(BASE_PATH."/storage/nas.md5", "w+") or die("Unable to open file!"); + $myfile = fopen(BASE_PATH . "/storage/nas.md5", "w+") or die("Unable to open file!"); echo("Restarting..."); system("/bin/bash /sbin/service radiusd restart", $retval); echo($retval); @@ -213,13 +209,13 @@ class SyncRadius fclose($myfile); } } - + $Nodes = Node::where('sort', 0)->where('node_ip', "<>", "")->where('node_ip', "<>", 'NULL')->get(); foreach ($Nodes as $Node) { if (file_exists("/usr/local/psionic/portsentry/portsentry.ignore")) { - $content=file_get_contents("/usr/local/psionic/portsentry/portsentry.ignore"); - if (strpos($content, $Node->node_ip)===false) { - file_put_contents("/usr/local/psionic/portsentry/portsentry.ignore", "\n".$Node->node_ip."/32", FILE_APPEND); + $content = file_get_contents("/usr/local/psionic/portsentry/portsentry.ignore"); + if (strpos($content, $Node->node_ip) === false) { + file_put_contents("/usr/local/psionic/portsentry/portsentry.ignore", "\n" . $Node->node_ip . "/32", FILE_APPEND); } } } diff --git a/app/Command/Update.php b/app/Command/Update.php index 5397fab5..33dc87f8 100644 --- a/app/Command/Update.php +++ b/app/Command/Update.php @@ -9,136 +9,134 @@ use App\Utils\DatatablesHelper; class Update { - public static function update($xcat) + public static function update($xcat) { global $System_Config; - $copy_result=copy(BASE_PATH."/config/.config.php",BASE_PATH."/config/.config.php.bak"); - if($copy_result==true){ - echo('备份成功'.PHP_EOL); - } - else{ - echo('备份失败,迁移终止'.PHP_EOL); - return false; - } - - echo(PHP_EOL); - - echo('开始升级ssrdownload...'.PHP_EOL); - Job::updatedownload(); - echo('升级ssrdownload结束'.PHP_EOL); - - echo('开始升级QQWry...'.PHP_EOL); - $xcat->initQQWry(); - echo('升级QQWry结束'.PHP_EOL); - - echo(PHP_EOL); - - $config_old=file_get_contents(BASE_PATH."/config/.config.php"); - $config_new=file_get_contents(BASE_PATH."/config/.config.php.example"); - - //执行版本升级 - $version_old=0; - if(isset($System_Config['version'])){ - $version_old=$System_Config['version']; - } - Update::old_to_new($version_old); - - //将旧config迁移到新config上 - $migrated=array(); - foreach($System_Config as $key => $value_reserve){ - if($key=='config_migrate_notice'||$key=='version'){ - continue; - } - - $regex='/System_Config\[\''.$key.'\'\].*?;/s'; - $matches_new=array(); - preg_match($regex,$config_new,$matches_new); - if(isset($matches_new[0])==false){ - echo('未找到配置项:'.$key.' 未能在新config文件中找到,可能已被更名或废弃'.PHP_EOL); - continue; - } - - $matches_old=array(); - preg_match($regex,$config_old,$matches_old); - - $config_new=str_replace($matches_new[0],$matches_old[0],$config_new); - array_push($migrated,'System_Config[\''.$key.'\']'); - } - echo(PHP_EOL); - - //检查新增了哪些config - $regex_new='/System_Config\[\'.*?\'\]/s'; - $matches_new_all=array(); - preg_match_all($regex_new,$config_new,$matches_new_all); - $differences=array_diff($matches_new_all[0],$migrated); - foreach($differences as $difference){ - if($difference=='System_Config[\'config_migrate_notice\']'|| - $difference=='System_Config[\'version\']'){ - continue; - } - //匹配注释 - $regex_comment='/'.$difference.'.*?;.*?(?=\n)/s'; - $regex_comment=str_replace('[','\[',$regex_comment); - $regex_comment=str_replace(']','\]',$regex_comment); - $matches_comment=array(); - preg_match($regex_comment,$config_new,$matches_comment); - $comment=""; - if(isset($matches_comment[0])){ - $comment=$matches_comment[0]; - $comment=substr( - $comment,strpos( - $comment,'//',strpos($comment,';') //查找';'之后的第一个'//',然后substr其后面的comment - )+2 - ); - } - //裁去首尾 - $difference=substr($difference,15); - $difference=substr($difference, 0, -2); - - echo('新增配置项:'.$difference.':'.$comment.PHP_EOL); - } - echo('新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行'.PHP_EOL); - - //输出notice - $regex_notice='/System_Config\[\'config_migrate_notice\'\].*?(?=\';)/s'; - $matches_notice=array(); - preg_match($regex_notice,$config_new,$matches_notice); - $notice_new=$matches_notice[0]; - $notice_new=substr( - $notice_new,strpos( - $notice_new,'\'',strpos($notice_new,'=') //查找'='之后的第一个'\'',然后substr其后面的notice - )+1 - ); - echo('以下是迁移附注:'); - if(isset($System_Config['config_migrate_notice'])){ - if($System_Config['config_migrate_notice']!=$notice_new){ - echo($notice_new); - } - } - else{ - echo($notice_new); - } - echo(PHP_EOL); - - file_put_contents(BASE_PATH."/config/.config.php",$config_new); - echo(PHP_EOL.'迁移完成'.PHP_EOL); - - echo(PHP_EOL); - - echo('开始升级composer依赖...'.PHP_EOL); - system('php '.BASE_PATH.'/composer.phar selfupdate'); - system('php '.BASE_PATH.'/composer.phar install -d '.BASE_PATH); - echo('升级composer依赖结束,请自行根据上方输出确认是否升级成功'.PHP_EOL); - system('rm -rf '.BASE_PATH.'/storage/framework/smarty/compile/*'); - system('chown -R www:www '.BASE_PATH.'/storage'); + $copy_result = copy(BASE_PATH . "/config/.config.php", BASE_PATH . "/config/.config.php.bak"); + if ($copy_result == true) { + echo('备份成功' . PHP_EOL); + } else { + echo('备份失败,迁移终止' . PHP_EOL); + return false; + } + + echo(PHP_EOL); + + echo('开始升级ssrdownload...' . PHP_EOL); + Job::updatedownload(); + echo('升级ssrdownload结束' . PHP_EOL); + + echo('开始升级QQWry...' . PHP_EOL); + $xcat->initQQWry(); + echo('升级QQWry结束' . PHP_EOL); + + echo(PHP_EOL); + + $config_old = file_get_contents(BASE_PATH . "/config/.config.php"); + $config_new = file_get_contents(BASE_PATH . "/config/.config.php.example"); + + //执行版本升级 + $version_old = 0; + if (isset($System_Config['version'])) { + $version_old = $System_Config['version']; + } + Update::old_to_new($version_old); + + //将旧config迁移到新config上 + $migrated = array(); + foreach ($System_Config as $key => $value_reserve) { + if ($key == 'config_migrate_notice' || $key == 'version') { + continue; + } + + $regex = '/System_Config\[\'' . $key . '\'\].*?;/s'; + $matches_new = array(); + preg_match($regex, $config_new, $matches_new); + if (isset($matches_new[0]) == false) { + echo('未找到配置项:' . $key . ' 未能在新config文件中找到,可能已被更名或废弃' . PHP_EOL); + continue; + } + + $matches_old = array(); + preg_match($regex, $config_old, $matches_old); + + $config_new = str_replace($matches_new[0], $matches_old[0], $config_new); + array_push($migrated, 'System_Config[\'' . $key . '\']'); + } + echo(PHP_EOL); + + //检查新增了哪些config + $regex_new = '/System_Config\[\'.*?\'\]/s'; + $matches_new_all = array(); + preg_match_all($regex_new, $config_new, $matches_new_all); + $differences = array_diff($matches_new_all[0], $migrated); + foreach ($differences as $difference) { + if ($difference == 'System_Config[\'config_migrate_notice\']' || + $difference == 'System_Config[\'version\']') { + continue; + } + //匹配注释 + $regex_comment = '/' . $difference . '.*?;.*?(?=\n)/s'; + $regex_comment = str_replace('[', '\[', $regex_comment); + $regex_comment = str_replace(']', '\]', $regex_comment); + $matches_comment = array(); + preg_match($regex_comment, $config_new, $matches_comment); + $comment = ""; + if (isset($matches_comment[0])) { + $comment = $matches_comment[0]; + $comment = substr( + $comment, strpos( + $comment, '//', strpos($comment, ';') //查找';'之后的第一个'//',然后substr其后面的comment + ) + 2 + ); + } + //裁去首尾 + $difference = substr($difference, 15); + $difference = substr($difference, 0, -2); + + echo('新增配置项:' . $difference . ':' . $comment . PHP_EOL); + } + echo('新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行' . PHP_EOL); + + //输出notice + $regex_notice = '/System_Config\[\'config_migrate_notice\'\].*?(?=\';)/s'; + $matches_notice = array(); + preg_match($regex_notice, $config_new, $matches_notice); + $notice_new = $matches_notice[0]; + $notice_new = substr( + $notice_new, strpos( + $notice_new, '\'', strpos($notice_new, '=') //查找'='之后的第一个'\'',然后substr其后面的notice + ) + 1 + ); + echo('以下是迁移附注:'); + if (isset($System_Config['config_migrate_notice'])) { + if ($System_Config['config_migrate_notice'] != $notice_new) { + echo($notice_new); + } + } else { + echo($notice_new); + } + echo(PHP_EOL); + + file_put_contents(BASE_PATH . "/config/.config.php", $config_new); + echo(PHP_EOL . '迁移完成' . PHP_EOL); + + echo(PHP_EOL); + + echo('开始升级composer依赖...' . PHP_EOL); + system('php ' . BASE_PATH . '/composer.phar selfupdate'); + system('php ' . BASE_PATH . '/composer.phar install -d ' . BASE_PATH); + echo('升级composer依赖结束,请自行根据上方输出确认是否升级成功' . PHP_EOL); + system('rm -rf ' . BASE_PATH . '/storage/framework/smarty/compile/*'); + system('chown -R www:www ' . BASE_PATH . '/storage'); } - public static function old_to_new($version_old) - { - if($version_old<=0){ - echo('执行升级:0 -> 1'); - $conn=mysqli_connect(Config::get('db_host'),Config::get('db_username'),Config::get('db_password'),Config::get('db_database')); - mysqli_query($conn,'ALTER TABLE user ADD discord BIGINT NULL AFTER telegram_id'); - } - } + public static function old_to_new($version_old) + { + if ($version_old <= 0) { + echo('执行升级:0 -> 1'); + $conn = mysqli_connect(Config::get('db_host'), Config::get('db_username'), Config::get('db_password'), Config::get('db_database')); + mysqli_query($conn, 'ALTER TABLE user ADD discord BIGINT NULL AFTER telegram_id'); + } + } } diff --git a/app/Controllers/Admin/AnnController.php b/app/Controllers/Admin/AnnController.php index d7f82c63..4c82f375 100644 --- a/app/Controllers/Admin/AnnController.php +++ b/app/Controllers/Admin/AnnController.php @@ -16,9 +16,9 @@ class AnnController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("op" => "操作", "id" => "ID", - "date" => "日期", "content" => "内容"); + "date" => "日期", "content" => "内容"); $table_config['default_show_column'] = array("op", "id", - "date", "content"); + "date", "content"); $table_config['ajax_url'] = 'announcement/ajax'; return $this->view()->assign('table_config', $table_config)->display('admin/announcement/index.tpl'); } @@ -31,15 +31,15 @@ class AnnController extends AdminController public function add($request, $response, $args) { $issend = $request->getParam('issend'); - $PushBear = $request->getParam('PushBear'); + $PushBear = $request->getParam('PushBear'); $vip = $request->getParam('vip'); $content = $request->getParam('content'); - if($request->getParam('page') == 1){ + if ($request->getParam('page') == 1) { $ann = new Ann(); - $ann->date = date("Y-m-d H:i:s"); - $ann->content = $content; - $ann->markdown = $request->getParam('markdown'); + $ann->date = date("Y-m-d H:i:s"); + $ann->content = $content; + $ann->markdown = $request->getParam('markdown'); if (!$ann->save()) { $rs['ret'] = 0; @@ -47,19 +47,19 @@ class AnnController extends AdminController return $response->getBody()->write(json_encode($rs)); } } - if ($issend == 1){ - $beginSend = (int)($request->getParam('page') - 1) * Config::get('sendPageLimit'); - $users = User::where('class', ">=", $vip)->skip($beginSend)->limit(Config::get('sendPageLimit'))->get(); - foreach($users as $user){ - $subject = Config::get('appName')."-公告"; + if ($issend == 1) { + $beginSend = (int)($request->getParam('page') - 1) * Config::get('sendPageLimit'); + $users = User::where('class', ">=", $vip)->skip($beginSend)->limit(Config::get('sendPageLimit'))->get(); + foreach ($users as $user) { + $subject = Config::get('appName') . "-公告"; $to = $user->email; if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { - continue; + continue; } $text = $content; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -67,42 +67,42 @@ class AnnController extends AdminController } } } - if ($PushBear == 1){ - $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); - $postdata = http_build_query( - array( - 'text' => Config::get('appName')."-公告", - 'desp' => $$request->getParam('markdown') - )); - $opts = array('http' => - array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $postdata - )); - $context = stream_context_create($opts); - file_get_contents('https://sc.ftqq.com/'.$ScFtqq_SCKEY.'.send', false, $context); - - } - if(count($users) == Config::get('sendPageLimit')){ + if ($PushBear == 1) { + $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); + $postdata = http_build_query( + array( + 'text' => Config::get('appName') . "-公告", + 'desp' => $$request->getParam('markdown') + )); + $opts = array('http' => + array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $postdata + )); + $context = stream_context_create($opts); + file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context); + + } + if (count($users) == Config::get('sendPageLimit')) { $rs['ret'] = 2; $rs['msg'] = $request->getParam('page') + 1; return $response->getBody()->write(json_encode($rs)); - }else{ - Telegram::SendMarkdown("新公告:".PHP_EOL.$request->getParam('markdown')); + } else { + Telegram::SendMarkdown("新公告:" . PHP_EOL . $request->getParam('markdown')); $rs['ret'] = 1; - if ($issend == 1 && $PushBear == 1){ - $rs['msg'] = "公告添加成功,邮件发送和PushBear推送成功"; - } - if($issend == 1 && $PushBear != 1){ - $rs['msg'] = "公告添加成功,邮件发送成功"; - } - if($issend != 1 && $PushBear == 1){ - $rs['msg'] = "公告添加成功,PushBear推送成功"; - } - if($issend != 1 && $PushBear != 1){ - $rs['msg'] = "公告添加成功"; - } + if ($issend == 1 && $PushBear == 1) { + $rs['msg'] = "公告添加成功,邮件发送和PushBear推送成功"; + } + if ($issend == 1 && $PushBear != 1) { + $rs['msg'] = "公告添加成功,邮件发送成功"; + } + if ($issend != 1 && $PushBear == 1) { + $rs['msg'] = "公告添加成功,PushBear推送成功"; + } + if ($issend != 1 && $PushBear != 1) { + $rs['msg'] = "公告添加成功"; + } return $response->getBody()->write(json_encode($rs)); } } @@ -121,9 +121,9 @@ class AnnController extends AdminController $id = $args['id']; $ann = Ann::find($id); - $ann->content = $request->getParam('content'); - $ann->markdown = $request->getParam('markdown'); - $ann->date = date("Y-m-d H:i:s"); + $ann->content = $request->getParam('content'); + $ann->markdown = $request->getParam('markdown'); + $ann->date = date("Y-m-d H:i:s"); if (!$ann->save()) { $rs['ret'] = 0; @@ -131,7 +131,7 @@ class AnnController extends AdminController return $response->getBody()->write(json_encode($rs)); } - Telegram::SendMarkdown("公告更新:".PHP_EOL.$request->getParam('markdown')); + Telegram::SendMarkdown("公告更新:" . PHP_EOL . $request->getParam('markdown')); $rs['ret'] = 1; $rs['msg'] = "修改成功"; @@ -159,12 +159,12 @@ class AnnController extends AdminController $datatables->query('Select id as op,id,date,content from announcement'); $datatables->edit('op', function ($data) { - return '编辑 - 删除'; + return '编辑 + 删除'; }); $datatables->edit('DT_RowId', function ($data) { - return 'row_1_'.$data['id']; + return 'row_1_' . $data['id']; }); $body = $response->getBody(); diff --git a/app/Controllers/Admin/AutoController.php b/app/Controllers/Admin/AutoController.php index e22fe024..81280e96 100644 --- a/app/Controllers/Admin/AutoController.php +++ b/app/Controllers/Admin/AutoController.php @@ -13,9 +13,9 @@ class autoController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", - "datetime" => "时间", "type" => "类型", "value" => "内容"); + "datetime" => "时间", "type" => "类型", "value" => "内容"); $table_config['default_show_column'] = array("op", "id", - "datetime", "type", "value"); + "datetime", "type", "value"); $table_config['ajax_url'] = 'auto/ajax'; return $this->view()->assign('table_config', $table_config)->display('admin/auto/index.tpl'); } @@ -28,10 +28,10 @@ class autoController extends AdminController public function add($request, $response, $args) { $auto = new Auto(); - $auto->datetime = time(); - $auto->value = $request->getParam('content'); - $auto->sign = $request->getParam('sign'); - $auto->type = 1; + $auto->datetime = time(); + $auto->value = $request->getParam('content'); + $auto->sign = $request->getParam('sign'); + $auto->type = 1; if (!$auto->save()) { $rs['ret'] = 0; diff --git a/app/Controllers/Admin/CodeController.php b/app/Controllers/Admin/CodeController.php index b12477de..90e0be0e 100644 --- a/app/Controllers/Admin/CodeController.php +++ b/app/Controllers/Admin/CodeController.php @@ -16,9 +16,9 @@ class CodeController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", "code" => "内容", - "type" => "类型", "number" => "操作", - "isused" => "是否已经使用", "userid" => "用户ID", - "user_name" => "用户名", "usedatetime" => "使用时间"); + "type" => "类型", "number" => "操作", + "isused" => "是否已经使用", "userid" => "用户ID", + "user_name" => "用户名", "usedatetime" => "使用时间"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -43,11 +43,11 @@ class CodeController extends AdminController $type = $request->getParam('type'); $number = $request->getParam('number'); - if(Tools::isInt($n)==false){ - $rs['ret'] = 0; + if (Tools::isInt($n) == false) { + $rs['ret'] = 0; $rs['msg'] = "非法请求"; return $response->getBody()->write(json_encode($rs)); - } + } for ($i = 0; $i < $n; $i++) { $char = Tools::genRandomChar(32); @@ -55,13 +55,12 @@ class CodeController extends AdminController $code->code = time() . $char; $code->type = -1; $code->number = $number; - $code->userid=0; - $code->usedatetime="1989:06:04 02:30:00"; + $code->userid = 0; + $code->usedatetime = "1989:06:04 02:30:00"; $code->save(); } - $rs['ret'] = 1; $rs['msg'] = "充值码添加成功"; return $response->getBody()->write(json_encode($rs)); @@ -96,14 +95,14 @@ class CodeController extends AdminController $datatables->edit('number', function ($data) { switch ($data['type']) { - case -1: - return "充值 ".$data['number']." 元"; + case -1: + return "充值 " . $data['number'] . " 元"; - case -2: - return "支出 ".$data['number']." 元"; + case -2: + return "支出 " . $data['number'] . " 元"; - default: - return "已经废弃"; + default: + return "已经废弃"; } }); @@ -126,14 +125,14 @@ class CodeController extends AdminController $datatables->edit('type', function ($data) { switch ($data['type']) { - case -1: - return "充值金额"; + case -1: + return "充值金额"; - case -2: - return "财务支出"; + case -2: + return "财务支出"; - default: - return "已经废弃"; + default: + return "已经废弃"; } }); diff --git a/app/Controllers/Admin/DetectController.php b/app/Controllers/Admin/DetectController.php index f7395231..d4943862 100644 --- a/app/Controllers/Admin/DetectController.php +++ b/app/Controllers/Admin/DetectController.php @@ -15,8 +15,8 @@ class DetectController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("op" => "操作", "id" => "ID", "name" => "名称", - "text" => "介绍", "regex" => "正则表达式", - "type" => "类型"); + "text" => "介绍", "regex" => "正则表达式", + "type" => "类型"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -28,11 +28,11 @@ class DetectController extends AdminController public function log($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", "user_id" => "用户ID", - "user_name" => "用户名", "node_id" => "节点ID", - "node_name" => "节点名", "rule_id" => "规则ID", - "rule_name" => "规则名", "rule_text" => "规则描述", - "rule_regex" => "规则正则表达式", "rule_type" => "规则类型", - "datetime" => "时间"); + "user_name" => "用户名", "node_id" => "节点ID", + "node_name" => "节点名", "rule_id" => "规则ID", + "rule_name" => "规则名", "rule_text" => "规则描述", + "rule_regex" => "规则正则表达式", "rule_type" => "规则类型", + "datetime" => "时间"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -49,10 +49,10 @@ class DetectController extends AdminController public function add($request, $response, $args) { $rule = new DetectRule(); - $rule->name = $request->getParam('name'); - $rule->text = $request->getParam('text'); - $rule->regex = $request->getParam('regex'); - $rule->type = $request->getParam('type'); + $rule->name = $request->getParam('name'); + $rule->text = $request->getParam('text'); + $rule->regex = $request->getParam('regex'); + $rule->type = $request->getParam('type'); if (!$rule->save()) { $rs['ret'] = 0; @@ -60,7 +60,7 @@ class DetectController extends AdminController return $response->getBody()->write(json_encode($rs)); } - Telegram::SendMarkdown("有新的审计规则:".$rule->name); + Telegram::SendMarkdown("有新的审计规则:" . $rule->name); $rs['ret'] = 1; $rs['msg'] = "添加成功"; @@ -79,10 +79,10 @@ class DetectController extends AdminController $id = $args['id']; $rule = DetectRule::find($id); - $rule->name = $request->getParam('name'); - $rule->text = $request->getParam('text'); - $rule->regex = $request->getParam('regex'); - $rule->type = $request->getParam('type'); + $rule->name = $request->getParam('name'); + $rule->text = $request->getParam('text'); + $rule->regex = $request->getParam('regex'); + $rule->type = $request->getParam('type'); if (!$rule->save()) { $rs['ret'] = 0; @@ -90,7 +90,7 @@ class DetectController extends AdminController return $response->getBody()->write(json_encode($rs)); } - Telegram::SendMarkdown("规则更新:".PHP_EOL.$request->getParam('name')); + Telegram::SendMarkdown("规则更新:" . PHP_EOL . $request->getParam('name')); $rs['ret'] = 1; $rs['msg'] = "修改成功"; @@ -118,8 +118,8 @@ class DetectController extends AdminController $datatables->query('Select id as op,id,name,text,regex,type from detect_list'); $datatables->edit('op', function ($data) { - return '编辑 - 删除'; + return '编辑 + 删除'; }); $datatables->edit('type', function ($data) { diff --git a/app/Controllers/Admin/IpController.php b/app/Controllers/Admin/IpController.php index d6de9a67..1999dd74 100644 --- a/app/Controllers/Admin/IpController.php +++ b/app/Controllers/Admin/IpController.php @@ -20,8 +20,8 @@ class IpController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", "userid" => "用户ID", - "user_name" => "用户名", "ip" => "IP", - "location" => "归属地", "datetime" => "时间", "type" => "类型"); + "user_name" => "用户名", "ip" => "IP", + "location" => "归属地", "datetime" => "时间", "type" => "类型"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -33,9 +33,9 @@ class IpController extends AdminController public function alive($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", "userid" => "用户ID", - "user_name" => "用户名", "nodeid" => "节点ID", - "node_name" => "节点名", "ip" => "IP", - "location" => "归属地", "datetime" => "时间", "is_node" => "是否为中转连接"); + "user_name" => "用户名", "nodeid" => "节点ID", + "node_name" => "节点名", "ip" => "IP", + "location" => "归属地", "datetime" => "时间", "is_node" => "是否为中转连接"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -47,8 +47,8 @@ class IpController extends AdminController public function block($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", - "name" => "节点名称", "ip" => "IP", - "location" => "归属地", "datetime" => "时间"); + "name" => "节点名称", "ip" => "IP", + "location" => "归属地", "datetime" => "时间"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -60,8 +60,8 @@ class IpController extends AdminController public function unblock($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", "userid" => "用户ID", - "user_name" => "用户名", "ip" => "IP", - "location" => "归属地", "datetime" => "时间"); + "user_name" => "用户名", "ip" => "IP", + "location" => "归属地", "datetime" => "时间"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -88,7 +88,7 @@ class IpController extends AdminController $res['ret'] = 1; - $res['msg'] = "发送解封命令解封 ".$ip." 成功"; + $res['msg'] = "发送解封命令解封 " . $ip . " 成功"; return $this->echoJson($response, $res); } @@ -104,8 +104,8 @@ class IpController extends AdminController $iplocation = new QQWry(); $datatables->edit('location', function ($data) use ($iplocation) { - $location=$iplocation->getlocation($data['location']); - return iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $location = $iplocation->getlocation($data['location']); + return iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); }); $body = $response->getBody(); @@ -124,8 +124,8 @@ class IpController extends AdminController $iplocation = new QQWry(); $datatables->edit('location', function ($data) use ($iplocation) { - $location=$iplocation->getlocation($data['location']); - return iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $location = $iplocation->getlocation($data['location']); + return iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); }); $body = $response->getBody(); @@ -144,8 +144,8 @@ class IpController extends AdminController $iplocation = new QQWry(); $datatables->edit('location', function ($data) use ($iplocation) { - $location=$iplocation->getlocation($data['location']); - return iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $location = $iplocation->getlocation($data['location']); + return iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); }); $datatables->edit('type', function ($data) { @@ -168,13 +168,13 @@ class IpController extends AdminController $iplocation = new QQWry(); - $datatables->edit('ip', function ($data){ + $datatables->edit('ip', function ($data) { return Tools::getRealIp($data['ip']); }); - $datatables->edit('is_node', function ($data){ + $datatables->edit('is_node', function ($data) { $is_node = Node::where("node_ip", Tools::getRealIp($data['ip']))->first(); - if($is_node) { + if ($is_node) { return "是"; } else { return "否"; @@ -182,8 +182,8 @@ class IpController extends AdminController }); $datatables->edit('location', function ($data) use ($iplocation) { - $location=$iplocation->getlocation(Tools::getRealIp($data['location'])); - return iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $location = $iplocation->getlocation(Tools::getRealIp($data['location'])); + return iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); }); $body = $response->getBody(); diff --git a/app/Controllers/Admin/NodeController.php b/app/Controllers/Admin/NodeController.php index 528914cf..e25855c3 100644 --- a/app/Controllers/Admin/NodeController.php +++ b/app/Controllers/Admin/NodeController.php @@ -17,15 +17,15 @@ class NodeController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = Array("op" => "操作", "id" => "ID", "name" => "节点名称", - "type" => "显示与隐藏", "sort" => "类型", - "server" => "节点地址", "node_ip" => "节点IP", - "info" => "节点信息", - "status" => "状态", "traffic_rate" => "流量比率", "node_group" => "节点群组", - "node_class" => "节点等级", "node_speedlimit" => "节点限速/Mbps", - "node_bandwidth" => "已走流量/GB", "node_bandwidth_limit" => "流量限制/GB", - "bandwidthlimit_resetday" => "流量重置日", "node_heartbeat" => "上一次活跃时间", - "custom_method" => "自定义加密", "custom_rss" => "自定义协议以及混淆", - "mu_only" => "只启用单端口多用户"); + "type" => "显示与隐藏", "sort" => "类型", + "server" => "节点地址", "node_ip" => "节点IP", + "info" => "节点信息", + "status" => "状态", "traffic_rate" => "流量比率", "node_group" => "节点群组", + "node_class" => "节点等级", "node_speedlimit" => "节点限速/Mbps", + "node_bandwidth" => "已走流量/GB", "node_bandwidth_limit" => "流量限制/GB", + "bandwidthlimit_resetday" => "流量重置日", "node_heartbeat" => "上一次活跃时间", + "custom_method" => "自定义加密", "custom_rss" => "自定义协议以及混淆", + "mu_only" => "只启用单端口多用户"); $table_config['default_show_column'] = Array("op", "id", "name", "sort"); $table_config['ajax_url'] = 'node/ajax'; @@ -40,12 +40,12 @@ class NodeController extends AdminController public function add($request, $response, $args) { $node = new Node(); - $node->name = $request->getParam('name'); - $node->server = trim($request->getParam('server')); - $node->method = $request->getParam('method'); - $node->custom_method = $request->getParam('custom_method'); - $node->custom_rss = $request->getParam('custom_rss'); - $node->mu_only = $request->getParam('mu_only'); + $node->name = $request->getParam('name'); + $node->server = trim($request->getParam('server')); + $node->method = $request->getParam('method'); + $node->custom_method = $request->getParam('custom_method'); + $node->custom_rss = $request->getParam('custom_rss'); + $node->mu_only = $request->getParam('mu_only'); $node->traffic_rate = $request->getParam('rate'); $node->info = $request->getParam('info'); $node->type = $request->getParam('type'); @@ -55,9 +55,9 @@ class NodeController extends AdminController $node->sort = $request->getParam('sort'); $req_node_ip = trim($request->getParam('node_ip')); - if($req_node_ip==""){ - $req_node_ip=$node->server; - } + if ($req_node_ip == "") { + $req_node_ip = $node->server; + } if (in_array($node->sort, array(0, 1, 10, 11, 12, 13))) { $server_list = explode(";", $node->server); @@ -75,21 +75,21 @@ class NodeController extends AdminController $node->node_ip = ""; } - if ($node->sort==1) { + if ($node->sort == 1) { Radius::AddNas($node->node_ip, $request->getParam('server')); } - $node->node_class=$request->getParam('class'); - $node->node_bandwidth_limit=$request->getParam('node_bandwidth_limit')*1024*1024*1024; - $node->bandwidthlimit_resetday=$request->getParam('bandwidthlimit_resetday'); + $node->node_class = $request->getParam('class'); + $node->node_bandwidth_limit = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024; + $node->bandwidthlimit_resetday = $request->getParam('bandwidthlimit_resetday'); $node->save(); - $domain_name = explode('.'.Config::get('cloudflare_name'), $node->server); + $domain_name = explode('.' . Config::get('cloudflare_name'), $node->server); if (Config::get('cloudflare_enable') == 'true') { CloudflareDriver::updateRecord($domain_name[0], $node->node_ip); } - Telegram::Send("新节点添加~".$request->getParam('name')); + Telegram::Send("新节点添加~" . $request->getParam('name')); $rs['ret'] = 1; $rs['msg'] = "节点添加成功"; @@ -110,25 +110,25 @@ class NodeController extends AdminController $id = $args['id']; $node = Node::find($id); - $node->name = $request->getParam('name'); - $node->node_group = $request->getParam('group'); - $node->server = trim($request->getParam('server')); - $node->method = $request->getParam('method'); - $node->custom_method = $request->getParam('custom_method'); - $node->custom_rss = $request->getParam('custom_rss'); - $node->mu_only = $request->getParam('mu_only'); + $node->name = $request->getParam('name'); + $node->node_group = $request->getParam('group'); + $node->server = trim($request->getParam('server')); + $node->method = $request->getParam('method'); + $node->custom_method = $request->getParam('custom_method'); + $node->custom_rss = $request->getParam('custom_rss'); + $node->mu_only = $request->getParam('mu_only'); $node->traffic_rate = $request->getParam('rate'); $node->info = $request->getParam('info'); $node->node_speedlimit = $request->getParam('node_speedlimit'); $node->type = $request->getParam('type'); $node->sort = $request->getParam('sort'); - $req_node_ip=trim($request->getParam('node_ip')); - if($req_node_ip==""){ - $req_node_ip=$node->server; - } + $req_node_ip = trim($request->getParam('node_ip')); + if ($req_node_ip == "") { + $req_node_ip = $node->server; + } - $success=true; + $success = true; if (in_array($node->sort, array(0, 1, 10, 11, 12, 13))) { $server_list = explode(";", $node->server); if (!Tools::is_ip($server_list[0])) { @@ -140,36 +140,35 @@ class NodeController extends AdminController $node->node_ip = ""; } - if (!$success) { - $rs['ret'] = 0; + if (!$success) { + $rs['ret'] = 0; $rs['msg'] = "更新节点IP失败,请检查您输入的节点地址是否正确!"; return $response->getBody()->write(json_encode($rs)); - } - - if (in_array($node->sort, array(0, 10, 11, 12, 13))) { - Tools::updateRelayRuleIp($node); - } - - if ($node->sort==1) { - $SS_Node=Node::where('sort', '=', 0)->where('server', '=', $request->getParam('server'))->first(); - if ($SS_Node!=null) { - if (time()-$SS_Node->node_heartbeat<300||$SS_Node->node_heartbeat==0) { + } + + if (in_array($node->sort, array(0, 10, 11, 12, 13))) { + Tools::updateRelayRuleIp($node); + } + + if ($node->sort == 1) { + $SS_Node = Node::where('sort', '=', 0)->where('server', '=', $request->getParam('server'))->first(); + if ($SS_Node != null) { + if (time() - $SS_Node->node_heartbeat < 300 || $SS_Node->node_heartbeat == 0) { Radius::AddNas(gethostbyname($request->getParam('server')), $request->getParam('server')); } - } - else { + } else { Radius::AddNas(gethostbyname($request->getParam('server')), $request->getParam('server')); } } $node->status = $request->getParam('status'); - $node->node_class=$request->getParam('class'); - $node->node_bandwidth_limit=$request->getParam('node_bandwidth_limit')*1024*1024*1024; - $node->bandwidthlimit_resetday=$request->getParam('bandwidthlimit_resetday'); + $node->node_class = $request->getParam('class'); + $node->node_bandwidth_limit = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024; + $node->bandwidthlimit_resetday = $request->getParam('bandwidthlimit_resetday'); $node->save(); - Telegram::Send("节点信息被修改~".$request->getParam('name')); + Telegram::Send("节点信息被修改~" . $request->getParam('name')); $rs['ret'] = 1; $rs['msg'] = "修改成功"; @@ -181,7 +180,7 @@ class NodeController extends AdminController { $id = $request->getParam('id'); $node = Node::find($id); - if ($node->sort==1) { + if ($node->sort == 1) { Radius::DelNas($node->node_ip); } @@ -193,7 +192,7 @@ class NodeController extends AdminController return $response->getBody()->write(json_encode($rs)); } - Telegram::Send("节点被删除~".$name); + Telegram::Send("节点被删除~" . $name); $rs['ret'] = 1; $rs['msg'] = "删除成功"; @@ -206,29 +205,29 @@ class NodeController extends AdminController $total_column = Array("op" => "操作", "id" => "ID", "name" => "节点名称", - "type" => "显示与隐藏", "sort" => "类型", - "server" => "节点地址", "node_ip" => "节点IP", - "info" => "节点信息", - "status" => "状态", "traffic_rate" => "流量比率", "node_group" => "节点群组", - "node_class" => "节点等级", "node_speedlimit" => "节点限速/Mbps", - "node_bandwidth" => "已走流量/GB", "node_bandwidth_limit" => "流量限制/GB", - "bandwidthlimit_resetday" => "流量重置日", "node_heartbeat" => "上一次活跃时间", - "custom_method" => "自定义加密", "custom_rss" => "自定义协议以及混淆", - "mu_only" => "只启用单端口多用户"); + "type" => "显示与隐藏", "sort" => "类型", + "server" => "节点地址", "node_ip" => "节点IP", + "info" => "节点信息", + "status" => "状态", "traffic_rate" => "流量比率", "node_group" => "节点群组", + "node_class" => "节点等级", "node_speedlimit" => "节点限速/Mbps", + "node_bandwidth" => "已走流量/GB", "node_bandwidth_limit" => "流量限制/GB", + "bandwidthlimit_resetday" => "流量重置日", "node_heartbeat" => "上一次活跃时间", + "custom_method" => "自定义加密", "custom_rss" => "自定义协议以及混淆", + "mu_only" => "只启用单端口多用户"); $key_str = ''; - foreach($total_column as $single_key => $single_value) { - if($single_key == 'op') { + foreach ($total_column as $single_key => $single_value) { + if ($single_key == 'op') { $key_str .= 'id as op'; continue; } - $key_str .= ','.$single_key; + $key_str .= ',' . $single_key; } - $datatables->query('Select '.$key_str.' from ss_node'); + $datatables->query('Select ' . $key_str . ' from ss_node'); $datatables->edit('op', function ($data) { - return '编辑 - 删除'; + return '编辑 + 删除'; }); $datatables->edit('node_bandwidth', function ($data) { @@ -241,36 +240,36 @@ class NodeController extends AdminController $datatables->edit('sort', function ($data) { $sort = ''; - switch($data['sort']) { + switch ($data['sort']) { case 0: - $sort = 'Shadowsocks'; - break; + $sort = 'Shadowsocks'; + break; case 1: - $sort = 'VPN/Radius基础'; - break; + $sort = 'VPN/Radius基础'; + break; case 2: - $sort = 'SSH'; - break; + $sort = 'SSH'; + break; case 5: - $sort = 'Anyconnect'; - break; + $sort = 'Anyconnect'; + break; case 9: - $sort = 'Shadowsocks - 单端口多用户'; - break; + $sort = 'Shadowsocks - 单端口多用户'; + break; case 10: - $sort = 'Shadowsocks - 中转'; - break; + $sort = 'Shadowsocks - 中转'; + break; case 11: - $sort = 'V2Ray 节点'; - break; + $sort = 'V2Ray 节点'; + break; case 12: - $sort = 'V2Ray - 中转'; - break; + $sort = 'V2Ray - 中转'; + break; case 13: - $sort = 'Shadowsocks - V2Ray-Plugin'; - break; + $sort = 'Shadowsocks - V2Ray-Plugin'; + break; default: - $sort = '系统保留'; + $sort = '系统保留'; } return $sort; }); @@ -296,7 +295,7 @@ class NodeController extends AdminController }); $datatables->edit('DT_RowId', function ($data) { - return 'row_1_'.$data['id']; + return 'row_1_' . $data['id']; }); $body = $response->getBody(); diff --git a/app/Controllers/Admin/RelayController.php b/app/Controllers/Admin/RelayController.php index c8ec6b64..c3c3dc9b 100644 --- a/app/Controllers/Admin/RelayController.php +++ b/app/Controllers/Admin/RelayController.php @@ -17,8 +17,8 @@ class RelayController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("op" => "操作", "id" => "ID", "user_id" => "用户ID", - "user_name" => "用户名", "source_node_name" => "起源节点", - "dist_node_name" => "目标节点", "port" => "端口", "priority" => "优先级"); + "user_name" => "用户名", "source_node_name" => "起源节点", + "dist_node_name" => "目标节点", "port" => "端口", "priority" => "优先级"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -35,10 +35,10 @@ class RelayController extends AdminController $query->Where('sort', 10) ->orWhere('sort', 12); } - )->orderBy('name')->get(); - foreach($source_nodes as $node){ - if ($node->sort==12){ - $node->name = $node->name." 正在使用V2ray后端 "; + )->orderBy('name')->get(); + foreach ($source_nodes as $node) { + if ($node->sort == 12) { + $node->name = $node->name . " 正在使用V2ray后端 "; } } $dist_nodes = Node::where( @@ -50,12 +50,12 @@ class RelayController extends AdminController } )->orderBy('name')->get(); - foreach ($dist_nodes as $node){ - if ($node->sort==11 or $node->sort==12){ + foreach ($dist_nodes as $node) { + if ($node->sort == 11 or $node->sort == 12) { $node_explode = Tools::ssv2Array($node->server); - $node->name = $node->name." 如果是V2ray后端 请设置成 ".$node_explode['port']; - }else { - $node->name = $node->name." 如果是V2ray后端 请不要设置,用户页面设置 "; + $node->name = $node->name . " 如果是V2ray后端 请设置成 " . $node_explode['port']; + } else { + $node->name = $node->name . " 如果是V2ray后端 请不要设置,用户页面设置 "; } } @@ -77,9 +77,9 @@ class RelayController extends AdminController return $response->getBody()->write(json_encode($rs)); } - if ($source_node->sort==12){ + if ($source_node->sort == 12) { $rules = Relay::Where('source_node_id', $source_node_id)->get(); - if (count($rules)>0){ + if (count($rules) > 0) { $rs['ret'] = 0; $rs['msg'] = "v2ray中转一个起点一个rule"; return $response->getBody()->write(json_encode($rs)); @@ -111,7 +111,7 @@ class RelayController extends AdminController $maybe_rule_id = Tools::has_conflict_rule($rule, $ruleset, 0, $rule->source_node_id); if ($maybe_rule_id != 0) { $rs['ret'] = 0; - $rs['msg'] = "您即将添加的规则与规则 ID:".$maybe_rule_id." 冲突!"; + $rs['msg'] = "您即将添加的规则与规则 ID:" . $maybe_rule_id . " 冲突!"; if ($maybe_rule_id == -1) { $rs['msg'] = "您即将添加的规则可能会造成冲突!"; } @@ -144,11 +144,11 @@ class RelayController extends AdminController function ($query) { $query->Where('sort', 10) ->orWhere('sort', 12); - } - )->orderBy('name')->get(); - foreach($source_nodes as $node){ - if ($node->sort==12){ - $node->name = $node->name." 正在使用V2ray后端 "; + } + )->orderBy('name')->get(); + foreach ($source_nodes as $node) { + if ($node->sort == 12) { + $node->name = $node->name . " 正在使用V2ray后端 "; } } @@ -161,12 +161,12 @@ class RelayController extends AdminController } )->orderBy('name')->get(); - foreach ($dist_nodes as $node){ - if ($node->sort==11 or $node->sort==12){ + foreach ($dist_nodes as $node) { + if ($node->sort == 11 or $node->sort == 12) { $node_explode = Tools::ssv2Array($node->server); - $node->name = $node->name." 如果是V2ray后端 请设置成".$node_explode['port']; - }else { - $node->name = $node->name." 如果是V2ray后端 请不要设置,用户页面设置 "; + $node->name = $node->name . " 如果是V2ray后端 请设置成" . $node_explode['port']; + } else { + $node->name = $node->name . " 如果是V2ray后端 请不要设置,用户页面设置 "; } } @@ -220,7 +220,7 @@ class RelayController extends AdminController $maybe_rule_id = Tools::has_conflict_rule($rule, $ruleset, $rule->id, $rule->source_node_id); if ($maybe_rule_id != 0) { $rs['ret'] = 0; - $rs['msg'] = "您即将添加的规则与规则 ID:".$maybe_rule_id." 冲突!"; + $rs['msg'] = "您即将添加的规则与规则 ID:" . $maybe_rule_id . " 冲突!"; if ($maybe_rule_id == -1) { $rs['msg'] = "您即将添加的规则可能会造成冲突!"; } @@ -262,7 +262,7 @@ class RelayController extends AdminController public function path_search($request, $response, $args) { - $uid=$args["id"]; + $uid = $args["id"]; $user = User::find($uid); @@ -281,7 +281,7 @@ class RelayController extends AdminController $query->Where('sort', 10) ->orWhere('sort', 12); } - )->where("node_class", "<=", $user->class)->orderBy('name')->get(); + )->where("node_class", "<=", $user->class)->orderBy('name')->get(); $pathset = new \ArrayObject(); @@ -331,10 +331,10 @@ class RelayController extends AdminController if ($single_path->end_node->id == $path->begin_node->id) { $path->begin_node = $single_path->begin_node; if ($path->begin_node->isNodeAccessable() == false) { - $path->path = ''.$single_path->begin_node->name.''." → ".$path->path; + $path->path = '' . $single_path->begin_node->name . '' . " → " . $path->path; $path->status = "阻断"; } else { - $path->path = $single_path->begin_node->name." → ".$path->path; + $path->path = $single_path->begin_node->name . " → " . $path->path; $path->status = "通畅"; } @@ -345,10 +345,10 @@ class RelayController extends AdminController if ($path->end_node->id == $single_path->begin_node->id) { $path->end_node = $single_path->end_node; if ($single_path->end_node->isNodeAccessable() == false) { - $path->path = $path->path." → ".''.$single_path->end_node->name.''; + $path->path = $path->path . " → " . '' . $single_path->end_node->name . ''; $path->status = "阻断"; } else { - $path->path = $path->path." → ".$single_path->end_node->name; + $path->path = $path->path . " → " . $single_path->end_node->name; } $pathset->offsetUnset($index); @@ -367,8 +367,8 @@ class RelayController extends AdminController $datatables->query('Select relay.id as op,relay.id,relay.user_id,user.user_name,source_node.name as source_node_name,dist_node.name as dist_node_name,relay.port,relay.priority from relay,user,ss_node as source_node,ss_node as dist_node WHERE (relay.user_id = user.id or relay.user_id = 0) and source_node.id = relay.source_node_id and dist_node.id = relay.dist_node_id group by id'); $datatables->edit('op', function ($data) { - return '编辑 - 删除'; + return '编辑 + 删除'; }); $datatables->edit('user_name', function ($data) { diff --git a/app/Controllers/Admin/ShopController.php b/app/Controllers/Admin/ShopController.php index 84f364dc..53ed5865 100644 --- a/app/Controllers/Admin/ShopController.php +++ b/app/Controllers/Admin/ShopController.php @@ -15,9 +15,9 @@ class ShopController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("op" => "操作", "id" => "ID", "name" => "商品名称", - "price" => "价格", "content" => "商品内容", - "auto_renew" => "自动续费", "auto_reset_bandwidth" => "续费时是否重置流量", - "status" => "状态", "period_sales" => "周期销量"); + "price" => "价格", "content" => "商品内容", + "auto_renew" => "自动续费", "auto_reset_bandwidth" => "续费时是否重置流量", + "status" => "状态", "period_sales" => "周期销量"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -34,53 +34,53 @@ class ShopController extends AdminController public function add($request, $response, $args) { $shop = new Shop(); - $shop->name = $request->getParam('name'); - $shop->price = $request->getParam('price'); - $shop->auto_renew = $request->getParam('auto_renew'); - $shop->auto_reset_bandwidth = $request->getParam('auto_reset_bandwidth'); - - $content=array(); - if ($request->getParam('bandwidth')!=0) { - $content["bandwidth"]=$request->getParam('bandwidth'); + $shop->name = $request->getParam('name'); + $shop->price = $request->getParam('price'); + $shop->auto_renew = $request->getParam('auto_renew'); + $shop->auto_reset_bandwidth = $request->getParam('auto_reset_bandwidth'); + + $content = array(); + if ($request->getParam('bandwidth') != 0) { + $content["bandwidth"] = $request->getParam('bandwidth'); } - if ($request->getParam('expire')!=0) { - $content["expire"]=$request->getParam('expire'); + if ($request->getParam('expire') != 0) { + $content["expire"] = $request->getParam('expire'); } - if ($request->getParam('class')!=0) { - $content["class"]=$request->getParam('class'); + if ($request->getParam('class') != 0) { + $content["class"] = $request->getParam('class'); } - if ($request->getParam('class_expire')!=0) { - $content["class_expire"]=$request->getParam('class_expire'); + if ($request->getParam('class_expire') != 0) { + $content["class_expire"] = $request->getParam('class_expire'); } - if ($request->getParam('reset')!=0) { - $content["reset"]=$request->getParam('reset'); + if ($request->getParam('reset') != 0) { + $content["reset"] = $request->getParam('reset'); } - if ($request->getParam('reset_value')!=0) { - $content["reset_value"]=$request->getParam('reset_value'); + if ($request->getParam('reset_value') != 0) { + $content["reset_value"] = $request->getParam('reset_value'); } - if ($request->getParam('reset_exp')!=0) { - $content["reset_exp"]=$request->getParam('reset_exp'); + if ($request->getParam('reset_exp') != 0) { + $content["reset_exp"] = $request->getParam('reset_exp'); } //if ($request->getParam('speedlimit')!=0) { - $content["speedlimit"]=$request->getParam('speedlimit'); + $content["speedlimit"] = $request->getParam('speedlimit'); //} //if ($request->getParam('connector')!=0) { - $content["connector"]=$request->getParam('connector'); + $content["connector"] = $request->getParam('connector'); //} - if ($request->getParam('content_extra')!='') { - $content["content_extra"]=$request->getParam('content_extra'); + if ($request->getParam('content_extra') != '') { + $content["content_extra"] = $request->getParam('content_extra'); } - $shop->content=json_encode($content); + $shop->content = json_encode($content); if (!$shop->save()) { @@ -107,64 +107,64 @@ class ShopController extends AdminController $id = $args['id']; $shop = Shop::find($id); - $shop->name = $request->getParam('name'); - $shop->price = $request->getParam('price'); - $shop->auto_renew = $request->getParam('auto_renew'); + $shop->name = $request->getParam('name'); + $shop->price = $request->getParam('price'); + $shop->auto_renew = $request->getParam('auto_renew'); if ($shop->auto_reset_bandwidth == 1 && $request->getParam('auto_reset_bandwidth') == 0) { $boughts = Bought::where("shopid", $id)->get(); foreach ($boughts as $bought) { - $bought->renew=0; + $bought->renew = 0; $bought->save(); } } - $shop->auto_reset_bandwidth = $request->getParam('auto_reset_bandwidth'); - $shop->status=1; + $shop->auto_reset_bandwidth = $request->getParam('auto_reset_bandwidth'); + $shop->status = 1; - $content=array(); - if ($request->getParam('bandwidth')!=0) { - $content["bandwidth"]=$request->getParam('bandwidth'); + $content = array(); + if ($request->getParam('bandwidth') != 0) { + $content["bandwidth"] = $request->getParam('bandwidth'); } - if ($request->getParam('expire')!=0) { - $content["expire"]=$request->getParam('expire'); + if ($request->getParam('expire') != 0) { + $content["expire"] = $request->getParam('expire'); } - if ($request->getParam('class')!=0) { - $content["class"]=$request->getParam('class'); + if ($request->getParam('class') != 0) { + $content["class"] = $request->getParam('class'); } - if ($request->getParam('class_expire')!=0) { - $content["class_expire"]=$request->getParam('class_expire'); + if ($request->getParam('class_expire') != 0) { + $content["class_expire"] = $request->getParam('class_expire'); } - if ($request->getParam('reset')!=0) { - $content["reset"]=$request->getParam('reset'); + if ($request->getParam('reset') != 0) { + $content["reset"] = $request->getParam('reset'); } - if ($request->getParam('reset_value')!=0) { - $content["reset_value"]=$request->getParam('reset_value'); + if ($request->getParam('reset_value') != 0) { + $content["reset_value"] = $request->getParam('reset_value'); } - if ($request->getParam('reset_exp')!=0) { - $content["reset_exp"]=$request->getParam('reset_exp'); + if ($request->getParam('reset_exp') != 0) { + $content["reset_exp"] = $request->getParam('reset_exp'); } - + //if ($request->getParam('speedlimit')!=0) { - $content["speedlimit"]=$request->getParam('speedlimit'); + $content["speedlimit"] = $request->getParam('speedlimit'); //} //if ($request->getParam('connector')!=0) { - $content["connector"]=$request->getParam('connector'); + $content["connector"] = $request->getParam('connector'); //} - if ($request->getParam('content_extra')!='') { - $content["content_extra"]=$request->getParam('content_extra'); + if ($request->getParam('content_extra') != '') { + $content["content_extra"] = $request->getParam('content_extra'); } - $shop->content=json_encode($content); + $shop->content = json_encode($content); if (!$shop->save()) { $rs['ret'] = 0; @@ -177,12 +177,11 @@ class ShopController extends AdminController } - public function deleteGet($request, $response, $args) { $id = $request->getParam('id'); $shop = Shop::find($id); - $shop->status=0; + $shop->status = 0; if (!$shop->save()) { $rs['ret'] = 0; $rs['msg'] = "下架失败"; @@ -192,7 +191,7 @@ class ShopController extends AdminController $boughts = Bought::where("shopid", $id)->get(); foreach ($boughts as $bought) { - $bought->renew=0; + $bought->renew = 0; $bought->save(); } @@ -203,11 +202,11 @@ class ShopController extends AdminController public function bought($request, $response, $args) { - $table_config['total_column'] = array("op" => "操作", "id" => "ID", - "datetime" => "购买日期","content" => "内容", - "price" => "价格", "user_id" => "用户ID", - "user_name" => "用户名", "renew" => "自动续费时间", - "auto_reset_bandwidth" => "续费时是否重置流量"); + $table_config['total_column'] = array("op" => "操作", "id" => "ID", + "datetime" => "购买日期", "content" => "内容", + "price" => "价格", "user_id" => "用户ID", + "user_name" => "用户名", "renew" => "自动续费时间", + "auto_reset_bandwidth" => "续费时是否重置流量"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -220,7 +219,7 @@ class ShopController extends AdminController { $id = $request->getParam('id'); $shop = Bought::find($id); - $shop->renew=0; + $shop->renew = 0; if (!$shop->save()) { $rs['ret'] = 0; $rs['msg'] = "退订失败"; @@ -237,8 +236,8 @@ class ShopController extends AdminController $datatables->query('Select id as op,id,name,price,content,auto_renew,auto_reset_bandwidth,status,id as period_sales from shop'); $datatables->edit('op', function ($data) { - return '编辑 - 下架'; + return '编辑 + 下架'; }); $datatables->edit('content', function ($data) { @@ -250,29 +249,29 @@ class ShopController extends AdminController if ($data['auto_renew'] == 0) { return "不自动续费"; } else { - return $data['auto_renew']." 天后续费"; + return $data['auto_renew'] . " 天后续费"; } }); $datatables->edit('auto_reset_bandwidth', function ($data) { return $data['auto_reset_bandwidth'] == 0 ? '不自动重置' : '自动重置'; }); - + $datatables->edit('status', function ($data) { return $data['status'] == 1 ? '上架' : '下架'; }); $datatables->edit('period_sales', function ($data) { - $shop = Shop::find($data['id']); - $period=Config::get('sales_period'); + $shop = Shop::find($data['id']); + $period = Config::get('sales_period'); - if($period=='expire'){ - $period=json_decode($shop->content,true)['class_expire']; - } + if ($period == 'expire') { + $period = json_decode($shop->content, true)['class_expire']; + } - $period=$period*24*60*60; - $sales = Bought::where('shopid',$shop->id)->where('datetime','>' ,time()-$period)->count(); - return $sales; + $period = $period * 24 * 60 * 60; + $sales = Bought::where('shopid', $shop->id)->where('datetime', '>', time() - $period)->count(); + return $sales; }); $body = $response->getBody(); @@ -285,7 +284,7 @@ class ShopController extends AdminController $datatables->query('Select bought.id as op,bought.id as id,bought.datetime,shop.id as content,bought.price,user.id as user_id,user.user_name,renew,shop.auto_reset_bandwidth from bought,user,shop where bought.shopid = shop.id and bought.userid = user.id'); $datatables->edit('op', function ($data) { - return '中止'; + return '中止'; }); $datatables->edit('content', function ($data) { @@ -297,7 +296,7 @@ class ShopController extends AdminController if ($data['renew'] == 0) { return "不自动续费"; } else { - return date('Y-m-d H:i:s', $data['renew'])." 续费"; + return date('Y-m-d H:i:s', $data['renew']) . " 续费"; } }); diff --git a/app/Controllers/Admin/TicketController.php b/app/Controllers/Admin/TicketController.php index a1bdee86..2eb63f8d 100644 --- a/app/Controllers/Admin/TicketController.php +++ b/app/Controllers/Admin/TicketController.php @@ -21,16 +21,15 @@ class TicketController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("op" => "操作", "id" => "ID", - "datetime" => "时间", "title" => "标题", "userid" => "用户ID", - "user_name" => "用户名", "status" => "状态"); + "datetime" => "时间", "title" => "标题", "userid" => "用户ID", + "user_name" => "用户名", "status" => "状态"); $table_config['default_show_column'] = array("op", "id", - "datetime", "title", "userid", "user_name", "status"); + "datetime", "title", "userid", "user_name", "status"); $table_config['ajax_url'] = 'ticket/ajax'; return $this->view()->assign('table_config', $table_config)->display('admin/ticket/index.tpl'); } - public function update($request, $response, $args) { $id = $args['id']; @@ -38,31 +37,31 @@ class TicketController extends AdminController $status = $request->getParam('status'); - if ($content==""||$status=="") { + if ($content == "" || $status == "") { $res['ret'] = 0; $res['msg'] = "请填全"; return $this->echoJson($response, $res); } - if (strpos($content, "admin")!=false||strpos($content, "user")!=false) { + if (strpos($content, "admin") != false || strpos($content, "user") != false) { $res['ret'] = 0; $res['msg'] = "请求中有不正当的词语。"; return $this->echoJson($response, $res); } - $ticket_main=Ticket::where("id", "=", $id)->where("rootid", "=", 0)->first(); + $ticket_main = Ticket::where("id", "=", $id)->where("rootid", "=", 0)->first(); //if($status==1&&$ticket_main->status!=$status) { $adminUser = User::where("id", "=", $ticket_main->userid)->get(); foreach ($adminUser as $user) { - $subject = Config::get('appName')."-工单被回复"; + $subject = Config::get('appName') . "-工单被回复"; $to = $user->email; - $text = "您好,有人回复了id."/view\">工单,请您查看。" ; + $text = "您好,有人回复了id . "/view\">工单,请您查看。"; try { Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -73,13 +72,13 @@ class TicketController extends AdminController $antiXss = new AntiXSS(); - $ticket=new Ticket(); - $ticket->title=$antiXss->xss_clean($ticket_main->title); - $ticket->content=$antiXss->xss_clean($content); - $ticket->rootid=$ticket_main->id; - $ticket->userid=Auth::getUser()->id; - $ticket->datetime=time(); - $ticket_main->status=$status; + $ticket = new Ticket(); + $ticket->title = $antiXss->xss_clean($ticket_main->title); + $ticket->content = $antiXss->xss_clean($content); + $ticket->rootid = $ticket_main->id; + $ticket->userid = Auth::getUser()->id; + $ticket->datetime = time(); + $ticket_main->status = $status; $ticket_main->save(); $ticket->save(); @@ -99,8 +98,8 @@ class TicketController extends AdminController } - $ticketset=Ticket::where("id", $id)->orWhere("rootid", "=", $id)->orderBy("datetime", "desc")->paginate(5, ['*'], 'page', $pageNum); - $ticketset->setPath('/admin/ticket/'.$id."/view"); + $ticketset = Ticket::where("id", $id)->orWhere("rootid", "=", $id)->orderBy("datetime", "desc")->paginate(5, ['*'], 'page', $pageNum); + $ticketset->setPath('/admin/ticket/' . $id . "/view"); return $this->view()->assign('ticketset', $ticketset)->assign("id", $id)->display('admin/ticket/view.tpl'); } @@ -111,7 +110,7 @@ class TicketController extends AdminController $datatables->query('Select ticket.id as op,ticket.id,ticket.datetime,ticket.title,ticket.userid,user.user_name,ticket.status from ticket,user where ticket.userid = user.id and ticket.rootid = 0'); $datatables->edit('op', function ($data) { - return '查看'; + return '查看'; }); $datatables->edit('datetime', function ($data) { diff --git a/app/Controllers/Admin/UserController.php b/app/Controllers/Admin/UserController.php index cd3542d6..910587c1 100644 --- a/app/Controllers/Admin/UserController.php +++ b/app/Controllers/Admin/UserController.php @@ -25,24 +25,26 @@ class UserController extends AdminController public function index($request, $response, $args) { $table_config['total_column'] = array("op" => "操作", "id" => "ID", "user_name" => "用户名", - "remark" => "备注", "email" => "邮箱", "money" => "金钱", - "im_type" => "联络方式类型", "im_value" => "联络方式详情", - "node_group" => "群组", "expire_in" => "账户过期时间", - "class" => "等级", "class_expire" => "等级过期时间", - "passwd" => "连接密码","port" => "连接端口", "method" => "加密方式", - "protocol" => "连接协议", "obfs" => "连接混淆方式", - "online_ip_count" => "在线IP数", "last_ss_time" => "上次使用时间", - "used_traffic" => "已用流量/GB", "enable_traffic" => "总流量/GB", - "last_checkin_time" => "上次签到时间", "today_traffic" => "今日流量/MB", - "enable" => "是否启用", "reg_date" => "注册时间", - "reg_ip" => "注册IP", "auto_reset_day" => "自动重置流量日", - "auto_reset_bandwidth" => "自动重置流量/GB", "ref_by" => "邀请人ID", "ref_by_user_name" => "邀请人用户名", - "top_up" => "累计充值"); + "remark" => "备注", "email" => "邮箱", "money" => "金钱", + "im_type" => "联络方式类型", "im_value" => "联络方式详情", + "node_group" => "群组", "expire_in" => "账户过期时间", + "class" => "等级", "class_expire" => "等级过期时间", + "passwd" => "连接密码", "port" => "连接端口", "method" => "加密方式", + "protocol" => "连接协议", "obfs" => "连接混淆方式", + "online_ip_count" => "在线IP数", "last_ss_time" => "上次使用时间", + "used_traffic" => "已用流量/GB", "enable_traffic" => "总流量/GB", + "last_checkin_time" => "上次签到时间", "today_traffic" => "今日流量/MB", + "enable" => "是否启用", "reg_date" => "注册时间", + "reg_ip" => "注册IP", "auto_reset_day" => "自动重置流量日", + "auto_reset_bandwidth" => "自动重置流量/GB", "ref_by" => "邀请人ID", "ref_by_user_name" => "邀请人用户名", + "top_up" => "累计充值"); $table_config['default_show_column'] = array("op", "id", "user_name", "remark", "email"); $table_config['ajax_url'] = 'user/ajax'; return $this->view()->assign('table_config', $table_config)->display('admin/user/index.tpl'); } - public function createNewUser($request, $response, $args){ + + public function createNewUser($request, $response, $args) + { # 需要一个 userEmail $email = $request->getParam('userEmail'); $email = trim($email); @@ -63,7 +65,7 @@ class UserController extends AdminController // do reg user $user = new User(); $pass = Tools::genRandomChar(8); - $user->user_name =$email; + $user->user_name = $email; $user->email = $email; $user->pass = Hash::passwordHash($pass); $user->passwd = Tools::genRandomChar(6); @@ -95,9 +97,9 @@ class UserController extends AdminController $user->plan = 'A'; $user->theme = Config::get('theme'); - $groups=explode(",", Config::get('ramdom_group')); + $groups = explode(",", Config::get('ramdom_group')); - $user->node_group=$groups[array_rand($groups)]; + $user->node_group = $groups[array_rand($groups)]; $ga = new GA(); $secret = $ga->createSecret(); @@ -106,14 +108,14 @@ class UserController extends AdminController $user->ga_enable = 0; if ($user->save()) { $res['ret'] = 1; - $res['msg'] = "新用户注册成功 用户名: ".$email." 随机初始密码: ".$pass; - $res['email_error']="success"; - $subject = Config::get('appName')."-新用户注册通知"; + $res['msg'] = "新用户注册成功 用户名: " . $email . " 随机初始密码: " . $pass; + $res['email_error'] = "success"; + $subject = Config::get('appName') . "-新用户注册通知"; $to = $user->email; - $text = "您好,管理员已经为您生成账户,用户名: ".$email.",登录密码为:". $pass.",感谢您的支持。 " ; + $text = "您好,管理员已经为您生成账户,用户名: " . $email . ",登录密码为:" . $pass . ",感谢您的支持。 "; try { Mail::send($to, $subject, 'newuser.tpl', [ - "user" => $user,"text" => $text + "user" => $user, "text" => $text ], [ ]); } catch (\Exception $e) { @@ -125,7 +127,9 @@ class UserController extends AdminController $res['msg'] = "未知错误"; return $response->getBody()->write(json_encode($res)); } - public function buy($request, $response, $args){ + + public function buy($request, $response, $args) + { #shop 信息可以通过 App\Controllers\UserController:shop 获得 # 需要shopId,disableothers,autorenew,userEmail @@ -133,9 +137,9 @@ class UserController extends AdminController $shop = Shop::where("id", $shopId)->where("status", 1)->first(); $disableothers = $request->getParam('disableothers'); $autorenew = $request->getParam('autorenew'); - $email=$request->getParam("userEmail"); - $user = User::where("email",'=', $email)->first(); - if ($user==null){ + $email = $request->getParam("userEmail"); + $user = User::where("email", '=', $email)->first(); + if ($user == null) { $result['ret'] = 0; $result['msg'] = "未找到该用户"; return $response->getBody()->write(json_encode($result)); @@ -176,41 +180,39 @@ class UserController extends AdminController public function search($request, $response, $args) { $pageNum = 1; - $text=$args["text"]; + $text = $args["text"]; if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } - $users = User::where("email", "LIKE", "%".$text."%")->orWhere("user_name", "LIKE", "%".$text."%")->orWhere("im_value", "LIKE", "%".$text."%")->orWhere("port", "LIKE", "%".$text."%")->orWhere("remark", "LIKE", "%".$text."%")->paginate(20, ['*'], 'page', $pageNum); - $users->setPath('/admin/user/search/'.$text); - + $users = User::where("email", "LIKE", "%" . $text . "%")->orWhere("user_name", "LIKE", "%" . $text . "%")->orWhere("im_value", "LIKE", "%" . $text . "%")->orWhere("port", "LIKE", "%" . $text . "%")->orWhere("remark", "LIKE", "%" . $text . "%")->paginate(20, ['*'], 'page', $pageNum); + $users->setPath('/admin/user/search/' . $text); //Ip::where("datetime","<",time()-90)->get()->delete(); - $total = Ip::where("datetime", ">=", time()-90)->orderBy('userid', 'desc')->get(); + $total = Ip::where("datetime", ">=", time() - 90)->orderBy('userid', 'desc')->get(); - $userip=array(); - $useripcount=array(); - $regloc=array(); + $userip = array(); + $useripcount = array(); + $regloc = array(); $iplocation = new QQWry(); foreach ($users as $user) { - $useripcount[$user->id]=0; - $userip[$user->id]=array(); + $useripcount[$user->id] = 0; + $userip[$user->id] = array(); - $location=$iplocation->getlocation($user->reg_ip); - $regloc[$user->id]=iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $location = $iplocation->getlocation($user->reg_ip); + $regloc[$user->id] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); } - foreach ($total as $single) { if (isset($useripcount[$single->userid])) { if (!isset($userip[$single->userid][$single->ip])) { - $useripcount[$single->userid]=$useripcount[$single->userid]+1; - $location=$iplocation->getlocation($single->ip); - $userip[$single->userid][$single->ip]=iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $useripcount[$single->userid] = $useripcount[$single->userid] + 1; + $location = $iplocation->getlocation($single->ip); + $userip[$single->userid][$single->ip] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); } } } @@ -222,42 +224,40 @@ class UserController extends AdminController public function sort($request, $response, $args) { $pageNum = 1; - $text=$args["text"]; - $asc=$args["asc"]; + $text = $args["text"]; + $asc = $args["asc"]; if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } - $users->setPath('/admin/user/sort/'.$text."/".$asc); - + $users->setPath('/admin/user/sort/' . $text . "/" . $asc); //Ip::where("datetime","<",time()-90)->get()->delete(); - $total = Ip::where("datetime", ">=", time()-90)->orderBy('userid', 'desc')->get(); + $total = Ip::where("datetime", ">=", time() - 90)->orderBy('userid', 'desc')->get(); - $userip=array(); - $useripcount=array(); - $regloc=array(); + $userip = array(); + $useripcount = array(); + $regloc = array(); $iplocation = new QQWry(); foreach ($users as $user) { - $useripcount[$user->id]=0; - $userip[$user->id]=array(); + $useripcount[$user->id] = 0; + $userip[$user->id] = array(); - $location=$iplocation->getlocation($user->reg_ip); - $regloc[$user->id]=iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $location = $iplocation->getlocation($user->reg_ip); + $regloc[$user->id] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); } - foreach ($total as $single) { if (isset($useripcount[$single->userid])) { if (!isset($userip[$single->userid][$single->ip])) { - $useripcount[$single->userid]=$useripcount[$single->userid]+1; - $location=$iplocation->getlocation($single->ip); - $userip[$single->userid][$single->ip]=iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); + $useripcount[$single->userid] = $useripcount[$single->userid] + 1; + $location = $iplocation->getlocation($single->ip); + $userip[$single->userid][$single->ip] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); } } } @@ -281,13 +281,13 @@ class UserController extends AdminController $id = $args['id']; $user = User::find($id); - $email1=$user->email; + $email1 = $user->email; - $user->email = $request->getParam('email'); + $user->email = $request->getParam('email'); - $email2=$request->getParam('email'); + $email2 = $request->getParam('email'); - $passwd=$request->getParam('passwd'); + $passwd = $request->getParam('passwd'); Radius::ChangeUserName($email1, $email2, $passwd); @@ -297,10 +297,10 @@ class UserController extends AdminController $user->clean_link(); } - $user->auto_reset_day = $request->getParam('auto_reset_day'); + $user->auto_reset_day = $request->getParam('auto_reset_day'); $user->auto_reset_bandwidth = $request->getParam('auto_reset_bandwidth'); $origin_port = $user->port; - $user->port = $request->getParam('port'); + $user->port = $request->getParam('port'); $relay_rules = Relay::where('user_id', $user->id)->where('port', $origin_port)->get(); foreach ($relay_rules as $rule) { @@ -348,7 +348,7 @@ class UserController extends AdminController $id = $request->getParam('id'); $user = User::find($id); - $email1=$user->email; + $email1 = $user->email; if (!$user->kill_user()) { $rs['ret'] = 0; @@ -392,8 +392,8 @@ class UserController extends AdminController return $response->getBody()->write(json_encode($rs)); } - public function ajax($request, $response, $args) - { + public function ajax($request, $response, $args) + { //得到排序的方式 $order = $request->getParam('order')[0]['dir']; //得到排序字段的下标 @@ -404,158 +404,153 @@ class UserController extends AdminController $limit_length = $request->getParam('length'); $search = $request->getParam('search')['value']; - if($order_field=='used_traffic'){ - $order_field='u + d'; - } - elseif($order_field=='enable_traffic'){ - $order_field='transfer_enable'; - } - elseif($order_field=='today_traffic'){ - $order_field='u +d - last_day_t'; - } + if ($order_field == 'used_traffic') { + $order_field = 'u + d'; + } elseif ($order_field == 'enable_traffic') { + $order_field = 'transfer_enable'; + } elseif ($order_field == 'today_traffic') { + $order_field = 'u +d - last_day_t'; + } - $users=array(); - $count_filtered=0; + $users = array(); + $count_filtered = 0; if ($search) { $users = User::where( - function ($query) use ($search) { - $query->where('id','LIKE',"%$search%") - ->orwhere('user_name','LIKE',"%$search%") - ->orwhere('email','LIKE',"%$search%") - ->orwhere('passwd','LIKE',"%$search%") - ->orwhere('port','LIKE',"%$search%") - ->orwhere('reg_date','LIKE',"%$search%") - ->orwhere('invite_num','LIKE',"%$search%") - ->orwhere('money','LIKE',"%$search%") - ->orwhere('ref_by','LIKE',"%$search%") - ->orwhere('method','LIKE',"%$search%") - ->orwhere('reg_ip','LIKE',"%$search%") - ->orwhere('node_speedlimit','LIKE',"%$search%") - ->orwhere('im_value','LIKE',"%$search%") - ->orwhere('class','LIKE',"%$search%") - ->orwhere('class_expire','LIKE',"%$search%") - ->orwhere('expire_in','LIKE',"%$search%") - ->orwhere('remark','LIKE',"%$search%") - ->orwhere('node_group','LIKE',"%$search%") - ->orwhere('auto_reset_day','LIKE',"%$search%") - ->orwhere('auto_reset_bandwidth','LIKE',"%$search%") - ->orwhere('protocol','LIKE',"%$search%") - ->orwhere('protocol_param','LIKE',"%$search%") - ->orwhere('obfs','LIKE',"%$search%") - ->orwhere('obfs_param','LIKE',"%$search%"); - } - ) - ->orderByRaw($order_field.' '.$order) + function ($query) use ($search) { + $query->where('id', 'LIKE', "%$search%") + ->orwhere('user_name', 'LIKE', "%$search%") + ->orwhere('email', 'LIKE', "%$search%") + ->orwhere('passwd', 'LIKE', "%$search%") + ->orwhere('port', 'LIKE', "%$search%") + ->orwhere('reg_date', 'LIKE', "%$search%") + ->orwhere('invite_num', 'LIKE', "%$search%") + ->orwhere('money', 'LIKE', "%$search%") + ->orwhere('ref_by', 'LIKE', "%$search%") + ->orwhere('method', 'LIKE', "%$search%") + ->orwhere('reg_ip', 'LIKE', "%$search%") + ->orwhere('node_speedlimit', 'LIKE', "%$search%") + ->orwhere('im_value', 'LIKE', "%$search%") + ->orwhere('class', 'LIKE', "%$search%") + ->orwhere('class_expire', 'LIKE', "%$search%") + ->orwhere('expire_in', 'LIKE', "%$search%") + ->orwhere('remark', 'LIKE', "%$search%") + ->orwhere('node_group', 'LIKE', "%$search%") + ->orwhere('auto_reset_day', 'LIKE', "%$search%") + ->orwhere('auto_reset_bandwidth', 'LIKE', "%$search%") + ->orwhere('protocol', 'LIKE', "%$search%") + ->orwhere('protocol_param', 'LIKE', "%$search%") + ->orwhere('obfs', 'LIKE', "%$search%") + ->orwhere('obfs_param', 'LIKE', "%$search%"); + } + ) + ->orderByRaw($order_field . ' ' . $order) ->skip($limit_start)->limit($limit_length) ->get(); $count_filtered = User::where( - function ($query)use($search) { - $query->where('id','LIKE',"%$search%") - ->orwhere('user_name','LIKE',"%$search%") - ->orwhere('email','LIKE',"%$search%") - ->orwhere('passwd','LIKE',"%$search%") - ->orwhere('port','LIKE',"%$search%") - ->orwhere('reg_date','LIKE',"%$search%") - ->orwhere('invite_num','LIKE',"%$search%") - ->orwhere('money','LIKE',"%$search%") - ->orwhere('ref_by','LIKE',"%$search%") - ->orwhere('method','LIKE',"%$search%") - ->orwhere('reg_ip','LIKE',"%$search%") - ->orwhere('node_speedlimit','LIKE',"%$search%") - ->orwhere('im_value','LIKE',"%$search%") - ->orwhere('class','LIKE',"%$search%") - ->orwhere('class_expire','LIKE',"%$search%") - ->orwhere('expire_in','LIKE',"%$search%") - ->orwhere('remark','LIKE',"%$search%") - ->orwhere('node_group','LIKE',"%$search%") - ->orwhere('auto_reset_day','LIKE',"%$search%") - ->orwhere('auto_reset_bandwidth','LIKE',"%$search%") - ->orwhere('protocol','LIKE',"%$search%") - ->orwhere('protocol_param','LIKE',"%$search%") - ->orwhere('obfs','LIKE',"%$search%") - ->orwhere('obfs_param','LIKE',"%$search%"); - } - )->count(); - } - else{ - $users = User::orderByRaw($order_field.' '.$order) - ->skip($limit_start)->limit($limit_length) - ->get(); + function ($query) use ($search) { + $query->where('id', 'LIKE', "%$search%") + ->orwhere('user_name', 'LIKE', "%$search%") + ->orwhere('email', 'LIKE', "%$search%") + ->orwhere('passwd', 'LIKE', "%$search%") + ->orwhere('port', 'LIKE', "%$search%") + ->orwhere('reg_date', 'LIKE', "%$search%") + ->orwhere('invite_num', 'LIKE', "%$search%") + ->orwhere('money', 'LIKE', "%$search%") + ->orwhere('ref_by', 'LIKE', "%$search%") + ->orwhere('method', 'LIKE', "%$search%") + ->orwhere('reg_ip', 'LIKE', "%$search%") + ->orwhere('node_speedlimit', 'LIKE', "%$search%") + ->orwhere('im_value', 'LIKE', "%$search%") + ->orwhere('class', 'LIKE', "%$search%") + ->orwhere('class_expire', 'LIKE', "%$search%") + ->orwhere('expire_in', 'LIKE', "%$search%") + ->orwhere('remark', 'LIKE', "%$search%") + ->orwhere('node_group', 'LIKE', "%$search%") + ->orwhere('auto_reset_day', 'LIKE', "%$search%") + ->orwhere('auto_reset_bandwidth', 'LIKE', "%$search%") + ->orwhere('protocol', 'LIKE', "%$search%") + ->orwhere('protocol_param', 'LIKE', "%$search%") + ->orwhere('obfs', 'LIKE', "%$search%") + ->orwhere('obfs_param', 'LIKE', "%$search%"); + } + )->count(); + } else { + $users = User::orderByRaw($order_field . ' ' . $order) + ->skip($limit_start)->limit($limit_length) + ->get(); $count_filtered = User::count(); } - $data=array(); - foreach ($users as $user) { - $tempdata=array(); - //model里是casts所以没法直接 $tempdata=(array)$user - $tempdata['op']='编辑 - 删除 - 切换为该用户';; - $tempdata['id']=$user->id; - $tempdata['user_name']=$user->user_name; - $tempdata['remark']=$user->remark; - $tempdata['email']=$user->email; - $tempdata['money']=$user->money; - $tempdata['im_value']=$user->im_value; - switch($user->im_type) { - case 1: - $tempdata['im_type'] = '微信'; - break; - case 2: - $tempdata['im_type'] = 'QQ'; - break; - case 3: - $tempdata['im_type'] = 'Google+'; - break; - default: - $tempdata['im_type'] = 'Telegram'; - $tempdata['im_value'] = ''.$user->im_value.''; - } - $tempdata['node_group']=$user->node_group; - $tempdata['expire_in']=$user->expire_in; - $tempdata['class']=$user->class; - $tempdata['class_expire']=$user->class_expire; - $tempdata['passwd']=$user->passwd; - $tempdata['port']=$user->port; - $tempdata['method']=$user->method; - $tempdata['protocol']=$user->protocol; - $tempdata['obfs']=$user->obfs; - $tempdata['online_ip_count']=$user->online_ip_count(); - $tempdata['last_ss_time']=$user->lastSsTime(); - $tempdata['used_traffic']=Tools::flowToGB($user->u + $user->d); - $tempdata['enable_traffic']=Tools::flowToGB($user->transfer_enable); - $tempdata['last_checkin_time']=$user->lastCheckInTime(); - $tempdata['today_traffic']=Tools::flowToMB($user->u + $user->d-$user->last_day_t); - $tempdata['enable']=$user->enable == 1 ? "可用" : "禁用"; - $tempdata['reg_date']=$user->reg_date; - $tempdata['reg_ip']=$user->reg_ip; - $tempdata['auto_reset_day']=$user->auto_reset_day; - $tempdata['auto_reset_bandwidth']=$user->auto_reset_bandwidth; - $tempdata['ref_by']= $user->ref_by; - if ($user->ref_by == 0) { - $tempdata['ref_by_user_name'] = "系统邀请"; - } - else { - $ref_user = User::find($user->ref_by); - if ($ref_user == null) { - $tempdata['ref_by_user_name'] = "邀请人已经被删除"; - } - else { - $tempdata['ref_by_user_name'] = $ref_user->user_name; - } - } - - $tempdata['top_up']=$user->get_top_up(); - - array_push($data,$tempdata); - } + $data = array(); + foreach ($users as $user) { + $tempdata = array(); + //model里是casts所以没法直接 $tempdata=(array)$user + $tempdata['op'] = '编辑 + 删除 + 切换为该用户';; + $tempdata['id'] = $user->id; + $tempdata['user_name'] = $user->user_name; + $tempdata['remark'] = $user->remark; + $tempdata['email'] = $user->email; + $tempdata['money'] = $user->money; + $tempdata['im_value'] = $user->im_value; + switch ($user->im_type) { + case 1: + $tempdata['im_type'] = '微信'; + break; + case 2: + $tempdata['im_type'] = 'QQ'; + break; + case 3: + $tempdata['im_type'] = 'Google+'; + break; + default: + $tempdata['im_type'] = 'Telegram'; + $tempdata['im_value'] = '' . $user->im_value . ''; + } + $tempdata['node_group'] = $user->node_group; + $tempdata['expire_in'] = $user->expire_in; + $tempdata['class'] = $user->class; + $tempdata['class_expire'] = $user->class_expire; + $tempdata['passwd'] = $user->passwd; + $tempdata['port'] = $user->port; + $tempdata['method'] = $user->method; + $tempdata['protocol'] = $user->protocol; + $tempdata['obfs'] = $user->obfs; + $tempdata['online_ip_count'] = $user->online_ip_count(); + $tempdata['last_ss_time'] = $user->lastSsTime(); + $tempdata['used_traffic'] = Tools::flowToGB($user->u + $user->d); + $tempdata['enable_traffic'] = Tools::flowToGB($user->transfer_enable); + $tempdata['last_checkin_time'] = $user->lastCheckInTime(); + $tempdata['today_traffic'] = Tools::flowToMB($user->u + $user->d - $user->last_day_t); + $tempdata['enable'] = $user->enable == 1 ? "可用" : "禁用"; + $tempdata['reg_date'] = $user->reg_date; + $tempdata['reg_ip'] = $user->reg_ip; + $tempdata['auto_reset_day'] = $user->auto_reset_day; + $tempdata['auto_reset_bandwidth'] = $user->auto_reset_bandwidth; + $tempdata['ref_by'] = $user->ref_by; + if ($user->ref_by == 0) { + $tempdata['ref_by_user_name'] = "系统邀请"; + } else { + $ref_user = User::find($user->ref_by); + if ($ref_user == null) { + $tempdata['ref_by_user_name'] = "邀请人已经被删除"; + } else { + $tempdata['ref_by_user_name'] = $ref_user->user_name; + } + } + + $tempdata['top_up'] = $user->get_top_up(); + + array_push($data, $tempdata); + } $info = [ - 'draw'=> $request->getParam('draw'), // ajax请求次数,作为标识符 - 'recordsTotal'=>User::count(), - 'recordsFiltered'=>$count_filtered, - 'data'=>$data, + 'draw' => $request->getParam('draw'), // ajax请求次数,作为标识符 + 'recordsTotal' => User::count(), + 'recordsFiltered' => $count_filtered, + 'data' => $data, ]; - return json_encode($info,true); - } + return json_encode($info, true); + } } diff --git a/app/Controllers/AdminController.php b/app/Controllers/AdminController.php index 563d9fa8..884f94d3 100644 --- a/app/Controllers/AdminController.php +++ b/app/Controllers/AdminController.php @@ -52,10 +52,10 @@ class AdminController extends UserController public function invite($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", - "total" => "原始金额", "event_user_id" => "发起用户ID", - "event_user_name" => "发起用户名", "ref_user_id" => "获利用户ID", - "ref_user_name" => "获利用户名", "ref_get" => "获利金额", - "datetime" => "时间"); + "total" => "原始金额", "event_user_id" => "发起用户ID", + "event_user_name" => "发起用户名", "ref_user_id" => "获利用户ID", + "ref_user_name" => "获利用户名", "ref_get" => "获利金额", + "datetime" => "时间"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -63,36 +63,36 @@ class AdminController extends UserController $table_config['ajax_url'] = 'payback/ajax'; return $this->view()->assign('table_config', $table_config)->display('admin/invite.tpl'); } - + public function addInvite($request, $response, $args) { $num = $request->getParam('num'); $prefix = $request->getParam('prefix'); - if(Tools::isInt($num)==false){ - $res['ret'] = 0; + if (Tools::isInt($num) == false) { + $res['ret'] = 0; $res['msg'] = "非法请求"; return $response->getBody()->write(json_encode($res)); - } + } - if ($request->getParam('uid')!="0") { - if (strpos($request->getParam('uid'), "@")!=false) { - $user=User::where("email", "=", $request->getParam('uid'))->first(); + if ($request->getParam('uid') != "0") { + if (strpos($request->getParam('uid'), "@") != false) { + $user = User::where("email", "=", $request->getParam('uid'))->first(); } else { - $user=User::Where("id", "=", $request->getParam('uid'))->first(); + $user = User::Where("id", "=", $request->getParam('uid'))->first(); } - if ($user==null) { + if ($user == null) { $res['ret'] = 0; $res['msg'] = "邀请次数添加失败,检查用户id或者用户邮箱是否输入正确"; return $response->getBody()->write(json_encode($res)); } $uid = $user->id; } else { - $uid=0; + $uid = 0; } - $user->invite_num += $num; - $user->save(); + $user->invite_num += $num; + $user->save(); $res['ret'] = 1; $res['msg'] = "邀请次数添加成功"; return $response->getBody()->write(json_encode($res)); @@ -102,8 +102,8 @@ class AdminController extends UserController public function coupon($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", "code" => "优惠码", - "expire" => "过期时间", "shop" => "限定商品ID", - "credit" => "额度", "onetime" => "次数"); + "expire" => "过期时间", "shop" => "限定商品ID", + "credit" => "额度", "onetime" => "次数"); $table_config['default_show_column'] = array(); foreach ($table_config['total_column'] as $column => $value) { array_push($table_config['default_show_column'], $column); @@ -115,43 +115,41 @@ class AdminController extends UserController public function addCoupon($request, $response, $args) { $code = new Coupon(); - $code->onetime=$request->getParam('onetime'); - $generate_type=$request->getParam('generate_type'); - $final_code=$request->getParam('prefix'); - - if(empty($final_code)&&($generate_type==1||$generate_type==3)){ - $res['ret'] = 0; - $res['msg'] = "优惠码不能为空"; - return $response->getBody()->write(json_encode($res)); - } - - if($generate_type==1){ - if(Coupon::where('code',$final_code)->count()!=0){ - $res['ret'] = 0; - $res['msg'] = "优惠码已存在"; - return $response->getBody()->write(json_encode($res)); - } - } - else{ - while(true){ - if($generate_type==2){ - $temp_code=Tools::genRandomChar(8); - } - elseif($generate_type==3){ - $temp_code=$final_code.Tools::genRandomChar(8); - } - - if(Coupon::where('code',$temp_code)->count()==0){ - $final_code=$temp_code; - break; - } - } - } + $code->onetime = $request->getParam('onetime'); + $generate_type = $request->getParam('generate_type'); + $final_code = $request->getParam('prefix'); + + if (empty($final_code) && ($generate_type == 1 || $generate_type == 3)) { + $res['ret'] = 0; + $res['msg'] = "优惠码不能为空"; + return $response->getBody()->write(json_encode($res)); + } + + if ($generate_type == 1) { + if (Coupon::where('code', $final_code)->count() != 0) { + $res['ret'] = 0; + $res['msg'] = "优惠码已存在"; + return $response->getBody()->write(json_encode($res)); + } + } else { + while (true) { + if ($generate_type == 2) { + $temp_code = Tools::genRandomChar(8); + } elseif ($generate_type == 3) { + $temp_code = $final_code . Tools::genRandomChar(8); + } + + if (Coupon::where('code', $temp_code)->count() == 0) { + $final_code = $temp_code; + break; + } + } + } $code->code = $final_code; - $code->expire=time()+$request->getParam('expire')*3600; - $code->shop=$request->getParam('shop'); - $code->credit=$request->getParam('credit'); + $code->expire = time() + $request->getParam('expire') * 3600; + $code->shop = $request->getParam('shop'); + $code->credit = $request->getParam('credit'); $code->save(); @@ -163,14 +161,14 @@ class AdminController extends UserController public function trafficLog($request, $response, $args) { $table_config['total_column'] = array("id" => "ID", "user_id" => "用户ID", - "user_name" => "用户名", "node_name" => "使用节点", - "rate" => "倍率", "origin_traffic" => "实际使用流量", - "traffic" => "结算流量", - "log_time" => "记录时间"); + "user_name" => "用户名", "node_name" => "使用节点", + "rate" => "倍率", "origin_traffic" => "实际使用流量", + "traffic" => "结算流量", + "log_time" => "记录时间"); $table_config['default_show_column'] = array("id", "user_id", - "user_name", "node_name", - "rate", "origin_traffic", - "traffic", "log_time"); + "user_name", "node_name", + "rate", "origin_traffic", + "traffic", "log_time"); $table_config['ajax_url'] = 'trafficlog/ajax'; return $this->view()->assign('table_config', $table_config)->display('admin/trafficlog.tpl'); } diff --git a/app/Controllers/ApiController.php b/app/Controllers/ApiController.php index 48795909..aeca5173 100644 --- a/app/Controllers/ApiController.php +++ b/app/Controllers/ApiController.php @@ -14,7 +14,6 @@ use App\Utils\Helper; /** * ApiController */ - class ApiController extends BaseController { public function index() @@ -26,7 +25,7 @@ class ApiController extends BaseController $accessToken = $id = $args['token']; $storage = Factory::createTokenStorage(); $token = $storage->get($accessToken); - if ($token==null) { + if ($token == null) { $res['ret'] = 0; $res['msg'] = "token is null"; return $this->echoJson($response, $res); @@ -40,8 +39,8 @@ class ApiController extends BaseController public function newToken($request, $response, $args) { // $data = $request->post('sdf'); - $email = $request->getParam('email'); - + $email = $request->getParam('email'); + $email = strtolower($email); $passwd = $request->getParam('passwd'); @@ -61,7 +60,7 @@ class ApiController extends BaseController } $tokenStr = Tools::genToken(); $storage = Factory::createTokenStorage(); - $expireTime = time() + 3600*24*7; + $expireTime = time() + 3600 * 24 * 7; if ($storage->store($tokenStr, $user, $expireTime)) { $res['ret'] = 1; $res['msg'] = "ok"; @@ -86,56 +85,56 @@ class ApiController extends BaseController ->orWhere("node_group", "=", 0); } )->orderBy("name")->get(); - + $mu_nodes = Node::where('sort', 9)->where('node_class', '<=', $user->class)->where("type", "1")->where( function ($query) use ($user) { $query->where("node_group", "=", $user->node_group) ->orWhere("node_group", "=", 0); } )->orderBy("name")->get(); - - $temparray=array(); + + $temparray = array(); foreach ($nodes as $node) { if ($node->mu_only == 0) { - array_push($temparray, array("remarks"=>$node->name, - "server"=>$node->server, - "server_port"=>$user->port, - "method"=>($node->custom_method==1?$user->method:$node->method), - "obfs"=>str_replace("_compatible", "", (($node->custom_rss==1&&!($user->obfs=='plain'&&$user->protocol=='origin'))?$user->obfs:"plain")), - "obfsparam"=>(($node->custom_rss==1&&!($user->obfs=='plain'&&$user->protocol=='origin'))?$user->obfs_param:""), - "remarks_base64"=>base64_encode($node->name), - "password"=>$user->passwd, - "tcp_over_udp"=>false, - "udp_over_tcp"=>false, - "group"=>Config::get('appName'), - "protocol"=>str_replace("_compatible", "", (($node->custom_rss==1&&!($user->obfs=='plain'&&$user->protocol=='origin'))?$user->protocol:"origin")), - "obfs_udp"=>false, - "enable"=>true)); + array_push($temparray, array("remarks" => $node->name, + "server" => $node->server, + "server_port" => $user->port, + "method" => ($node->custom_method == 1 ? $user->method : $node->method), + "obfs" => str_replace("_compatible", "", (($node->custom_rss == 1 && !($user->obfs == 'plain' && $user->protocol == 'origin')) ? $user->obfs : "plain")), + "obfsparam" => (($node->custom_rss == 1 && !($user->obfs == 'plain' && $user->protocol == 'origin')) ? $user->obfs_param : ""), + "remarks_base64" => base64_encode($node->name), + "password" => $user->passwd, + "tcp_over_udp" => false, + "udp_over_tcp" => false, + "group" => Config::get('appName'), + "protocol" => str_replace("_compatible", "", (($node->custom_rss == 1 && !($user->obfs == 'plain' && $user->protocol == 'origin')) ? $user->protocol : "origin")), + "obfs_udp" => false, + "enable" => true)); } - + if ($node->custom_rss == 1) { foreach ($mu_nodes as $mu_node) { $mu_user = User::where('port', '=', $mu_node->server)->first(); $mu_user->obfs_param = $user->getMuMd5(); - - array_push($temparray, array("remarks"=>$node->name."- ".$mu_node->server." 单端口", - "server"=>$node->server, - "server_port"=>$mu_user->port, - "method"=>$mu_user->method, - "group"=>Config::get('appName'), - "obfs"=>str_replace("_compatible", "", (($node->custom_rss==1&&!($mu_user->obfs=='plain'&&$mu_user->protocol=='origin'))?$mu_user->obfs:"plain")), - "obfsparam"=>(($node->custom_rss==1&&!($mu_user->obfs=='plain'&&$mu_user->protocol=='origin'))?$mu_user->obfs_param:""), - "remarks_base64"=>base64_encode($node->name."- ".$mu_node->server." 单端口"), - "password"=>$mu_user->passwd, - "tcp_over_udp"=>false, - "udp_over_tcp"=>false, - "protocol"=>str_replace("_compatible", "", (($node->custom_rss==1&&!($mu_user->obfs=='plain'&&$mu_user->protocol=='origin'))?$mu_user->protocol:"origin")), - "obfs_udp"=>false, - "enable"=>true)); + + array_push($temparray, array("remarks" => $node->name . "- " . $mu_node->server . " 单端口", + "server" => $node->server, + "server_port" => $mu_user->port, + "method" => $mu_user->method, + "group" => Config::get('appName'), + "obfs" => str_replace("_compatible", "", (($node->custom_rss == 1 && !($mu_user->obfs == 'plain' && $mu_user->protocol == 'origin')) ? $mu_user->obfs : "plain")), + "obfsparam" => (($node->custom_rss == 1 && !($mu_user->obfs == 'plain' && $mu_user->protocol == 'origin')) ? $mu_user->obfs_param : ""), + "remarks_base64" => base64_encode($node->name . "- " . $mu_node->server . " 单端口"), + "password" => $mu_user->passwd, + "tcp_over_udp" => false, + "udp_over_tcp" => false, + "protocol" => str_replace("_compatible", "", (($node->custom_rss == 1 && !($mu_user->obfs == 'plain' && $mu_user->protocol == 'origin')) ? $mu_user->protocol : "origin")), + "obfs_udp" => false, + "enable" => true)); } } } - + $res['ret'] = 1; $res['msg'] = "ok"; $res['data'] = $temparray; diff --git a/app/Controllers/BaseController.php b/app/Controllers/BaseController.php index 2044598d..6d682bc6 100644 --- a/app/Controllers/BaseController.php +++ b/app/Controllers/BaseController.php @@ -8,13 +8,12 @@ use App\Services\View; /** * BaseController */ - class BaseController { public $view; public $smarty; - + public function construct__() { } diff --git a/app/Controllers/Client/ClientApiController.php b/app/Controllers/Client/ClientApiController.php index 6fe4e29e..917108f5 100644 --- a/app/Controllers/Client/ClientApiController.php +++ b/app/Controllers/Client/ClientApiController.php @@ -33,20 +33,21 @@ class ClientApiController extends BaseController return $this->echoJson($response, $res); } - public function Redirect($request, $response, $args){ + public function Redirect($request, $response, $args) + { $user = Auth::getUser(); $url = $request->getQueryParams()["target"]; - if(!$user->isLogin){ + if (!$user->isLogin) { $accessToken = Helper::getTokenFromReq($request); $storage = Factory::createTokenStorage(); $token = $storage->get($accessToken); - if ($token==null) { + if ($token == null) { $res['ret'] = 0; $res['msg'] = "token is null"; return $this->echoJson($response, $res); } $user = User::find($token->userId); - $time = 3600*24; + $time = 3600 * 24; Auth::login($user->id, $time); } return $response->withRedirect($url); @@ -60,12 +61,12 @@ class ClientApiController extends BaseController $user = User::find($token->userId); $ssr_sub_token = LinkController::GenerateSSRSubCode($user->id, 0); $mu = 0; - if($request->getQueryParams()["mu"]!=""){ + if ($request->getQueryParams()["mu"] != "") { $mu = $request->getQueryParams()["mu"]; } $res['ret'] = 1; $res['msg'] = "ok"; - $res['data'] = Config::get('subUrl').$ssr_sub_token.'?mu='.$mu; + $res['data'] = Config::get('subUrl') . $ssr_sub_token . '?mu=' . $mu; return $this->echoJson($response, $res); } } diff --git a/app/Controllers/HomeController.php b/app/Controllers/HomeController.php index 5326fa33..92cfecfe 100644 --- a/app/Controllers/HomeController.php +++ b/app/Controllers/HomeController.php @@ -30,14 +30,13 @@ class HomeController extends BaseController { $GtSdk = null; $recaptcha_sitekey = null; - if (Config::get('captcha_provider') != ''){ - switch(Config::get('captcha_provider')) - { + if (Config::get('captcha_provider') != '') { + switch (Config::get('captcha_provider')) { case 'recaptcha': $recaptcha_sitekey = Config::get('recaptcha_sitekey'); break; case 'geetest': - $uid = time().rand(1, 10000) ; + $uid = time() . rand(1, 10000); $GtSdk = Geetest::get($uid); break; } @@ -84,39 +83,39 @@ class HomeController extends BaseController { return $this->view()->display('tos.tpl'); } - + public function staff() { return $this->view()->display('staff.tpl'); } - + public function telegram($request, $response, $args) { $token = ""; if (isset($request->getQueryParams()["token"])) { $token = $request->getQueryParams()["token"]; } - + if ($token == Config::get('telegram_request_token')) { TelegramProcess::process(); } else { echo("不正确请求!"); } } - + public function page404($request, $response, $args) { return $this->view()->display('404.tpl'); } - + public function page405($request, $response, $args) { return $this->view()->display('405.tpl'); } - + public function page500($request, $response, $args) { - return $this->view()->display('500.tpl'); + return $this->view()->display('500.tpl'); } public function getOrderList($request, $response, $args) diff --git a/app/Controllers/LinkController.php b/app/Controllers/LinkController.php index dad94269..0d63c4a0 100644 --- a/app/Controllers/LinkController.php +++ b/app/Controllers/LinkController.php @@ -25,7 +25,7 @@ class LinkController extends BaseController public static function GenerateRandomLink() { - $i =0; + $i = 0; for ($i = 0; $i < 10; $i++) { $token = Tools::genRandomChar(16); $Elink = Link::where("token", "=", $token)->first(); @@ -67,21 +67,21 @@ class LinkController extends BaseController return null; } - if($Elink->type!=11){ - return null; - } - - $user=User::where("id", $Elink->userid)->first(); + if ($Elink->type != 11) { + return null; + } + + $user = User::where("id", $Elink->userid)->first(); if ($user == null) { return null; } $mu = 0; - if (isset($request->getQueryParams()["mu"])) { - $mu = (int)$request->getQueryParams()["mu"]; + if (isset($request->getQueryParams()["mu"])) { + $mu = (int)$request->getQueryParams()["mu"]; } - $newResponse = $response->withHeader('Content-type', ' application/octet-stream; charset=utf-8')->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate')->withHeader('Content-Disposition', ' attachment; filename='.$token.'.txt'); + $newResponse = $response->withHeader('Content-type', ' application/octet-stream; charset=utf-8')->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate')->withHeader('Content-Disposition', ' attachment; filename=' . $token . '.txt'); $newResponse->getBody()->write(LinkController::GetSSRSub(User::where("id", "=", $Elink->userid)->first(), $mu)); return $newResponse; } @@ -92,15 +92,13 @@ class LinkController extends BaseController public static function GetSSRSub($user, $mu = 0) { - if ($mu==0||$mu==1) { + if ($mu == 0 || $mu == 1) { return Tools::base64_url_encode(URL::getAllUrl($user, $mu, 0)); - } - elseif ($mu == LinkController::V2RYA_MU){ + } elseif ($mu == LinkController::V2RYA_MU) { return Tools::base64_url_encode(URL::getAllVMessUrl($user)); - } - elseif ($mu==LinkController::SSD_MU) { - return URL::getAllSSDUrl($user); - } elseif ($mu==LinkController::CLASH_MU) { + } elseif ($mu == LinkController::SSD_MU) { + return URL::getAllSSDUrl($user); + } elseif ($mu == LinkController::CLASH_MU) { // Clash return LinkController::GetClash($user); } @@ -184,10 +182,10 @@ class LinkController extends BaseController } $render = ConfRender::getTemplateRender(); $render->assign('user', $user) - ->assign('confs', $confs) - ->assign('proxies', array_map(function ($conf) { - return $conf['name']; - }, $proxy_confs)); + ->assign('confs', $confs) + ->assign('proxies', array_map(function ($conf) { + return $conf['name']; + }, $proxy_confs)); return $render->fetch('clash.tpl'); } diff --git a/app/Controllers/Mod_Mu/FuncController.php b/app/Controllers/Mod_Mu/FuncController.php index 7f4e26d9..48482a8a 100644 --- a/app/Controllers/Mod_Mu/FuncController.php +++ b/app/Controllers/Mod_Mu/FuncController.php @@ -33,7 +33,9 @@ class FuncController extends BaseController ]; return $this->echoJson($response, $res); } - public function get_dis_node_info($nodeid){ + + public function get_dis_node_info($nodeid) + { $node = Node::where("id", $nodeid)->first(); if ($node == null) { return null; @@ -46,28 +48,28 @@ class FuncController extends BaseController { $params = $request->getQueryParams(); $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; - }else{ - $node = Node::where("id",$node_id)->first(); + } else { + $node = Node::where("id", $node_id)->first(); } $rules = Relay::Where('source_node_id', $node_id)->get(); - if (count($rules)>0){ + if (count($rules) > 0) { if ($rules[0]['dist_node_id'] == -1) { - $server= null; + $server = null; } - foreach ($rules as $rule){ + foreach ($rules as $rule) { $dis = $this->get_dis_node_info($rule['dist_node_id']); - if ($dis!=null){ + if ($dis != null) { $rule['source_node_sort'] = $node->sort; - $rule["dist_node_sort"]= $dis->sort; + $rule["dist_node_sort"] = $dis->sort; $rule['dist_node_server'] = $dis->server; - }else{ - $rule['source_node_sort'] =$node->sort; - $rule["dist_node_sort"]= null; + } else { + $rule['source_node_sort'] = $node->sort; + $rule["dist_node_sort"] = null; $rule['dist_node_server'] = null; } @@ -76,7 +78,7 @@ class FuncController extends BaseController "ret" => 1, "data" => $rules, ]; - }else{ + } else { $res = [ "ret" => 1, "data" => array(), @@ -114,10 +116,10 @@ class FuncController extends BaseController $data = $request->getParam('data'); $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { $res = [ @@ -157,10 +159,10 @@ class FuncController extends BaseController $data = $request->getParam('data'); $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { $res = [ @@ -202,10 +204,10 @@ class FuncController extends BaseController $params = $request->getQueryParams(); $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { $res = [ @@ -219,7 +221,7 @@ class FuncController extends BaseController $autos = array(); foreach ($autos_raw as $auto_raw) { - $has_exec = Auto::where('sign', $node_id.'-'.$auto_raw->id)->where('type', '2')->first(); + $has_exec = Auto::where('sign', $node_id . '-' . $auto_raw->id)->where('type', '2')->first(); if ($has_exec == null) { array_push($autos, $auto_raw); } @@ -238,10 +240,10 @@ class FuncController extends BaseController $data = $request->getParam('data'); $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { $res = [ diff --git a/app/Controllers/Mod_Mu/NodeController.php b/app/Controllers/Mod_Mu/NodeController.php index 92ddfedc..7dd8dbdf 100644 --- a/app/Controllers/Mod_Mu/NodeController.php +++ b/app/Controllers/Mod_Mu/NodeController.php @@ -13,10 +13,10 @@ class NodeController extends BaseController public function info($request, $response, $args) { $node_id = $args['id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $load = $request->getParam('load'); $uptime = $request->getParam('uptime'); $log = new NodeInfoLog(); @@ -41,10 +41,10 @@ class NodeController extends BaseController public function get_info($request, $response, $args) { $node_id = $args['id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id = $node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { $res = [ diff --git a/app/Controllers/Mod_Mu/UserController.php b/app/Controllers/Mod_Mu/UserController.php index 9c78fa0d..4a7228f9 100644 --- a/app/Controllers/Mod_Mu/UserController.php +++ b/app/Controllers/Mod_Mu/UserController.php @@ -19,49 +19,48 @@ class UserController extends BaseController $params = $request->getQueryParams(); $node_id = $params['node_id']; - $node=new Node(); - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } - else{ - $node = Node::where("id", "=", $node_id)->first(); - if ($node == null) { - $res = [ - "ret" => 0 - ]; - return $this->echoJson($response, $res); - } - } - $node->node_heartbeat=time(); + $node = new Node(); + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } else { + $node = Node::where("id", "=", $node_id)->first(); + if ($node == null) { + $res = [ + "ret" => 0 + ]; + return $this->echoJson($response, $res); + } + } + $node->node_heartbeat = time(); $node->save(); - if ($node->node_group!=0) { + if ($node->node_group != 0) { $users_raw = User::where( - function ($query) use ($node){ + function ($query) use ($node) { $query->where( - function ($query1) use ($node){ - $query1->where("class", ">=", $node->node_class) - ->where("node_group", "=", $node->node_group); - } + function ($query1) use ($node) { + $query1->where("class", ">=", $node->node_class) + ->where("node_group", "=", $node->node_group); + } )->orwhere('is_admin', 1); } ) - ->where("enable", 1)->where("expire_in", ">", date("Y-m-d H:i:s"))->get(); + ->where("enable", 1)->where("expire_in", ">", date("Y-m-d H:i:s"))->get(); } else { $users_raw = User::where( - function ($query) use ($node){ + function ($query) use ($node) { $query->where( - function ($query1) use ($node){ - $query1->where("class", ">=", $node->node_class); - } + function ($query1) use ($node) { + $query1->where("class", ">=", $node->node_class); + } )->orwhere('is_admin', 1); } )->where("enable", 1)->where("expire_in", ">", date("Y-m-d H:i:s"))->get(); } - if ($node->node_bandwidth_limit!=0) { + if ($node->node_bandwidth_limit != 0) { if ($node->node_bandwidth_limit < $node->node_bandwidth) { - $users=null; + $users = null; $res = [ "ret" => 1, @@ -74,8 +73,8 @@ class UserController extends BaseController $users = array(); $key_list = array('email', 'method', 'obfs', 'obfs_param', 'protocol', 'protocol_param', - 'forbidden_ip', 'forbidden_port', 'node_speedlimit', 'disconnect_ip', - 'is_multi_user', 'id', 'port', 'passwd', 'u', 'd'); + 'forbidden_ip', 'forbidden_port', 'node_speedlimit', 'disconnect_ip', + 'is_multi_user', 'id', 'port', 'passwd', 'u', 'd'); foreach ($users_raw as $user_raw) { if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) { @@ -100,10 +99,10 @@ class UserController extends BaseController $data = $request->getParam('data'); $this_time_total_bandwidth = 0; $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { @@ -121,7 +120,7 @@ class UserController extends BaseController $user = User::find($user_id); - if($user == NULL) { + if ($user == NULL) { continue; } @@ -172,10 +171,10 @@ class UserController extends BaseController $data = $request->getParam('data'); $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { @@ -212,10 +211,10 @@ class UserController extends BaseController $data = $request->getParam('data'); $node_id = $params['node_id']; - if($node_id=='0'){ - $node = Node::where("node_ip",$_SERVER["REMOTE_ADDR"])->first(); - $node_id=$node->id; - } + if ($node_id == '0') { + $node = Node::where("node_ip", $_SERVER["REMOTE_ADDR"])->first(); + $node_id = $node->id; + } $node = Node::find($node_id); if ($node == null) { diff --git a/app/Controllers/Mu/NodeController.php b/app/Controllers/Mu/NodeController.php index 4d332b20..ed6d23cb 100644 --- a/app/Controllers/Mu/NodeController.php +++ b/app/Controllers/Mu/NodeController.php @@ -30,7 +30,7 @@ class NodeController extends BaseController ]; return $this->echoJson($response, $res); } - + public function info($request, $response, $args) { $node_id = $args['id']; diff --git a/app/Controllers/Mu/UserController.php b/app/Controllers/Mu/UserController.php index a71db1f2..7b1d1229 100644 --- a/app/Controllers/Mu/UserController.php +++ b/app/Controllers/Mu/UserController.php @@ -16,38 +16,38 @@ class UserController extends BaseController $node = Node::where("node_ip", "=", $_SERVER["REMOTE_ADDR"])->where( function ($query) { $query->where("sort", "=", 0) - ->orWhere("sort", "=", 10)->orWhere("sort","=",12); + ->orWhere("sort", "=", 10)->orWhere("sort", "=", 12); } )->first(); - $node->node_heartbeat=time(); + $node->node_heartbeat = time(); $node->save(); - if ($node->node_group!=0) { + if ($node->node_group != 0) { $users_raw = User::where( - function ($query) use ($node){ + function ($query) use ($node) { $query->where( - function ($query1) use ($node){ - $query1->where("class", ">=", $node->node_class) - ->where("node_group", "=", $node->node_group); - } + function ($query1) use ($node) { + $query1->where("class", ">=", $node->node_class) + ->where("node_group", "=", $node->node_group); + } )->orwhere('is_admin', 1); } ) - ->where("enable", 1)->where("expire_in", ">", date("Y-m-d H:i:s"))->get(); + ->where("enable", 1)->where("expire_in", ">", date("Y-m-d H:i:s"))->get(); } else { $users_raw = User::where( - function ($query) use ($node){ + function ($query) use ($node) { $query->where( - function ($query1) use ($node){ - $query1->where("class", ">=", $node->node_class); - } + function ($query1) use ($node) { + $query1->where("class", ">=", $node->node_class); + } )->orwhere('is_admin', 1); } )->where("enable", 1)->where("expire_in", ">", date("Y-m-d H:i:s"))->get(); } - if ($node->node_bandwidth_limit!=0) { - if ($node->node_bandwidth_limit<$node->node_bandwidth) { - $users=null; + if ($node->node_bandwidth_limit != 0) { + if ($node->node_bandwidth_limit < $node->node_bandwidth) { + $users = null; $res = [ "ret" => 1, @@ -58,7 +58,7 @@ class UserController extends BaseController } $key_list = array('method', 'id', 'port', 'passwd', 'u', 'd', 'enable', - 't', 'transfer_enable', 'switch', 'email'); + 't', 'transfer_enable', 'switch', 'email'); $users_output = array(); @@ -86,7 +86,7 @@ class UserController extends BaseController $nodeId = $request->getParam('node_id'); $node = Node::find($nodeId); - $node->node_bandwidth=$node->node_bandwidth+$d+$u; + $node->node_bandwidth = $node->node_bandwidth + $d + $u; $node->save(); diff --git a/app/Controllers/QuickPayFunction.php b/app/Controllers/QuickPayFunction.php index 99213993..763b2964 100644 --- a/app/Controllers/QuickPayFunction.php +++ b/app/Controllers/QuickPayFunction.php @@ -2,8 +2,10 @@ namespace App\Controllers; -class QuickPayFunction{ - public function md5Verify($p1, $p2,$p3,$p4,$sign) { +class QuickPayFunction +{ + public function md5Verify($p1, $p2, $p3, $p4, $sign) + { $preStr = $p1 . $p2 . $p3 . $p4 . "yft"; $mySign = md5($preStr); if ($mySign == $sign) { @@ -18,33 +20,36 @@ class QuickPayFunction{ * @param $para_temp 请求参数数组 * */ - public function buildRequestForm($para_temp,$ss_order_no,$pay_config) { + public function buildRequestForm($para_temp, $ss_order_no, $pay_config) + { //待请求参数数组 $para = QuickPayFunction::buildRequestPara($para_temp); $sHtml = "
"; - while (list ($key, $val) = each ($para)) { - $sHtml.= ""; + while (list ($key, $val) = each($para)) { + $sHtml .= ""; } - if ($pay_config->pay_config["type"] == "aliPay"){ + if ($pay_config->pay_config["type"] == "aliPay") { $sHtml .= ""; - }else{ - $sHtml .= ""; + } else { + $sHtml .= ""; } //submit按钮控件请不要含有name属性 - $sHtml = $sHtml."
"; + $sHtml = $sHtml . ""; - $sHtml = $sHtml.""; + $sHtml = $sHtml . ""; return $sHtml; } + /** * 生成要请求给云通付的参数数组 * @param $para_temp 请求前的参数数组 * @return 要请求的参数数组 */ - static function buildRequestPara($para_temp) { + static function buildRequestPara($para_temp) + { //除去待签名参数数组中的空值和签名参数 $para_filter = QuickPayFunction::paraFilter($para_temp); //生成签名结果 @@ -55,48 +60,58 @@ class QuickPayFunction{ return $para_filter; } + /** * 除去数组中的空值和签名参数 * @param $para 签名参数组 * return 去掉空值与签名参数后的新签名参数组 */ - static function paraFilter($para) { + static function paraFilter($para) + { $para_filter = array(); - while (list ($key, $val) = each ($para)) { - if($key == "sign" || $val == "")continue; - else $para_filter[$key] = $para[$key]; + while (list ($key, $val) = each($para)) { + if ($key == "sign" || $val == "") continue; + else $para_filter[$key] = $para[$key]; } return $para_filter; } + /** * 生成签名结果 * @param $para_filter 要签名的数组 * return 签名结果字符串 */ - static function buildRequestMysign($para_filter) { + static function buildRequestMysign($para_filter) + { //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 $prestr = QuickPayFunction::createLinkstring($para_filter); $mysign = MD5($prestr); return $mysign; } - static function md5Sign($prestr) { + + static function md5Sign($prestr) + { return md5($prestr); } + /** * 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 * @param $para 需要拼接的数组 * return 拼接完成以后的字符串 */ - static function createLinkstring($para) { - $arg = ""; - while (list ($key, $val) = each ($para)) { - $arg.=$key."=".$val."&"; + static function createLinkstring($para) + { + $arg = ""; + while (list ($key, $val) = each($para)) { + $arg .= $key . "=" . $val . "&"; } //去掉最后一个&字符 - $arg = substr($arg,0,count($arg)-2); + $arg = substr($arg, 0, count($arg) - 2); //如果存在转义字符,那么去掉转义 - if(get_magic_quotes_gpc()){$arg = stripslashes($arg);} + if (get_magic_quotes_gpc()) { + $arg = stripslashes($arg); + } return $arg; } diff --git a/app/Controllers/RelayController.php b/app/Controllers/RelayController.php index 14445ea7..1378ab33 100644 --- a/app/Controllers/RelayController.php +++ b/app/Controllers/RelayController.php @@ -36,7 +36,7 @@ class RelayController extends UserController $query->Where('sort', 10) ->orWhere('sort', 12); } - )->where("node_class", "<=", $user->class)->orderBy('name')->get(); + )->where("node_class", "<=", $user->class)->orderBy('name')->get(); $pathset = new \ArrayObject(); @@ -86,10 +86,10 @@ class RelayController extends UserController if ($single_path->end_node->id == $path->begin_node->id) { $path->begin_node = $single_path->begin_node; if ($path->begin_node->isNodeAccessable() == false) { - $path->path = ''.$single_path->begin_node->name.''." → ".$path->path; + $path->path = '' . $single_path->begin_node->name . '' . " → " . $path->path; $path->status = "阻断"; } else { - $path->path = $single_path->begin_node->name." → ".$path->path; + $path->path = $single_path->begin_node->name . " → " . $path->path; $path->status = "通畅"; } @@ -100,10 +100,10 @@ class RelayController extends UserController if ($path->end_node->id == $single_path->begin_node->id) { $path->end_node = $single_path->end_node; if ($single_path->end_node->isNodeAccessable() == false) { - $path->path = $path->path." → ".''.$single_path->end_node->name.''; + $path->path = $path->path . " → " . '' . $single_path->end_node->name . ''; $path->status = "阻断"; } else { - $path->path = $path->path." → ".$single_path->end_node->name; + $path->path = $path->path . " → " . $single_path->end_node->name; } $pathset->offsetUnset($index); @@ -124,15 +124,15 @@ class RelayController extends UserController $query->Where("node_group", "=", $user->node_group) ->orWhere("node_group", "=", 0); } - )->where('type', 1)->where( + )->where('type', 1)->where( function ($query) { $query->Where('sort', 10) ->orWhere('sort', 12); } - )->where("node_class", "<=", $user->class)->orderBy('name')->get(); - foreach($source_nodes as $node){ - if ($node->sort==12){ - $node->name = $node->name." 正在使用V2ray后端 "; + )->where("node_class", "<=", $user->class)->orderBy('name')->get(); + foreach ($source_nodes as $node) { + if ($node->sort == 12) { + $node->name = $node->name . " 正在使用V2ray后端 "; } } $dist_nodes = Node::where( @@ -164,13 +164,13 @@ class RelayController extends UserController } } - foreach ($dist_nodes as $node){ - if ($node->sort==11 or $node->sort==12){ + foreach ($dist_nodes as $node) { + if ($node->sort == 11 or $node->sort == 12) { $node_explode = Tools::ssv2Array($node->server); array_push($ports, $node_explode['port']); - $node->name = $node->name." 如果是V2ray后端 请设置成 ".$node_explode['port']; - }else { - $node->name = $node->name." 如果是V2ray后端 请设置成 ".$user->port; + $node->name = $node->name . " 如果是V2ray后端 请设置成 " . $node_explode['port']; + } else { + $node->name = $node->name . " 如果是V2ray后端 请设置成 " . $user->port; } } @@ -193,21 +193,21 @@ class RelayController extends UserController $query->Where("node_group", "=", $user->node_group) ->orWhere("node_group", "=", 0); } - )->where('type', 1)->where( + )->where('type', 1)->where( function ($query) { $query->Where('sort', 10) ->orWhere('sort', 12); } - )->where("node_class", "<=", $user->class)->first(); + )->where("node_class", "<=", $user->class)->first(); if ($source_node == null) { $rs['ret'] = 0; $rs['msg'] = "起源节点错误"; return $response->getBody()->write(json_encode($rs)); } - if ($source_node->sort==12){ + if ($source_node->sort == 12) { $rules = Relay::Where('source_node_id', $source_node_id)->get(); - foreach ($rules as $rule){ - if ($rule['user_id']==0 || $rule['user_id']=$user->id){ + foreach ($rules as $rule) { + if ($rule['user_id'] == 0 || $rule['user_id'] = $user->id) { $rs['ret'] = 0; $rs['msg'] = "v2ray中转一个起点一个rule"; return $response->getBody()->write(json_encode($rs)); @@ -247,12 +247,12 @@ class RelayController extends UserController ->orWhere("node_group", "=", 0); } )->where('type', 1)->where('sort', 9)->where("node_class", "<=", $user->class)->first(); - $v2ray_port_raw=""; - if ($dist_node->sort ==12 || $dist_node->sort==11) { + $v2ray_port_raw = ""; + if ($dist_node->sort == 12 || $dist_node->sort == 11) { $node_explode = Tools::ssv2Array($dist_node->server); $v2ray_port_raw = $node_explode['port']; } - if (($port_raw == null && $port != $user->port && $v2ray_port_raw=="")||($v2ray_port_raw!="" && ($port!=$user->port && $port!=$v2ray_port_raw))) { + if (($port_raw == null && $port != $user->port && $v2ray_port_raw == "") || ($v2ray_port_raw != "" && ($port != $user->port && $port != $v2ray_port_raw))) { $rs['ret'] = 0; $rs['msg'] = "端口错误"; return $response->getBody()->write(json_encode($rs)); @@ -279,7 +279,7 @@ class RelayController extends UserController $maybe_rule_id = Tools::has_conflict_rule($rule, $ruleset, 0, $rule->source_node_id); if ($maybe_rule_id != 0) { $rs['ret'] = 0; - $rs['msg'] = "您即将添加的规则与规则 ID:".$maybe_rule_id." 冲突!"; + $rs['msg'] = "您即将添加的规则与规则 ID:" . $maybe_rule_id . " 冲突!"; if ($maybe_rule_id == -1) { $rs['msg'] = "您即将添加的规则可能会造成冲突!"; } @@ -319,10 +319,10 @@ class RelayController extends UserController $query->Where('sort', 10) ->orWhere('sort', 12); } - )->where("node_class", "<=", $user->class)->orderBy('name')->get(); - foreach($source_nodes as $node){ - if ($node->sort==12){ - $node->name = $node->name." 正在使用V2ray后端 "; + )->where("node_class", "<=", $user->class)->orderBy('name')->get(); + foreach ($source_nodes as $node) { + if ($node->sort == 12) { + $node->name = $node->name . " 正在使用V2ray后端 "; } } $dist_nodes = Node::where( @@ -353,13 +353,13 @@ class RelayController extends UserController array_push($ports, $port_raw->server); } } - foreach ($dist_nodes as $node){ - if ($node->sort==11 or $node->sort==12){ + foreach ($dist_nodes as $node) { + if ($node->sort == 11 or $node->sort == 12) { $node_explode = Tools::ssv2Array($node->server); array_push($ports, $node_explode['port']); - $node->name = $node->name." 如果是V2ray后端 请设置成: ".$node_explode['port']; - }else { - $node->name = $node->name." 如果是V2ray后端 请设置成 ".$user->port; + $node->name = $node->name . " 如果是V2ray后端 请设置成: " . $node_explode['port']; + } else { + $node->name = $node->name . " 如果是V2ray后端 请设置成 " . $user->port; } } @@ -388,12 +388,12 @@ class RelayController extends UserController $query->Where("node_group", "=", $user->node_group) ->orWhere("node_group", "=", 0); } - )->where('type', 1)->where( + )->where('type', 1)->where( function ($query) { $query->Where('sort', 10) ->orWhere('sort', 12); } - )->where("node_class", "<=", $user->class)->first(); + )->where("node_class", "<=", $user->class)->first(); if ($source_node == null) { $rs['ret'] = 0; $rs['msg'] = "起源节点错误"; @@ -433,12 +433,12 @@ class RelayController extends UserController ->orWhere("node_group", "=", 0); } )->where('type', 1)->where('sort', 9)->where("node_class", "<=", $user->class)->first(); - $v2ray_port_raw=""; - if ($dist_node->sort ==12 || $dist_node->sort==11) { + $v2ray_port_raw = ""; + if ($dist_node->sort == 12 || $dist_node->sort == 11) { $node_explode = Tools::ssv2Array($dist_node->server); - $v2ray_port_raw= $node_explode['port']; + $v2ray_port_raw = $node_explode['port']; } - if (($port_raw == null && $port != $user->port && $v2ray_port_raw=="" )||($v2ray_port_raw!="" && ($port!=$user->port && $port!=$v2ray_port_raw))) { + if (($port_raw == null && $port != $user->port && $v2ray_port_raw == "") || ($v2ray_port_raw != "" && ($port != $user->port && $port != $v2ray_port_raw))) { $rs['ret'] = 0; $rs['msg'] = "端口错误"; return $response->getBody()->write(json_encode($rs)); @@ -464,7 +464,7 @@ class RelayController extends UserController $maybe_rule_id = Tools::has_conflict_rule($rule, $ruleset, $rule->id, $rule->source_node_id); if ($maybe_rule_id != 0) { $rs['ret'] = 0; - $rs['msg'] = "您即将添加的规则与规则 ID:".$maybe_rule_id." 冲突!"; + $rs['msg'] = "您即将添加的规则与规则 ID:" . $maybe_rule_id . " 冲突!"; if ($maybe_rule_id == -1) { $rs['msg'] = "您即将添加的规则可能会造成冲突!"; } diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index 13ce0f41..7a2b0887 100755 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -1210,7 +1210,7 @@ class UserController extends BaseController { $title = $request->getParam('title'); $content = $request->getParam('content'); - $markdown = $request->getParam('markdown'); + $markdown = $request->getParam('markdown'); if ($title == "" || $content == "") { $res['ret'] = 0; @@ -1234,40 +1234,40 @@ class UserController extends BaseController $ticket->datetime = time(); $ticket->save(); - if(Config::get('mail_ticket') == 'true' && $markdown !=''){ - $adminUser = User::where("is_admin", "=", "1")->get(); - foreach ($adminUser as $user) { - $subject = Config::get('appName') . "-新工单被开启"; - $to = $user->email; - $text = "管理员,有人开启了新的工单,请您及时处理。"; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user, "text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } - } - } - - if(Config::get('useScFtqq') == 'true' && $markdown !=''){ - $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); - $postdata = http_build_query( - array( - 'text' => Config::get('appName') . "-新工单被开启", - 'desp' => $markdown - )); - $opts = array('http' => - array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $postdata - )); - $context = stream_context_create($opts); - file_get_contents('https://sc.ftqq.com/'.$ScFtqq_SCKEY.'.send', false, $context); - } - + if (Config::get('mail_ticket') == 'true' && $markdown != '') { + $adminUser = User::where("is_admin", "=", "1")->get(); + foreach ($adminUser as $user) { + $subject = Config::get('appName') . "-新工单被开启"; + $to = $user->email; + $text = "管理员,有人开启了新的工单,请您及时处理。"; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + } + } + + if (Config::get('useScFtqq') == 'true' && $markdown != '') { + $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); + $postdata = http_build_query( + array( + 'text' => Config::get('appName') . "-新工单被开启", + 'desp' => $markdown + )); + $opts = array('http' => + array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $postdata + )); + $context = stream_context_create($opts); + file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context); + } + $res['ret'] = 1; $res['msg'] = "提交成功"; return $this->echoJson($response, $res); @@ -1278,7 +1278,7 @@ class UserController extends BaseController $id = $args['id']; $content = $request->getParam('content'); $status = $request->getParam('status'); - $markdown = $request->getParam('markdown'); + $markdown = $request->getParam('markdown'); if ($content == "" || $status == "") { $res['ret'] = 0; @@ -1300,72 +1300,72 @@ class UserController extends BaseController } if ($status == 1 && $ticket_main->status != $status) { - if(Config::get('mail_ticket') == 'true' && $markdown !=''){ - $adminUser = User::where("is_admin", "=", "1")->get(); - foreach ($adminUser as $user) { - $subject = Config::get('appName') . "-工单被重新开启"; - $to = $user->email; - $text = "管理员,有人重新开启了id . "/view\">工单,请您及时处理。"; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user, "text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } - } - } - if(Config::get('useScFtqq') == 'true' && $markdown !=''){ - $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); - $postdata = http_build_query( - array( - 'text' => Config::get('appName') . "-工单被重新开启", - 'desp' => $markdown - )); - $opts = array('http' => - array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $postdata - )); - $context = stream_context_create($opts); - file_get_contents('https://sc.ftqq.com/'.$ScFtqq_SCKEY.'.send', false, $context); - $useScFtqq = Config::get('ScFtqq_SCKEY'); - } + if (Config::get('mail_ticket') == 'true' && $markdown != '') { + $adminUser = User::where("is_admin", "=", "1")->get(); + foreach ($adminUser as $user) { + $subject = Config::get('appName') . "-工单被重新开启"; + $to = $user->email; + $text = "管理员,有人重新开启了id . "/view\">工单,请您及时处理。"; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + } + } + if (Config::get('useScFtqq') == 'true' && $markdown != '') { + $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); + $postdata = http_build_query( + array( + 'text' => Config::get('appName') . "-工单被重新开启", + 'desp' => $markdown + )); + $opts = array('http' => + array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $postdata + )); + $context = stream_context_create($opts); + file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context); + $useScFtqq = Config::get('ScFtqq_SCKEY'); + } } else { - if(Config::get('mail_ticket') == 'true' && $markdown !=''){ - $adminUser = User::where("is_admin", "=", "1")->get(); - foreach ($adminUser as $user) { - $subject = Config::get('appName') . "-工单被回复"; - $to = $user->email; - $text = "管理员,有人回复了id . "/view\">工单,请您及时处理。"; - try { - Mail::send($to, $subject, 'news/warn.tpl', [ - "user" => $user, "text" => $text - ], [ - ]); - } catch (\Exception $e) { - echo $e->getMessage(); - } - } - } - if(Config::get('useScFtqq') == 'true' && $markdown !=''){ - $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); - $postdata = http_build_query( - array( - 'text' => Config::get('appName') . "-工单被回复", - 'desp' => $markdown - )); - $opts = array('http' => - array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $postdata - )); - $context = stream_context_create($opts); - file_get_contents('https://sc.ftqq.com/'.$ScFtqq_SCKEY.'.send', false, $context); - } + if (Config::get('mail_ticket') == 'true' && $markdown != '') { + $adminUser = User::where("is_admin", "=", "1")->get(); + foreach ($adminUser as $user) { + $subject = Config::get('appName') . "-工单被回复"; + $to = $user->email; + $text = "管理员,有人回复了id . "/view\">工单,请您及时处理。"; + try { + Mail::send($to, $subject, 'news/warn.tpl', [ + "user" => $user, "text" => $text + ], [ + ]); + } catch (\Exception $e) { + echo $e->getMessage(); + } + } + } + if (Config::get('useScFtqq') == 'true' && $markdown != '') { + $ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY'); + $postdata = http_build_query( + array( + 'text' => Config::get('appName') . "-工单被回复", + 'desp' => $markdown + )); + $opts = array('http' => + array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $postdata + )); + $context = stream_context_create($opts); + file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context); + } } $antiXss = new AntiXSS(); diff --git a/app/Controllers/VueController.php b/app/Controllers/VueController.php index 03bb6c93..47e55972 100644 --- a/app/Controllers/VueController.php +++ b/app/Controllers/VueController.php @@ -387,7 +387,7 @@ class VueController extends BaseController } else { if ($node->sort == 13) { $server = Tools::ssv2Array($node->server); - $array_node['server']=$server['add']; + $array_node['server'] = $server['add']; } else { $array_node['server'] = $node->server; } diff --git a/app/Middleware/Admin.php b/app/Middleware/Admin.php index 976eaf05..df6efb7d 100644 --- a/app/Middleware/Admin.php +++ b/app/Middleware/Admin.php @@ -22,7 +22,7 @@ class Admin $newResponse = $response->withStatus(302)->withHeader('Location', '/user'); return $newResponse; } - + $response = $next($request, $response); return $response; } diff --git a/app/Middleware/Api.php b/app/Middleware/Api.php index bfa6b966..ea35e95d 100644 --- a/app/Middleware/Api.php +++ b/app/Middleware/Api.php @@ -12,7 +12,7 @@ class Api public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) { $accessToken = Helper::getTokenFromReq($request); - if ($accessToken==null) { + if ($accessToken == null) { $res['ret'] = 0; $res['msg'] = "token is null"; $response->getBody()->write(json_encode($res)); @@ -20,7 +20,7 @@ class Api } $storage = Factory::createTokenStorage(); $token = $storage->get($accessToken); - if ($token==null) { + if ($token == null) { $res['ret'] = 0; $res['msg'] = "token is null"; $response->getBody()->write(json_encode($res)); diff --git a/app/Middleware/Mod_Mu.php b/app/Middleware/Mod_Mu.php index 4b39bea3..8270521e 100644 --- a/app/Middleware/Mod_Mu.php +++ b/app/Middleware/Mod_Mu.php @@ -22,26 +22,26 @@ class Mod_Mu return $response; } - $auth=false; - $keyset=explode(",", Config::get('muKey')); + $auth = false; + $keyset = explode(",", Config::get('muKey')); foreach ($keyset as $sinkey) { - if ($key==$sinkey) { - $auth=true; + if ($key == $sinkey) { + $auth = true; break; } } - if ($auth==false) { + if ($auth == false) { $res['ret'] = 0; $res['data'] = "token or source is invalid"; $response->getBody()->write(json_encode($res)); return $response; } - $node = Node::where("node_ip", "LIKE", $_SERVER["REMOTE_ADDR"].'%')->first(); - if ($node==null && $_SERVER["REMOTE_ADDR"] != '127.0.0.1') { + $node = Node::where("node_ip", "LIKE", $_SERVER["REMOTE_ADDR"] . '%')->first(); + if ($node == null && $_SERVER["REMOTE_ADDR"] != '127.0.0.1') { $res['ret'] = 0; - $res['data'] = "token or source is invalid, Your ip address is ". $_SERVER["REMOTE_ADDR"]; + $res['data'] = "token or source is invalid, Your ip address is " . $_SERVER["REMOTE_ADDR"]; $response->getBody()->write(json_encode($res)); return $response; } diff --git a/app/Middleware/Mu.php b/app/Middleware/Mu.php index e9dc304c..1ac8e811 100644 --- a/app/Middleware/Mu.php +++ b/app/Middleware/Mu.php @@ -22,24 +22,24 @@ class Mu return $response; } - $auth=false; - $keyset=explode(",", Config::get('muKey')); + $auth = false; + $keyset = explode(",", Config::get('muKey')); foreach ($keyset as $sinkey) { - if ($key==$sinkey) { - $auth=true; + if ($key == $sinkey) { + $auth = true; break; } } - if ($auth==false) { + if ($auth == false) { $res['ret'] = 0; $res['msg'] = "token or source is invalid"; $response->getBody()->write(json_encode($res)); return $response; } - $node = Node::where("node_ip", "LIKE", $_SERVER["REMOTE_ADDR"].'%')->first(); - if ($node==null && $_SERVER["REMOTE_ADDR"] != '127.0.0.1') { + $node = Node::where("node_ip", "LIKE", $_SERVER["REMOTE_ADDR"] . '%')->first(); + if ($node == null && $_SERVER["REMOTE_ADDR"] != '127.0.0.1') { $res['ret'] = 0; $res['msg'] = "token or source is invalid"; $response->getBody()->write(json_encode($res)); diff --git a/app/Models/Auto.php b/app/Models/Auto.php index 4c43f3f3..90a1f628 100644 --- a/app/Models/Auto.php +++ b/app/Models/Auto.php @@ -10,12 +10,11 @@ class Auto extends Model protected $table = "auto"; - public function datetime() { return date("Y-m-d H:i:s", $this->attributes['datetime']); } - + public function content() { return str_replace(PHP_EOL, '
', $this->attributes['value']); diff --git a/app/Models/BlockIp.php b/app/Models/BlockIp.php index 4c910690..a0140355 100644 --- a/app/Models/BlockIp.php +++ b/app/Models/BlockIp.php @@ -10,13 +10,12 @@ class BlockIp extends Model protected $connection = "default"; protected $table = "blockip"; - - + public function node() { return Node::where("id", $this->attributes['nodeid'])->first(); } - + public function time() { return date("Y-m-d H:i:s", $this->attributes['datetime']); diff --git a/app/Models/Bought.php b/app/Models/Bought.php index 563b9ee7..bbfee5c3 100644 --- a/app/Models/Bought.php +++ b/app/Models/Bought.php @@ -16,7 +16,7 @@ class Bought extends Model { return date("Y-m-d H:i:s", $this->attributes['datetime']); } - + public function user() { $user = User::where("id", $this->attributes['userid'])->first(); @@ -27,7 +27,7 @@ class Bought extends Model return $user; } } - + public function shop() { return Shop::where("id", $this->attributes['shopid'])->first(); diff --git a/app/Models/Code.php b/app/Models/Code.php index 013136a2..73df7899 100644 --- a/app/Models/Code.php +++ b/app/Models/Code.php @@ -13,8 +13,7 @@ class Code extends Model protected $connection = "default"; protected $table = "code"; - - + public function user() { return User::where("id", $this->attributes['userid'])->first(); diff --git a/app/Models/Coupon.php b/app/Models/Coupon.php index a3615437..a190932e 100644 --- a/app/Models/Coupon.php +++ b/app/Models/Coupon.php @@ -6,7 +6,7 @@ class Coupon extends Model { protected $connection = "default"; protected $table = "coupon"; - + public function expire() { return date("Y-m-d H:i:s", $this->attributes['expire']); @@ -14,18 +14,18 @@ class Coupon extends Model public function order($shop) { - if ($this->attributes['shop']=="") { + if ($this->attributes['shop'] == "") { return true; } - - $shop_array=explode(",", $this->attributes['shop']); - + + $shop_array = explode(",", $this->attributes['shop']); + foreach ($shop_array as $shopid) { - if ($shopid==$shop) { + if ($shopid == $shop) { return true; } } - + return false; } } diff --git a/app/Models/DetectRule.php b/app/Models/DetectRule.php index 87878ad9..f3a7d7e1 100644 --- a/app/Models/DetectRule.php +++ b/app/Models/DetectRule.php @@ -5,7 +5,6 @@ namespace App\Models; /** * DetectLog Model */ - class DetectRule extends Model { protected $connection = "default"; diff --git a/app/Models/Disconnect.php b/app/Models/Disconnect.php index fb831fe2..a4ede9bd 100644 --- a/app/Models/Disconnect.php +++ b/app/Models/Disconnect.php @@ -5,7 +5,6 @@ namespace App\Models; /** * Disconnect Model */ - class Disconnect extends Model { protected $connection = "default"; diff --git a/app/Models/EmailVerify.php b/app/Models/EmailVerify.php index 7f004107..07a73c0e 100644 --- a/app/Models/EmailVerify.php +++ b/app/Models/EmailVerify.php @@ -5,7 +5,6 @@ namespace App\Models; /** * EmailVerify Model */ - class EmailVerify extends Model { protected $connection = "default"; diff --git a/app/Models/InviteCode.php b/app/Models/InviteCode.php index 5b03b362..6c0fb83d 100644 --- a/app/Models/InviteCode.php +++ b/app/Models/InviteCode.php @@ -5,7 +5,6 @@ namespace App\Models; /** * InviteCode Model */ - class InviteCode extends Model { protected $connection = "default"; diff --git a/app/Models/Ip.php b/app/Models/Ip.php index abb0e8a7..2dafac13 100644 --- a/app/Models/Ip.php +++ b/app/Models/Ip.php @@ -12,7 +12,7 @@ class Ip extends Model { protected $connection = "default"; protected $table = "alive_ip"; - + public function user() { $user = User::where("id", $this->attributes['userid'])->first(); @@ -34,8 +34,8 @@ class Ip extends Model return $node; } } - - + + public function ip() { return str_replace("::ffff:", "", $this->attributes['ip']); diff --git a/app/Models/LoginIp.php b/app/Models/LoginIp.php index 66cfc06a..690af792 100644 --- a/app/Models/LoginIp.php +++ b/app/Models/LoginIp.php @@ -12,7 +12,7 @@ class LoginIp extends Model { protected $connection = "default"; protected $table = "login_ip"; - + public function user() { $user = User::where("id", $this->attributes['userid'])->first(); @@ -23,7 +23,7 @@ class LoginIp extends Model return $user; } } - + public function datetime() { return date("Y-m-d H:i:s", $this->attributes['datetime']); diff --git a/app/Models/Model.php b/app/Models/Model.php index 0b876ac6..55bfd886 100644 --- a/app/Models/Model.php +++ b/app/Models/Model.php @@ -7,7 +7,6 @@ use Illuminate\Database\Eloquent\Model as EloquentMedel; /** * Base Model */ - class Model extends EloquentMedel { public $timestamps = false; diff --git a/app/Models/Node.php b/app/Models/Node.php index 7a91a320..dbb1347d 100644 --- a/app/Models/Node.php +++ b/app/Models/Node.php @@ -43,9 +43,9 @@ class Node extends Model public function getNodeUpRate() { $id = $this->attributes['id']; - $log = NodeOnlineLog::where('node_id', $id)->where('log_time', '>=', time()-86400)->count(); + $log = NodeOnlineLog::where('node_id', $id)->where('log_time', '>=', time() - 86400)->count(); - return $log/1440; + return $log / 1440; } public function getNodeLoad() @@ -65,7 +65,7 @@ class Node extends Model public function getOnlineUserCount() { $id = $this->attributes['id']; - $log = NodeOnlineLog::where('node_id', $id)->where("log_time",">",time()-300)->orderBy('id', 'desc')->first(); + $log = NodeOnlineLog::where('node_id', $id)->where("log_time", ">", time() - 300)->orderBy('id', 'desc')->first(); if ($log == null) { return 0; } @@ -81,9 +81,9 @@ class Node extends Model } - return "电信延迟:".$log->telecomping." 下载:".$log->telecomeupload." 上传:".$log->telecomedownload."
- 联通延迟:".$log->unicomping." 下载:".$log->unicomupload." 上传:".$log->unicomdownload."
- 移动延迟:".$log->cmccping." 下载:".$log->cmccupload." 上传:".$log->cmccdownload."
定时测试,仅供参考"; + return "电信延迟:" . $log->telecomping . " 下载:" . $log->telecomeupload . " 上传:" . $log->telecomedownload . "
+ 联通延迟:" . $log->unicomping . " 下载:" . $log->unicomupload . " 上传:" . $log->unicomdownload . "
+ 移动延迟:" . $log->cmccping . " 下载:" . $log->cmccupload . " 上传:" . $log->cmccdownload . "
定时测试,仅供参考"; } public function getSpeedtestResult() @@ -117,10 +117,10 @@ class Node extends Model $id = $this->attributes['id']; $sort = $this->attributes['sort']; $node_heartbeat = $this->attributes['node_heartbeat']; - $log = NodeOnlineLog::where('node_id', $id)->where("log_time",">",time()-300)->orderBy('id', 'desc')->first(); - if(!($sort == 0 || $sort == 7 || $sort == 8 || $sort == 10 || $sort == 11 || $sort == 12 || $sort == 13) || $node_heartbeat == 0){ + $log = NodeOnlineLog::where('node_id', $id)->where("log_time", ">", time() - 300)->orderBy('id', 'desc')->first(); + if (!($sort == 0 || $sort == 7 || $sort == 8 || $sort == 10 || $sort == 11 || $sort == 12 || $sort == 13) || $node_heartbeat == 0) { $result = null; - }else if ($log != null && $log->log_time + 300 > time()) { + } else if ($log != null && $log->log_time + 300 > time()) { $result = true; } return $result; diff --git a/app/Models/NodeInfoLog.php b/app/Models/NodeInfoLog.php index ffc28826..916b705f 100644 --- a/app/Models/NodeInfoLog.php +++ b/app/Models/NodeInfoLog.php @@ -1,18 +1,19 @@ attributes['load']; $exp = explode(" ", $load); return $exp[0]; } - + public function getTime() { $time = $this->attributes['log_time']; diff --git a/app/Models/Payback.php b/app/Models/Payback.php index 92712456..cbe7e9c6 100644 --- a/app/Models/Payback.php +++ b/app/Models/Payback.php @@ -6,7 +6,7 @@ class Payback extends Model { protected $connection = "default"; protected $table = 'payback'; - + public function user() { $user = User::where("id", $this->attributes['userid'])->first(); diff --git a/app/Models/Relay.php b/app/Models/Relay.php index 6ad2503c..940b4691 100644 --- a/app/Models/Relay.php +++ b/app/Models/Relay.php @@ -5,7 +5,6 @@ namespace App\Models; /** * DetectLog Model */ - class Relay extends Model { protected $connection = "default"; diff --git a/app/Models/Role.php b/app/Models/Role.php index 11c24efb..94691f79 100644 --- a/app/Models/Role.php +++ b/app/Models/Role.php @@ -5,7 +5,6 @@ namespace App\Models; /** * Node Model */ - class Role extends Model { protected $connection = "default"; diff --git a/app/Models/Shop.php b/app/Models/Shop.php index 731ead69..db3538e0 100644 --- a/app/Models/Shop.php +++ b/app/Models/Shop.php @@ -12,48 +12,48 @@ class Shop extends Model public function content() { $content = json_decode($this->attributes['content'], true); - $content_text=""; + $content_text = ""; $i = 0; - foreach ($content as $key=>$value) { + foreach ($content as $key => $value) { switch ($key) { case "bandwidth": - $content_text .= "添加流量 ".$value." G "; + $content_text .= "添加流量 " . $value . " G "; break; case "expire": - $content_text .= ", 为账号的有效期添加 ".$value." 天 "; + $content_text .= ", 为账号的有效期添加 " . $value . " 天 "; break; case "class": - $content_text .= ", 为账号升级为等级 ".$value." , 有效期 ".$content["class_expire"]." 天 "; + $content_text .= ", 为账号升级为等级 " . $value . " , 有效期 " . $content["class_expire"] . " 天 "; break; case "reset": - $content_text .= ", 在 ".$content["reset_exp"]." 天内 ,每 ".$value." 天重置流量为 ".$content["reset_value"]." G "; + $content_text .= ", 在 " . $content["reset_exp"] . " 天内 ,每 " . $value . " 天重置流量为 " . $content["reset_value"] . " G "; break; case "speedlimit": - if ($value == 0){ - $content_text .= ", 用户端口不限速 " ; - }else{ - $content_text .= ", 用户端口限速变为".$value." Mbps "; + if ($value == 0) { + $content_text .= ", 用户端口不限速 "; + } else { + $content_text .= ", 用户端口限速变为" . $value . " Mbps "; } break; case "connector": - if ($value == 0){ + if ($value == 0) { $content_text .= ", 用户IP不限制"; - }else{ - $content_text .= ", 用户IP限制变为 ".$value." 个"; + } else { + $content_text .= ", 用户IP限制变为 " . $value . " 个"; } break; default: } //if ($iattributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->bandwidth)) { return $content->bandwidth; } else { @@ -71,7 +71,7 @@ class Shop extends Model public function expire() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->expire)) { return $content->expire; } else { @@ -81,7 +81,7 @@ class Shop extends Model public function reset() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->reset)) { return $content->reset; } else { @@ -91,7 +91,7 @@ class Shop extends Model public function reset_value() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->reset_value)) { return $content->reset_value; } else { @@ -101,7 +101,7 @@ class Shop extends Model public function reset_exp() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->reset_exp)) { return $content->reset_exp; } else { @@ -111,17 +111,17 @@ class Shop extends Model public function content_extra() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->content_extra)) { $content_extra = $content->content_extra; - $content_extra = explode(';',$content_extra); + $content_extra = explode(';', $content_extra); $content_extra_new = array(); foreach ($content_extra as $innerContent) { - if (!strstr($innerContent,'-')) { + if (!strstr($innerContent, '-')) { $innerContent = 'check-' . $innerContent; } - $innerContent = explode('-',$innerContent); - array_push($content_extra_new,$innerContent); + $innerContent = explode('-', $innerContent); + array_push($content_extra_new, $innerContent); } $content_extra = $content_extra_new; return $content_extra; @@ -132,7 +132,7 @@ class Shop extends Model public function user_class() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->class)) { return $content->class; } else { @@ -142,7 +142,7 @@ class Shop extends Model public function class_expire() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->class_expire)) { return $content->class_expire; } else { @@ -152,7 +152,7 @@ class Shop extends Model public function speedlimit() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->speedlimit)) { return $content->speedlimit; } else { @@ -162,7 +162,7 @@ class Shop extends Model public function connector() { - $content = json_decode($this->attributes['content']); + $content = json_decode($this->attributes['content']); if (isset($content->connector)) { return $content->connector; } else { @@ -173,47 +173,47 @@ class Shop extends Model public function buy($user, $is_renew = 0) { $content = json_decode($this->attributes['content'], true); - $content_text=""; + $content_text = ""; - foreach ($content as $key=>$value) { + foreach ($content as $key => $value) { switch ($key) { case "bandwidth": if ($is_renew == 0) { if (Config::get('enable_bought_reset') == 'true') { - $user->transfer_enable=$value*1024*1024*1024; + $user->transfer_enable = $value * 1024 * 1024 * 1024; $user->u = 0; $user->d = 0; $user->last_day_t = 0; } else { - $user->transfer_enable=$user->transfer_enable+$value*1024*1024*1024; + $user->transfer_enable = $user->transfer_enable + $value * 1024 * 1024 * 1024; } } else { if ($this->attributes['auto_reset_bandwidth'] == 1) { - $user->transfer_enable=$value*1024*1024*1024; + $user->transfer_enable = $value * 1024 * 1024 * 1024; $user->u = 0; $user->d = 0; $user->last_day_t = 0; } else { - $user->transfer_enable=$user->transfer_enable+$value*1024*1024*1024; + $user->transfer_enable = $user->transfer_enable + $value * 1024 * 1024 * 1024; } } break; case "expire": - if (time()>strtotime($user->expire_in)) { - $user->expire_in=date("Y-m-d H:i:s", time()+$value*86400); + if (time() > strtotime($user->expire_in)) { + $user->expire_in = date("Y-m-d H:i:s", time() + $value * 86400); } else { - $user->expire_in=date("Y-m-d H:i:s", strtotime($user->expire_in)+$value*86400); + $user->expire_in = date("Y-m-d H:i:s", strtotime($user->expire_in) + $value * 86400); } break; case "class": - $user->class=$value; - $user->class_expire=date("Y-m-d H:i:s", time()+$content["class_expire"]*86400); + $user->class = $value; + $user->class_expire = date("Y-m-d H:i:s", time() + $content["class_expire"] * 86400); break; case "speedlimit": - $user->node_speedlimit=$value; + $user->node_speedlimit = $value; break; case "connector": - $user->node_connector=$value; + $user->node_connector = $value; break; default: } diff --git a/app/Models/Speedtest.php b/app/Models/Speedtest.php index ce7d1e49..8c908b79 100644 --- a/app/Models/Speedtest.php +++ b/app/Models/Speedtest.php @@ -12,34 +12,34 @@ class Speedtest extends Model { protected $connection = "default"; protected $table = "speedtest"; - + public function node() { return Node::find($this->attributes['nodeid']); } - + public function getTelecomPing() { $load = $this->attributes['telecomping']; $exp = explode(" ", $load); return $exp[0]; } - + public function getUnicomPing() { $load = $this->attributes['unicomping']; $exp = explode(" ", $load); return $exp[0]; } - + public function getCmccPing() { $load = $this->attributes['cmccping']; $exp = explode(" ", $load); return $exp[0]; } - + public function getTelecomUpload() { @@ -47,35 +47,35 @@ class Speedtest extends Model $exp = explode(" ", $load); return $exp[0]; } - + public function getTelecomDownload() { $load = $this->attributes['telecomedownload']; $exp = explode(" ", $load); return $exp[0]; } - + public function getUnicomUpload() { $load = $this->attributes['unicomupload']; $exp = explode(" ", $load); return $exp[0]; } - + public function getUnicomDownload() { $load = $this->attributes['unicomdownload']; $exp = explode(" ", $load); return $exp[0]; } - + public function getCmccDownload() { $load = $this->attributes['cmccdownload']; $exp = explode(" ", $load); return $exp[0]; } - + public function getCmccUpload() { $load = $this->attributes['cmccupload']; diff --git a/app/Models/TelegramSession.php b/app/Models/TelegramSession.php index 784c0c52..86fff38a 100644 --- a/app/Models/TelegramSession.php +++ b/app/Models/TelegramSession.php @@ -5,7 +5,6 @@ namespace App\Models; /** * TelegramSession Model */ - class TelegramSession extends Model { protected $connection = "default"; @@ -15,7 +14,7 @@ class TelegramSession extends Model { return date("Y-m-d H:i:s", $this->attributes['datetime']); } - + public function User() { $user = User::where("id", $this->attributes['user_id'])->first(); diff --git a/app/Models/Ticket.php b/app/Models/Ticket.php index 03903681..d223ffb7 100644 --- a/app/Models/Ticket.php +++ b/app/Models/Ticket.php @@ -5,7 +5,6 @@ namespace App\Models; /** * Ticket Model */ - class Ticket extends Model { protected $connection = "default"; @@ -15,7 +14,7 @@ class Ticket extends Model { return date("Y-m-d H:i:s", $this->attributes['datetime']); } - + public function User() { $user = User::where("id", $this->attributes['userid'])->first(); diff --git a/app/Models/TrafficLog.php b/app/Models/TrafficLog.php index 7c443363..1e78e67e 100644 --- a/app/Models/TrafficLog.php +++ b/app/Models/TrafficLog.php @@ -20,7 +20,7 @@ class TrafficLog extends Model return $node; } } - + public function user() { $user = User::where("id", $this->attributes['user_id'])->first(); @@ -36,10 +36,10 @@ class TrafficLog extends Model { return Tools::flowAutoShow($this->attributes['u'] + $this->attributes['d']); } - + public function totalUsedRaw() { - return number_format(($this->attributes['u'] + $this->attributes['d'])/1024, 2, ".", ""); + return number_format(($this->attributes['u'] + $this->attributes['d']) / 1024, 2, ".", ""); } public function logTime() diff --git a/app/Models/UnblockIp.php b/app/Models/UnblockIp.php index b055139a..888c1621 100644 --- a/app/Models/UnblockIp.php +++ b/app/Models/UnblockIp.php @@ -20,7 +20,7 @@ class UnblockIp extends Model return $user; } } - + public function time() { return date("Y-m-d H:i:s", $this->attributes['datetime']); diff --git a/app/Models/User.php b/app/Models/User.php index b984981e..b4b5b14c 100755 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -39,7 +39,7 @@ class User extends Model public function getGravatarAttribute() { - // $hash = md5(strtolower(trim($this->attributes['email']))); + // $hash = md5(strtolower(trim($this->attributes['email']))); return "/images/Avatar.jpg";//.$hash; } @@ -64,9 +64,9 @@ class User extends Model foreach ($matches[0] as $key) { $key_match = str_replace("%", "", $key); $key_match = str_replace("m", "", $key_match); - $md5 = substr(MD5($this->attributes['id'].$this->attributes['passwd'].$this->attributes['method'].$this->attributes['obfs'].$this->attributes['protocol']), - ($key_match < 0 ? $key_match : 0), - abs($key_match)); + $md5 = substr(MD5($this->attributes['id'] . $this->attributes['passwd'] . $this->attributes['method'] . $this->attributes['obfs'] . $this->attributes['protocol']), + ($key_match < 0 ? $key_match : 0), + abs($key_match)); $str = str_replace($key, $md5, $str); } return $str; @@ -117,19 +117,20 @@ class User extends Model { $uid = $this->attributes['id']; $code = new InviteCode(); - while(true){ - $temp_code=Tools::genRandomChar(4); - if(InviteCode::where('user_id', $uid)->count()==0){ - break; - } - } + while (true) { + $temp_code = Tools::genRandomChar(4); + if (InviteCode::where('user_id', $uid)->count() == 0) { + break; + } + } $code->code = $temp_code; $code->user_id = $uid; $code->save(); } - public function getUuid() { - return Uuid::uuid3(Uuid::NAMESPACE_DNS, $this->attributes['id']. '|' .$this->attributes['passwd'])->toString(); + public function getUuid() + { + return Uuid::uuid3(Uuid::NAMESPACE_DNS, $this->attributes['id'] . '|' . $this->attributes['passwd'])->toString(); } public function trafficUsagePercent() @@ -150,16 +151,19 @@ class User extends Model $transfer_enable = $this->attributes['transfer_enable']; return Tools::flowAutoShow($transfer_enable); } + public function enableTrafficInGB() { $transfer_enable = $this->attributes['transfer_enable']; return Tools::flowToGB($transfer_enable); } + public function usedTraffic() { $total = $this->attributes['u'] + $this->attributes['d']; return Tools::flowAutoShow($total); } + public function unusedTraffic() { $total = $this->attributes['u'] + $this->attributes['d']; @@ -169,7 +173,7 @@ class User extends Model public function TodayusedTraffic() { - $total = $this->attributes['u'] + $this->attributes['d']-$this->attributes['last_day_t']; + $total = $this->attributes['u'] + $this->attributes['d'] - $this->attributes['last_day_t']; return Tools::flowAutoShow($total); } @@ -184,7 +188,7 @@ class User extends Model $last = $this->attributes['last_check_in_time']; $now = time(); - if (date("Ymd", $now)!= date("Ymd", $last)) { + if (date("Ymd", $now) != date("Ymd", $last)) { return true; } return false; @@ -200,7 +204,7 @@ class User extends Model public function getGAurl() { $ga = new GA(); - $url = $ga->getUrl(urlencode(Config::get('appName')."-".$this->attributes['user_name']."-两步验证码"), $this->attributes['ga_token']); + $url = $ga->getUrl(urlencode(Config::get('appName') . "-" . $this->attributes['user_name'] . "-两步验证码"), $this->attributes['ga_token']); return $url; } @@ -221,7 +225,7 @@ class User extends Model $uid = $this->attributes['id']; Link::where('userid', $uid)->delete(); } - + public function clear_inviteCodes() { $uid = $this->attributes['id']; @@ -231,12 +235,12 @@ class User extends Model public function online_ip_count() { $uid = $this->attributes['id']; - $total = Ip::where("datetime", ">=", time()-90)->where('userid', $uid)->orderBy('userid', 'desc')->get(); + $total = Ip::where("datetime", ">=", time() - 90)->where('userid', $uid)->orderBy('userid', 'desc')->get(); $unique_ip_list = array(); foreach ($total as $single_record) { $single_record->ip = Tools::getRealIp($single_record->ip); $is_node = Node::where("node_ip", $single_record->ip)->first(); - if($is_node) { + if ($is_node) { continue; } @@ -289,19 +293,19 @@ class User extends Model $im_type = ''; $im_value = $this->attributes['im_value']; - switch($this->attributes['im_type']) { + switch ($this->attributes['im_type']) { case 1: - $im_type = '微信'; - break; + $im_type = '微信'; + break; case 2: - $im_type = 'QQ'; - break; + $im_type = 'QQ'; + break; case 3: - $im_type = 'Google+'; - break; + $im_type = 'Google+'; + break; default: - $im_type = 'Telegram'; - $im_value = ''.$im_value.''; + $im_type = 'Telegram'; + $im_value = '' . $im_value . ''; } $ref_user = User::find($this->attributes['ref_by']); @@ -320,25 +324,25 @@ class User extends Model } $iplocation = new QQWry(); - $location=$iplocation->getlocation($reg_location); - $reg_location .= "\n".iconv('gbk', 'utf-8//IGNORE', $location['country'].$location['area']); - - $return_array = Array('DT_RowId' => 'row_1_'.$id, $id, $id, - $this->attributes['user_name'], $this->attributes['remark'], - $this->attributes['email'], $this->attributes['money'], - $im_type, $im_value, - $this->attributes['node_group'], $account_expire_in, - $this->attributes['class'], $class_expire_in, - $this->attributes['passwd'], $this->attributes['port'], - $this->attributes['method'], - $this->attributes['protocol'], $this->attributes['obfs'], - $this->online_ip_count(), $this->lastSsTime(), - $used_traffic, $enable_traffic, - $this->lastCheckInTime(), $today_traffic, - $is_enable, $this->attributes['reg_date'], - $reg_location, - $this->attributes['auto_reset_day'], $this->attributes['auto_reset_bandwidth'], - $ref_user_id, $ref_user_name); + $location = $iplocation->getlocation($reg_location); + $reg_location .= "\n" . iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']); + + $return_array = Array('DT_RowId' => 'row_1_' . $id, $id, $id, + $this->attributes['user_name'], $this->attributes['remark'], + $this->attributes['email'], $this->attributes['money'], + $im_type, $im_value, + $this->attributes['node_group'], $account_expire_in, + $this->attributes['class'], $class_expire_in, + $this->attributes['passwd'], $this->attributes['port'], + $this->attributes['method'], + $this->attributes['protocol'], $this->attributes['obfs'], + $this->online_ip_count(), $this->lastSsTime(), + $used_traffic, $enable_traffic, + $this->lastCheckInTime(), $today_traffic, + $is_enable, $this->attributes['reg_date'], + $reg_location, + $this->attributes['auto_reset_day'], $this->attributes['auto_reset_bandwidth'], + $ref_user_id, $ref_user_name); return $return_array; } @@ -347,13 +351,13 @@ class User extends Model return $this->attributes[$key]; } - public function get_top_up() - { - $codes=Code::where('userid',$this->attributes['id'])->get(); - $top_up=0; - foreach($codes as $code){ - $top_up+=$code->number; + public function get_top_up() + { + $codes = Code::where('userid', $this->attributes['id'])->get(); + $top_up = 0; + foreach ($codes as $code) { + $top_up += $code->number; } - return round($top_up,2); - } + return round($top_up, 2); + } } diff --git a/app/Services/Analytic.php b/app/Services/Analytic.php index dd45febd..d01f14a4 100644 --- a/app/Services/Analytic.php +++ b/app/Services/Analytic.php @@ -9,7 +9,7 @@ class Analytic { public function userCount() { - return User::all()->count(); + return User::all()->count(); } public function checkinUserCount() diff --git a/app/Services/Analytics.php b/app/Services/Analytics.php index 2a7c0ace..dbc0e806 100644 --- a/app/Services/Analytics.php +++ b/app/Services/Analytics.php @@ -17,7 +17,7 @@ class Analytics { return User::where('last_check_in_time', '>', 0)->count(); } - + public function getTodayCheckinUser() { return User::where('last_check_in_time', '>', strtotime('today'))->count(); @@ -28,52 +28,52 @@ class Analytics $total = User::sum('u') + User::sum('d'); return Tools::flowAutoShow($total); } - + public function getTodayTrafficUsage() { $total = User::sum('u') + User::sum('d') - User::sum('last_day_t'); return Tools::flowAutoShow($total); } - - + + public function getRawTodayTrafficUsage() { $total = User::sum('u') + User::sum('d') - User::sum('last_day_t'); return $total; } - + public function getLastTrafficUsage() { $total = User::sum('last_day_t'); return Tools::flowAutoShow($total); } - - + + public function getRawLastTrafficUsage() { $total = User::sum('last_day_t'); return $total; } - + public function getUnusedTrafficUsage() { $total = User::sum('transfer_enable') - User::sum('u') - User::sum('d'); return Tools::flowAutoShow($total); } - + public function getRawUnusedTrafficUsage() { $total = User::sum('transfer_enable') - User::sum('u') - User::sum('d'); return $total; } - - + + public function getTotalTraffic() { $total = User::sum('transfer_enable'); return Tools::flowAutoShow($total); } - + public function getRawTotalTraffic() { $total = User::sum('transfer_enable'); @@ -85,7 +85,7 @@ class Analytics $time = time() - $time; return User::where('t', '>', $time)->count(); } - + public function getUnusedUser() { return User::where('t', '=', 0)->count(); @@ -95,20 +95,20 @@ class Analytics { return Node::count(); } - + public function getTotalNodes() { return Node::where('node_heartbeat', '>', 0)->where( - function ($query) { - $query->Where('sort', '=', 0) - ->orWhere('sort', '=', 10) - ->orWhere('sort', '=', 11) - ->orWhere('sort', '=', 12) - ->orWhere('sort', '=', 13); - } - )->count(); - } - + function ($query) { + $query->Where('sort', '=', 0) + ->orWhere('sort', '=', 10) + ->orWhere('sort', '=', 11) + ->orWhere('sort', '=', 12) + ->orWhere('sort', '=', 13); + } + )->count(); + } + public function getAliveNodes() { return Node::where( @@ -119,6 +119,6 @@ class Analytics ->orWhere('sort', '=', 12) ->orWhere('sort', '=', 13); } - )->where('node_heartbeat', '>', time()-90)->count(); + )->where('node_heartbeat', '>', time() - 90)->count(); } } diff --git a/app/Services/Auth/Base.php b/app/Services/Auth/Base.php index 7860e3cc..62d44453 100644 --- a/app/Services/Auth/Base.php +++ b/app/Services/Auth/Base.php @@ -5,6 +5,8 @@ namespace App\Services\Auth; abstract class Base { abstract public function login($uid, $time); + abstract public function logout(); + abstract public function getUser(); } diff --git a/app/Services/Auth/JwtToken.php b/app/Services/Auth/JwtToken.php index 29daa2f6..b5b4d97c 100644 --- a/app/Services/Auth/JwtToken.php +++ b/app/Services/Auth/JwtToken.php @@ -11,8 +11,8 @@ class JwtToken extends Base { $expireTime = time() + $time; $ary = [ - "uid" => $uid, - "expire_time" => $expireTime + "uid" => $uid, + "expire_time" => $expireTime ]; $decode = Jwt::encode($ary); Utils\Cookie::set([ @@ -26,7 +26,7 @@ class JwtToken extends Base Utils\Cookie::set([ //"uid" => $uid, "token" => "" - ], time()-3600); + ], time() - 3600); } public function getUser() diff --git a/app/Services/Auth/Redis.php b/app/Services/Auth/Redis.php index 14691f0b..50a43540 100644 --- a/app/Services/Auth/Redis.php +++ b/app/Services/Auth/Redis.php @@ -30,10 +30,10 @@ class Redis extends Base $sid = Tools::genSID(); Cookie::set([ 'sid' => $sid - ], $time+time()); + ], $time + time()); $value = $uid; $this->client->setex($sid, $time, $value); - $this->client->setex($sid."ip", $time, $_SERVER["REMOTE_ADDR"]); + $this->client->setex($sid . "ip", $time, $_SERVER["REMOTE_ADDR"]); } public function logout() @@ -46,22 +46,22 @@ class Redis extends Base { $sid = Cookie::get('sid'); $value = $this->client->get($sid); - - $ip = $this->client->get($sid."ip"); - $nodes=Node::where("node_ip", "=", $_SERVER["REMOTE_ADDR"])->first(); - if ($ip != $_SERVER["REMOTE_ADDR"] && $nodes==null && Config::get('enable_login_bind_ip')=='true') { + + $ip = $this->client->get($sid . "ip"); + $nodes = Node::where("node_ip", "=", $_SERVER["REMOTE_ADDR"])->first(); + if ($ip != $_SERVER["REMOTE_ADDR"] && $nodes == null && Config::get('enable_login_bind_ip') == 'true') { $user = new User(); $user->isLogin = false; return $user; } - + if ($value == null) { $user = new User(); $user->isLogin = false; return $user; } $uid = $value; - $user = User::find($uid); + $user = User::find($uid); if ($user == null) { $user = new User(); $user->isLogin = false; diff --git a/app/Services/Aws/Client.php b/app/Services/Aws/Client.php index 526cfe4b..50eea016 100644 --- a/app/Services/Aws/Client.php +++ b/app/Services/Aws/Client.php @@ -9,8 +9,8 @@ class Client public function getClient() { $sdk = new Sdk([ - 'region' => 'us-west-2', - 'version' => 'latest', + 'region' => 'us-west-2', + 'version' => 'latest', 'DynamoDb' => [ 'region' => 'eu-central-1' ] diff --git a/app/Services/Aws/Factory.php b/app/Services/Aws/Factory.php index e5433223..cb82d34e 100644 --- a/app/Services/Aws/Factory.php +++ b/app/Services/Aws/Factory.php @@ -11,11 +11,11 @@ class Factory { $sdk = new Sdk([ 'credentials' => array( - 'key' => Config::get('aws_access_key_id'), + 'key' => Config::get('aws_access_key_id'), 'secret' => Config::get('aws_secret_access_key'), ), - 'region' => Config::get('aws_region'), - 'version' => 'latest', + 'region' => Config::get('aws_region'), + 'version' => 'latest', 'DynamoDb' => [ 'region' => Config::get('aws_region') ] diff --git a/app/Services/Boot.php b/app/Services/Boot.php index e31a26d6..1fe45761 100644 --- a/app/Services/Boot.php +++ b/app/Services/Boot.php @@ -31,7 +31,7 @@ class Boot // Init Eloquent ORM Connection $capsule = new Capsule; $capsule->addConnection(Config::getDbConfig(), 'default'); - if (Config::get('enable_radius')=='true') { + if (Config::get('enable_radius') == 'true') { $capsule->addConnection(Config::getRadiusDbConfig(), 'radius'); } $capsule->bootEloquent(); diff --git a/app/Services/Config.php b/app/Services/Config.php index c6868d2e..f1d1ecba 100755 --- a/app/Services/Config.php +++ b/app/Services/Config.php @@ -22,16 +22,16 @@ class Config "appName" => self::get("appName"), "version" => VERSION, "baseUrl" => self::get("baseUrl"), - "min_port" => self::get("min_port"), - "max_port" => self::get("max_port"), + "min_port" => self::get("min_port"), + "max_port" => self::get("max_port"), "checkinMin" => self::get("checkinMin"), "checkinMax" => self::get("checkinMax"), - "invite_price"=>self::get("invite_price"), - "invite_get_money"=>self::get("invite_get_money"), + "invite_price" => self::get("invite_price"), + "invite_get_money" => self::get("invite_get_money"), "code_payback" => self::get("code_payback"), - "invite_gift"=>self::get("invite_gift"), - "port_price" => self::get("port_price"), - "port_price_specify" => self::get("port_price_specify"), + "invite_gift" => self::get("invite_gift"), + "port_price" => self::get("port_price"), + "port_price_specify" => self::get("port_price_specify"), "jump_delay" => self::get("jump_delay"), "enable_analytics_code" => self::get("enable_analytics_code"), "sspanelAnalysis" => self::get("sspanelAnalysis"), @@ -39,45 +39,45 @@ class Config "enable_telegram" => self::get("enable_telegram"), "enable_discord" => self::get("enable_discord"), "payment_system" => self::get("payment_system"), - "enable_mylivechat" => self::get("enable_mylivechat"), - "mylivechat_id" => self::get("mylivechat_id"), - "enable_ticket"=> self::get("enable_ticket"), - "enable_admin_contact" => self::get("enable_admin_contact"), - "admin_contact1" => self::get("admin_contact1"), - "admin_contact2" => self::get("admin_contact2"), - "admin_contact3" => self::get("admin_contact3"), - "register_mode" => self::get("register_mode"), + "enable_mylivechat" => self::get("enable_mylivechat"), + "mylivechat_id" => self::get("mylivechat_id"), + "enable_ticket" => self::get("enable_ticket"), + "enable_admin_contact" => self::get("enable_admin_contact"), + "admin_contact1" => self::get("admin_contact1"), + "admin_contact2" => self::get("admin_contact2"), + "admin_contact3" => self::get("admin_contact3"), + "register_mode" => self::get("register_mode"), "enable_flag" => self::get("enable_flag"), "enable_kill" => self::get("enable_kill"), "custom_invite_price" => self::get("custom_invite_price"), "captcha_provider" => self::get("captcha_provider"), "enable_email_verify" => self::get("enable_email_verify") - ]; + ]; } public static function getDbConfig() { return [ - 'driver' => self::get('db_driver'), - 'host' => self::get('db_host'), - 'database' => self::get('db_database'), - 'username' => self::get('db_username'), - 'password' => self::get('db_password'), - 'charset' => self::get('db_charset'), + 'driver' => self::get('db_driver'), + 'host' => self::get('db_host'), + 'database' => self::get('db_database'), + 'username' => self::get('db_username'), + 'password' => self::get('db_password'), + 'charset' => self::get('db_charset'), 'collation' => self::get('db_collation'), - 'prefix' => self::get('db_prefix') + 'prefix' => self::get('db_prefix') ]; } public static function getRadiusDbConfig() { return [ - 'driver' => self::get('db_driver'), - 'host' => self::get('radius_db_host'), - 'database' => self::get('radius_db_database'), - 'username' => self::get('radius_db_user'), - 'password' => self::get('radius_db_password'), - 'charset' => self::get('db_charset'), + 'driver' => self::get('db_driver'), + 'host' => self::get('radius_db_host'), + 'database' => self::get('radius_db_database'), + 'username' => self::get('radius_db_user'), + 'password' => self::get('radius_db_password'), + 'charset' => self::get('db_charset'), 'collation' => self::get('db_collation') ]; } @@ -87,32 +87,32 @@ class Config switch ($type) { case 'obfs': $list = array('plain', 'http_simple', 'http_simple_compatible', 'http_post', 'http_post_compatible', - 'tls1.2_ticket_auth', 'tls1.2_ticket_auth_compatible', 'tls1.2_ticket_fastauth', 'tls1.2_ticket_fastauth_compatible', - 'simple_obfs_http', 'simple_obfs_http_compatible', 'simple_obfs_tls', 'simple_obfs_tls_compatible'); + 'tls1.2_ticket_auth', 'tls1.2_ticket_auth_compatible', 'tls1.2_ticket_fastauth', 'tls1.2_ticket_fastauth_compatible', + 'simple_obfs_http', 'simple_obfs_http_compatible', 'simple_obfs_tls', 'simple_obfs_tls_compatible'); return $list; case 'protocol': $list = array('origin', 'verify_deflate', - 'auth_sha1_v4', 'auth_sha1_v4_compatible', 'auth_aes128_sha1', 'auth_aes128_md5', 'auth_chain_a', 'auth_chain_b','auth_chain_c','auth_chain_d','auth_chain_e','auth_chain_f'); + 'auth_sha1_v4', 'auth_sha1_v4_compatible', 'auth_aes128_sha1', 'auth_aes128_md5', 'auth_chain_a', 'auth_chain_b', 'auth_chain_c', 'auth_chain_d', 'auth_chain_e', 'auth_chain_f'); return $list; case 'allow_none_protocol': - $list = array('auth_chain_a', 'auth_chain_b','auth_chain_c','auth_chain_d','auth_chain_e','auth_chain_f'); + $list = array('auth_chain_a', 'auth_chain_b', 'auth_chain_c', 'auth_chain_d', 'auth_chain_e', 'auth_chain_f'); return $list; case 'relay_able_protocol': - $list = array('auth_aes128_md5', 'auth_aes128_sha1', 'auth_chain_a', 'auth_chain_b','auth_chain_c','auth_chain_d','auth_chain_e','auth_chain_f'); + $list = array('auth_aes128_md5', 'auth_aes128_sha1', 'auth_chain_a', 'auth_chain_b', 'auth_chain_c', 'auth_chain_d', 'auth_chain_e', 'auth_chain_f'); return $list; case 'ss_aead_method': $list = array('aes-128-gcm', 'aes-192-gcm', - 'aes-256-gcm', 'chacha20-ietf-poly1305', 'xchacha20-ietf-poly1305'); + 'aes-256-gcm', 'chacha20-ietf-poly1305', 'xchacha20-ietf-poly1305'); return $list; case 'ss_obfs': $list = array('simple_obfs_http', 'simple_obfs_http_compatible', 'simple_obfs_tls', 'simple_obfs_tls_compatible'); return $list; default: $list = array('rc4-md5', 'rc4-md5-6', 'aes-128-cfb', 'aes-192-cfb', 'aes-256-cfb', - 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'camellia-128-cfb', 'camellia-192-cfb', 'camellia-256-cfb', - 'bf-cfb', 'cast5-cfb', 'des-cfb', 'des-ede3-cfb', 'idea-cfb', - 'rc2-cfb', 'seed-cfb', 'salsa20', 'chacha20', 'xsalsa20', 'chacha20-ietf', 'aes-128-gcm', 'aes-192-gcm', 'none', - 'aes-256-gcm', 'chacha20-ietf-poly1305', 'xchacha20-ietf-poly1305'); + 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'camellia-128-cfb', 'camellia-192-cfb', 'camellia-256-cfb', + 'bf-cfb', 'cast5-cfb', 'des-cfb', 'des-ede3-cfb', 'idea-cfb', + 'rc2-cfb', 'seed-cfb', 'salsa20', 'chacha20', 'xsalsa20', 'chacha20-ietf', 'aes-128-gcm', 'aes-192-gcm', 'none', + 'aes-256-gcm', 'chacha20-ietf-poly1305', 'xchacha20-ietf-poly1305'); return $list; } } diff --git a/app/Services/Gateway/AbstractPayment.php b/app/Services/Gateway/AbstractPayment.php index 3bbed39c..d38d98ee 100644 --- a/app/Services/Gateway/AbstractPayment.php +++ b/app/Services/Gateway/AbstractPayment.php @@ -18,68 +18,74 @@ use App\Utils\Telegram; abstract class AbstractPayment { abstract public function purchase($request, $response, $args); + abstract public function notify($request, $response, $args); + abstract public function getPurchaseHTML(); + abstract public function getReturnHTML($request, $response, $args); + abstract public function getStatus($request, $response, $args); - public function postPayment($pid, $method){ + public function postPayment($pid, $method) + { $p = Paylist::where("tradeno", $pid)->first(); - if($p->status==1){ - return json_encode(['errcode'=>0]); + if ($p->status == 1) { + return json_encode(['errcode' => 0]); } - $p->status=1; + $p->status = 1; $p->save(); $user = User::find($p->userid); $user->money += $p->total; $user->save(); - $codeq=new Code(); - $codeq->code=$method; - $codeq->isused=1; - $codeq->type=-1; - $codeq->number=$p->total; - $codeq->usedatetime=date("Y-m-d H:i:s"); - $codeq->userid=$user->id; + $codeq = new Code(); + $codeq->code = $method; + $codeq->isused = 1; + $codeq->type = -1; + $codeq->number = $p->total; + $codeq->usedatetime = date("Y-m-d H:i:s"); + $codeq->userid = $user->id; $codeq->save(); if ($user->ref_by >= 1) { - $gift_user=User::where("id", "=", $user->ref_by)->first(); - $gift_user->money=($gift_user->money+($codeq->number*(Config::get('code_payback')/100))); + $gift_user = User::where("id", "=", $user->ref_by)->first(); + $gift_user->money = ($gift_user->money + ($codeq->number * (Config::get('code_payback') / 100))); $gift_user->save(); - $Payback=new Payback(); - $Payback->total=$codeq->number; - $Payback->userid=$user->id; - $Payback->ref_by=$user->ref_by; - $Payback->ref_get=$codeq->number*(Config::get('code_payback')/100); - $Payback->datetime=time(); + $Payback = new Payback(); + $Payback->total = $codeq->number; + $Payback->userid = $user->id; + $Payback->ref_by = $user->ref_by; + $Payback->ref_get = $codeq->number * (Config::get('code_payback') / 100); + $Payback->datetime = time(); $Payback->save(); } if (Config::get('enable_donate') == 'true') { if ($user->is_hide == 1) { - Telegram::Send("一位不愿透露姓名的大老爷给我们捐了 ".$codeq->number." 元!"); + Telegram::Send("一位不愿透露姓名的大老爷给我们捐了 " . $codeq->number . " 元!"); } else { - Telegram::Send($user->user_name." 大老爷给我们捐了 ".$codeq->number." 元!"); + Telegram::Send($user->user_name . " 大老爷给我们捐了 " . $codeq->number . " 元!"); } } return 0; } - public static function generateGuid() { - mt_srand((double)microtime()*10000); + public static function generateGuid() + { + mt_srand((double)microtime() * 10000); $charid = strtoupper(md5(uniqid(rand() + time(), true))); $hyphen = chr(45); - $uuid = chr(123) - .substr($charid, 0, 8).$hyphen - .substr($charid, 8, 4).$hyphen - .substr($charid,12, 4).$hyphen - .substr($charid,16, 4).$hyphen - .substr($charid,20,12) - .chr(125); - $uuid = str_replace(['}', '{', '-'],'',$uuid); + $uuid = chr(123) + . substr($charid, 0, 8) . $hyphen + . substr($charid, 8, 4) . $hyphen + . substr($charid, 12, 4) . $hyphen + . substr($charid, 16, 4) . $hyphen + . substr($charid, 20, 12) + . chr(125); + $uuid = str_replace(['}', '{', '-'], '', $uuid); $uuid = substr($uuid, 0, 8); return $uuid; } diff --git a/app/Services/Gateway/AopF2F.php b/app/Services/Gateway/AopF2F.php index 77d221c5..dcd82ab6 100644 --- a/app/Services/Gateway/AopF2F.php +++ b/app/Services/Gateway/AopF2F.php @@ -17,13 +17,14 @@ use Omnipay\Omnipay; class AopF2F extends AbstractPayment { - private function createGateway(){ + private function createGateway() + { $gateway = Omnipay::create('Alipay_AopF2F'); $gateway->setSignType('RSA2'); //RSA/RSA2 $gateway->setAppId(Config::get("f2fpay_app_id")); $gateway->setPrivateKey(Config::get("merchant_private_key")); // 可以是路径,也可以是密钥内容 $gateway->setAlipayPublicKey(Config::get("alipay_public_key")); // 可以是路径,也可以是密钥内容 - $gateway->setNotifyUrl(Config::get("baseUrl")."/payment/notify"); + $gateway->setNotifyUrl(Config::get("baseUrl") . "/payment/notify"); return $gateway; } @@ -49,7 +50,7 @@ class AopF2F extends AbstractPayment $request = $gateway->purchase(); $request->setBizContent([ - 'subject' => $pl->tradeno, + 'subject' => $pl->tradeno, 'out_trade_no' => $pl->tradeno, 'total_amount' => $pl->total ]); @@ -78,7 +79,7 @@ class AopF2F extends AbstractPayment /** @var \Omnipay\Alipay\Responses\AopCompletePurchaseResponse $response */ $aliResponse = $aliRequest->send(); $pid = $aliResponse->data('out_trade_no'); - if($aliResponse->isPaid()){ + if ($aliResponse->isPaid()) { self::postPayment($pid, "支付宝当面付"); die('success'); //The response should be 'success' only } diff --git a/app/Services/Gateway/Codepay.php b/app/Services/Gateway/Codepay.php index 0a48dbe1..55a9f8e2 100755 --- a/app/Services/Gateway/Codepay.php +++ b/app/Services/Gateway/Codepay.php @@ -7,6 +7,7 @@ */ namespace App\Services\Gateway; + use App\Services\Auth; use App\Services\Config; use App\Models\User; @@ -45,7 +46,7 @@ class Codepay extends AbstractPayment $pl = new Paylist(); $pl->userid = $user->id; $pl->total = $price; - $pl->tradeno = (string)time()."UID".(string)$user->id; + $pl->tradeno = (string)time() . "UID" . (string)$user->id; $pl->save(); @@ -88,7 +89,7 @@ class Codepay extends AbstractPayment //以下五行无需更改 ksort($_POST); //排序post参数 reset($_POST); //内部指针指向数组中的第一个元素 - $codepay_key=Config::get('codepay_key'); //这是您的密钥 + $codepay_key = Config::get('codepay_key'); //这是您的密钥 $sign = '';//初始化 foreach ($_POST AS $key => $val) { //遍历POST参数 if ($val == '' || $key == 'sign') continue; //跳过这些不签名 diff --git a/app/Services/Gateway/DoiAMPay.php b/app/Services/Gateway/DoiAMPay.php index 177b6cff..b126afe8 100644 --- a/app/Services/Gateway/DoiAMPay.php +++ b/app/Services/Gateway/DoiAMPay.php @@ -6,6 +6,7 @@ * Date: 2018/9/24 * Time: 下午4:01 */ + /** * Made By Leo * 黛米付接口 @@ -13,6 +14,7 @@ * 适用于 V1 API 黛米付面板V1 * copyright all rights reserved */ + namespace App\Services\Gateway; use App\Services\View; @@ -22,28 +24,26 @@ use App\Services\Config; use App\Models\Paylist; - - class DoiAMPay extends AbstractPayment { public function getPurchaseHTML() { - return View::getSmarty()->assign("enabled",Config::get("doiampay")['enabled'])->fetch("user/doiam.tpl"); + return View::getSmarty()->assign("enabled", Config::get("doiampay")['enabled'])->fetch("user/doiam.tpl"); } public function notify($request, $response, $args) { $order_data = $_POST; - $status = $order_data['status']; //获取传递过来的交易状态 + $status = $order_data['status']; //获取传递过来的交易状态 $invoiceid = $order_data['out_trade_no']; //订单号 - $transid = $order_data['trade_no']; //转账交易号 - $amount = $order_data['money']; //获取递过来的总价格 - if(!DoiAM::checksign($_POST,Config::get("doiampay")['mchdata'][$args['type']]['token'])){ - return (json_encode(array('errcode'=>2333))); + $transid = $order_data['trade_no']; //转账交易号 + $amount = $order_data['money']; //获取递过来的总价格 + if (!DoiAM::checksign($_POST, Config::get("doiampay")['mchdata'][$args['type']]['token'])) { + return (json_encode(array('errcode' => 2333))); } if ($status == 'success') { - self::postPayment($invoiceid, "黛米付".['wepay' => "(微信)" , 'qqpay' => '(QQ支付)','alipay' => "(支付宝)"][$args['type']]); - return json_encode(['errcode'=>0]); + self::postPayment($invoiceid, "黛米付" . ['wepay' => "(微信)", 'qqpay' => '(QQ支付)', 'alipay' => "(支付宝)"][$args['type']]); + return json_encode(['errcode' => 0]); } else { return 1; } @@ -53,11 +53,11 @@ class DoiAMPay extends AbstractPayment { $type = $request->getParam('type'); $price = $request->getParam('price'); - if(Config::get("doiampay")['enabled'][$type]==0){ - return json_encode(['errcode'=>-1,'errmsg'=>"非法的支付方式."]); + if (Config::get("doiampay")['enabled'][$type] == 0) { + return json_encode(['errcode' => -1, 'errmsg' => "非法的支付方式."]); } - if($price <= 0){ - return json_encode(['errcode'=>-1,'errmsg'=>"非法的金额."]); + if ($price <= 0) { + return json_encode(['errcode' => -1, 'errmsg' => "非法的金额."]); } $user = Auth::getUser(); $settings = Config::get("doiampay")['mchdata'][$type]; @@ -71,20 +71,20 @@ class DoiAMPay extends AbstractPayment 'price' => $price, 'phone' => $settings['phone'], 'mchid' => $settings['mchid'], - 'subject' => Config::get("appName")."充值".$price."元", - 'body' => Config::get("appName")."充值".$price."元", + 'subject' => Config::get("appName") . "充值" . $price . "元", + 'body' => Config::get("appName") . "充值" . $price . "元", 'type' => 'Mod', ]; - $data = DoiAM::sign($data,$settings['token']); - $ret = DoiAM::post("https://api.daimiyun.cn/v2/".$type."/create",$data); - $result = json_decode($ret,true); - if($result and $result['errcode']==0){ - $result['pid']=$pl->tradeno; + $data = DoiAM::sign($data, $settings['token']); + $ret = DoiAM::post("https://api.daimiyun.cn/v2/" . $type . "/create", $data); + $result = json_decode($ret, true); + if ($result and $result['errcode'] == 0) { + $result['pid'] = $pl->tradeno; return json_encode($result); } else { return json_encode([ 'errcode' => -1, - 'errmsg' => "接口调用失败!".$ret, + 'errmsg' => "接口调用失败!" . $ret, ]); } return json_encode($result); @@ -114,36 +114,46 @@ HTML; } -class DoiAM{ - public static function sort(&$array){ +class DoiAM +{ + public static function sort(&$array) + { ksort($array); } - public static function getsign($array,$key){ + + public static function getsign($array, $key) + { unset($array['sign']); self::sort($array); - $sss=http_build_query($array); - $sign=hash("sha256",$sss.$key); - $sign=sha1($sign.hash("sha256",$key)); + $sss = http_build_query($array); + $sign = hash("sha256", $sss . $key); + $sign = sha1($sign . hash("sha256", $key)); return $sign; } - public static function sign($array,$key){ - $array['sign']=self::getSign($array,$key); + + public static function sign($array, $key) + { + $array['sign'] = self::getSign($array, $key); return $array; } - public static function checksign($array,$key){ + + public static function checksign($array, $key) + { $new = $array; - $new=self::sign($new,$key); - if(!isset($array['sign'])){ + $new = self::sign($new, $key); + if (!isset($array['sign'])) { return false; } - return $array['sign']==$new['sign']; + return $array['sign'] == $new['sign']; } - public static function post($url, $data = null){ + + public static function post($url, $data = null) + { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); - if (!empty($data)){ + if (!empty($data)) { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } diff --git a/app/Services/Gateway/PaymentWall.php b/app/Services/Gateway/PaymentWall.php index 5b20bc88..ccbc8e85 100644 --- a/app/Services/Gateway/PaymentWall.php +++ b/app/Services/Gateway/PaymentWall.php @@ -7,6 +7,7 @@ */ namespace App\Services\Gateway; + use App\Models\User; use App\Models\Code; use App\Services\Auth; @@ -24,7 +25,7 @@ class PaymentWall extends AbstractPayment public function notify($request, $response, $args) { - if (Config::get('pmw_publickey')!="") { + if (Config::get('pmw_publickey') != "") { \Paymentwall_Config::getInstance()->set(array( 'api_type' => \Paymentwall_Config::API_VC, 'public_key' => Config::get('pmw_publickey'), @@ -38,35 +39,35 @@ class PaymentWall extends AbstractPayment } elseif ($pingback->isCancelable()) { // withdraw the virual currency } - $user=User::find($pingback->getUserId()); - $user->money=$user->money+$pingback->getVirtualCurrencyAmount(); + $user = User::find($pingback->getUserId()); + $user->money = $user->money + $pingback->getVirtualCurrencyAmount(); $user->save(); - $codeq=new Code(); - $codeq->code="Payment Wall 充值"; - $codeq->isused=1; - $codeq->type=-1; - $codeq->number=$pingback->getVirtualCurrencyAmount(); - $codeq->usedatetime=date("Y-m-d H:i:s"); - $codeq->userid=$user->id; + $codeq = new Code(); + $codeq->code = "Payment Wall 充值"; + $codeq->isused = 1; + $codeq->type = -1; + $codeq->number = $pingback->getVirtualCurrencyAmount(); + $codeq->usedatetime = date("Y-m-d H:i:s"); + $codeq->userid = $user->id; $codeq->save(); - if ($user->ref_by!=""&&$user->ref_by!=0&&$user->ref_by!=null) { - $gift_user=User::where("id", "=", $user->ref_by)->first(); - $gift_user->money=($gift_user->money+($codeq->number*(Config::get('code_payback')/100))); + if ($user->ref_by != "" && $user->ref_by != 0 && $user->ref_by != null) { + $gift_user = User::where("id", "=", $user->ref_by)->first(); + $gift_user->money = ($gift_user->money + ($codeq->number * (Config::get('code_payback') / 100))); $gift_user->save(); - $Payback=new Payback(); - $Payback->total=$pingback->getVirtualCurrencyAmount(); - $Payback->userid=$user->id; - $Payback->ref_by=$user->ref_by; - $Payback->ref_get=$codeq->number*(Config::get('code_payback')/100); - $Payback->datetime=time(); + $Payback = new Payback(); + $Payback->total = $pingback->getVirtualCurrencyAmount(); + $Payback->userid = $user->id; + $Payback->ref_by = $user->ref_by; + $Payback->ref_get = $codeq->number * (Config::get('code_payback') / 100); + $Payback->datetime = time(); $Payback->save(); } echo 'OK'; // Paymentwall expects response to be OK, otherwise the pingback will be resent if (Config::get('enable_donate') == 'true') { if ($user->is_hide == 1) { - Telegram::Send("姐姐姐姐,一位不愿透露姓名的大老爷给我们捐了 ".$codeq->number." 元呢~"); + Telegram::Send("姐姐姐姐,一位不愿透露姓名的大老爷给我们捐了 " . $codeq->number . " 元呢~"); } else { - Telegram::Send("姐姐姐姐,".$user->user_name." 大老爷给我们捐了 ".$codeq->number." 元呢~"); + Telegram::Send("姐姐姐姐," . $user->user_name . " 大老爷给我们捐了 " . $codeq->number . " 元呢~"); } } } else { @@ -92,18 +93,18 @@ class PaymentWall extends AbstractPayment array(), // array of products - leave blank for Virtual Currency API array( 'email' => $user->email, - 'history'=> + 'history' => array( - 'registration_date'=>strtotime($user->reg_date), - 'registration_ip'=>$user->reg_ip, - 'payments_number'=>Code::where('userid', '=', $user->id)->where('type', '=', -1)->count(), - 'membership'=>$user->class), - 'customer'=>array( - 'username'=>$user->user_name + 'registration_date' => strtotime($user->reg_date), + 'registration_ip' => $user->reg_ip, + 'payments_number' => Code::where('userid', '=', $user->id)->where('type', '=', -1)->count(), + 'membership' => $user->class), + 'customer' => array( + 'username' => $user->user_name ) ) // additional parameters ); - return $widget->getHtmlCode(array("height"=>Config::get('pmw_height'),"width"=>"100%")); + return $widget->getHtmlCode(array("height" => Config::get('pmw_height'), "width" => "100%")); } public function getReturnHTML($request, $response, $args) diff --git a/app/Services/Gateway/SPay.php b/app/Services/Gateway/SPay.php index 286c9ea9..9cf1ab79 100755 --- a/app/Services/Gateway/SPay.php +++ b/app/Services/Gateway/SPay.php @@ -7,6 +7,7 @@ */ namespace App\Services\Gateway; + use App\Services\View; use App\Services\Auth; use App\Services\Config; @@ -24,7 +25,7 @@ class SPay extends AbstractPayment $pl = new Paylist(); $pl->userid = $user->id; //if ($amount <= '10') { - //$amount='10'; + //$amount='10'; //} $pl->total = $amount; $pl->tradeno = self::generateGuid(); @@ -32,55 +33,65 @@ class SPay extends AbstractPayment //商户订单号,商户网站订单系统中唯一订单号,必填 $out_trade_no = $pl->tradeno; //订单名称,必填 - $subject = $pl->id."UID:".$user->id." 充值".$amount."元"; + $subject = $pl->id . "UID:" . $user->id . " 充值" . $amount . "元"; //付款金额,必填 $total_fee = (float)$amount; //商品描述,可空 $body = $user->id; /************************************************************/ - - + + $data['total_fee'] = $total_fee; //支付金额 - $data['partner']= Config::get('alipay_id'); //spay合作者id - $data['notify_url']= Config::get('baseUrl')."/spay_back"; //不能有get参数 也就是?xxx=xxx& xxx=xxx - $data['return_url']= Config::get('baseUrl')."/spay_back"; //不能有get参数 也就是?xxx=xxx& xxx=xxx - $data['out_trade_no']= $out_trade_no; //商户唯一订单号 - $data['service'] = 'create_direct_pay_by_user'; - $i=0; $jk=''; - ksort($data); - reset($data); - $ii=count($data); - foreach($data as $as1=>$as2){$i++;$jk .= $as1."=".$as2;if($ii!=$i)$jk .="&";} - $data['sign']=md5($jk.Config::get('alipay_key')); + $data['partner'] = Config::get('alipay_id'); //spay合作者id + $data['notify_url'] = Config::get('baseUrl') . "/spay_back"; //不能有get参数 也就是?xxx=xxx& xxx=xxx + $data['return_url'] = Config::get('baseUrl') . "/spay_back"; //不能有get参数 也就是?xxx=xxx& xxx=xxx + $data['out_trade_no'] = $out_trade_no; //商户唯一订单号 + $data['service'] = 'create_direct_pay_by_user'; + $i = 0; + $jk = ''; + ksort($data); + reset($data); + $ii = count($data); + foreach ($data as $as1 => $as2) { + $i++; + $jk .= $as1 . "=" . $as2; + if ($ii != $i) $jk .= "&"; + } + $data['sign'] = md5($jk . Config::get('alipay_key')); //header("Location: http://www.dayyun.com/pay/pay/alipay.php?".http_build_query($data)); - - - return json_encode(['code'=>0, 'url'=>"http://www.dayyun.com/pay/pay/alipay.php?".http_build_query($data)]); + + + return json_encode(['code' => 0, 'url' => "http://www.dayyun.com/pay/pay/alipay.php?" . http_build_query($data)]); } - + public function notify($request, $response, $args) { $data = $_GET; - $ispost=0; - if(empty($data['out_trade_no'])){ - $data= $_POST; - $ispost=1; + $ispost = 0; + if (empty($data['out_trade_no'])) { + $data = $_POST; + $ispost = 1; } //判断是同步通知还是异步通知 并赋值校验签名 - if(empty($data['out_trade_no'])) die(time()); - - $i=0; $jk=''; - ksort($data); - reset($data); - $sign=$data['sign']; - unset($data['sign']); - unset($data['sign_type']); - $ii=count($data); - foreach($data as $as1=>$as2){$i++;$jk .= $as1."=".$as2;if($ii!=$i)$jk .="&";} - $newsign=md5($jk.Config::get('alipay_key')); - if ($newsign != $sign) die('false'); + if (empty($data['out_trade_no'])) die(time()); + + $i = 0; + $jk = ''; + ksort($data); + reset($data); + $sign = $data['sign']; + unset($data['sign']); + unset($data['sign_type']); + $ii = count($data); + foreach ($data as $as1 => $as2) { + $i++; + $jk .= $as1 . "=" . $as2; + if ($ii != $i) $jk .= "&"; + } + $newsign = md5($jk . Config::get('alipay_key')); + if ($newsign != $sign) die('false'); $this->postPayment($data['out_trade_no'], "SPay 支付"); echo 'success'; - if($ispost==0) header("Location: /user/code"); + if ($ispost == 0) header("Location: /user/code"); } public function getPurchaseHTML() diff --git a/app/Services/Gateway/SPay/Spay_notify.php b/app/Services/Gateway/SPay/Spay_notify.php index 5119f719..5aa508d3 100755 --- a/app/Services/Gateway/SPay/Spay_notify.php +++ b/app/Services/Gateway/SPay/Spay_notify.php @@ -9,10 +9,12 @@ class Spay_notify { $this->alipay_config = $alipay_config; } + public static function Spay_notify($alipay_config) { self::__construct($alipay_config); } + /** * 针对notify_url验证消息是否是支付宝发出的合法消息 * @return 验证结果 @@ -24,8 +26,8 @@ class Spay_notify } else { //生成签名结果 $isSign = $this->getSignVeryfy($_POST, $_POST["sign"]); - - + + //写日志记录 //if ($isSign) { // $isSignStr = 'true'; @@ -36,7 +38,7 @@ class Spay_notify //$log_text = "responseTxt=".$responseTxt."\n notify_url_log:isSign=".$isSignStr.","; //$log_text = $log_text.Spay_tool::createLinkstring($_POST); //Spay_tool::logResult($log_text); - + //验证 //$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关 //isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关 @@ -47,7 +49,7 @@ class Spay_notify } } } - + /** * 针对return_url验证消息是否是支付宝发出的合法消息 * @return 验证结果 @@ -60,7 +62,7 @@ class Spay_notify //生成签名结果 $isSign = $this->getSignVeryfy($_GET, $_GET["sign"]); //获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息) - + //写日志记录 //if ($isSign) { // $isSignStr = 'true'; @@ -71,7 +73,7 @@ class Spay_notify //$log_text = "responseTxt=".$responseTxt."\n return_url_log:isSign=".$isSignStr.","; //$log_text = $log_text.Spay_tool::createLinkstring($_GET); //Spay_tool::logResult($log_text); - + //验证 //$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关 //isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关 @@ -82,7 +84,7 @@ class Spay_notify } } } - + /** * 获取返回时的签名验证结果 * @param $para_temp 通知返回来的参数数组 @@ -93,15 +95,15 @@ class Spay_notify { //除去待签名参数数组中的空值和签名参数 $para_filter = Spay_tool::paraFilter($para_temp); - + //对待签名参数数组排序 $para_sort = Spay_tool::argSort($para_filter); - + //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 $prestr = Spay_tool::createLinkstring($para_sort); - + $isSgin = false; - + return Spay_tool::md5Verify($prestr, $sign, $this->alipay_config['key']); } @@ -115,9 +117,9 @@ class Spay_notify public function getResponse($notify_id) { $veryfy_url = $this->http_verify_url; - $veryfy_url = $veryfy_url."notify_id=" . $notify_id; + $veryfy_url = $veryfy_url . "notify_id=" . $notify_id; $responseTxt = Spay_tool::getHttpResponseGET($veryfy_url); - + return $responseTxt; } } diff --git a/app/Services/Gateway/SPay/Spay_submit.php b/app/Services/Gateway/SPay/Spay_submit.php index 6c933640..9032a205 100755 --- a/app/Services/Gateway/SPay/Spay_submit.php +++ b/app/Services/Gateway/SPay/Spay_submit.php @@ -10,11 +10,12 @@ class Spay_submit { $this->alipay_config = $alipay_config; } + public static function Spay_submit($alipay_config) { self::__construct($alipay_config); } - + /** * 生成签名结果 * @param $para_sort 已排序要签名的数组 @@ -42,11 +43,11 @@ class Spay_submit //生成签名结果 $mysign = $this->buildRequestMysign($para_sort); - + //签名结果与签名方式加入请求提交参数组中 $para_sort['sign'] = $mysign; $para_sort['sign_type'] = "MD5"; - + return $para_sort; } @@ -59,13 +60,13 @@ class Spay_submit { //待请求参数数组 $para = $this->buildRequestPara($para_temp); - + //把参数组中所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对字符串做urlencode编码 $request_data = Spay_tool::createLinkstringUrlencode($para); - + return $request_data; } - + /** * 建立请求,以表单HTML形式构造(默认) * @param $para_temp 请求参数数组 diff --git a/app/Services/Gateway/SPay/Spay_tool.php b/app/Services/Gateway/SPay/Spay_tool.php index 61c57b43..74d51689 100644 --- a/app/Services/Gateway/SPay/Spay_tool.php +++ b/app/Services/Gateway/SPay/Spay_tool.php @@ -41,6 +41,7 @@ class Spay_tool return false; } } + /** * 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 * @param $para 需要拼接的数组 @@ -48,20 +49,21 @@ class Spay_tool */ public static function createLinkstring($para) { - $arg = ""; + $arg = ""; while (list($key, $val) = each($para)) { - $arg.=$key."=".$val."&"; + $arg .= $key . "=" . $val . "&"; } //去掉最后一个&字符 - $arg = substr($arg, 0, strlen($arg)-1); - + $arg = substr($arg, 0, strlen($arg) - 1); + //如果存在转义字符,那么去掉转义 if (get_magic_quotes_gpc()) { $arg = stripslashes($arg); } - + return $arg; } + /** * 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对字符串做urlencode编码 * @param $para 需要拼接的数组 @@ -69,20 +71,21 @@ class Spay_tool */ public static function createLinkstringUrlencode($para) { - $arg = ""; + $arg = ""; while (list($key, $val) = each($para)) { - $arg.=$key."=".urlencode($val)."&"; + $arg .= $key . "=" . urlencode($val) . "&"; } //去掉最后一个&字符 - $arg = substr($arg, 0, count($arg)-2); - + $arg = substr($arg, 0, count($arg) - 2); + //如果存在转义字符,那么去掉转义 if (get_magic_quotes_gpc()) { $arg = stripslashes($arg); } - + return $arg; } + /** * 除去数组中的空值和签名参数 * @param $para 签名参数组 @@ -100,6 +103,7 @@ class Spay_tool } return $para_filter; } + /** * 对数组排序 * @param $para 排序前的数组 @@ -111,16 +115,17 @@ class Spay_tool reset($para); return $para; } + /** * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库) * 注意:服务器需要开通fopen配置 * @param $word 要写入日志里的文本内容 默认值:空值 */ - public static function logResult($word='') + public static function logResult($word = '') { - $fp = fopen(BASE_PATH."/storage/log.txt", "a"); - flock($fp, LOCK_EX) ; - fwrite($fp, "执行日期:".strftime("%Y%m%d%H%M%S", time())."\n".$word."\n"); + $fp = fopen(BASE_PATH . "/storage/log.txt", "a"); + flock($fp, LOCK_EX); + fwrite($fp, "执行日期:" . strftime("%Y%m%d%H%M%S", time()) . "\n" . $word . "\n"); flock($fp, LOCK_UN); fclose($fp); } @@ -144,7 +149,7 @@ class Spay_tool $responseText = curl_exec($curl); //var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容 curl_close($curl); - + return $responseText; } @@ -159,9 +164,9 @@ class Spay_tool { $output = ""; if (!isset($_output_charset)) { - $_output_charset = $_input_charset; + $_output_charset = $_input_charset; } - if ($_input_charset == $_output_charset || $input ==null) { + if ($_input_charset == $_output_charset || $input == null) { $output = $input; } elseif (function_exists("mb_convert_encoding")) { $output = mb_convert_encoding($input, $_output_charset, $_input_charset); @@ -172,6 +177,7 @@ class Spay_tool } return $output; } + /** * 实现多种字符解码方式 * @param $input 需要解码的字符串 @@ -183,9 +189,9 @@ class Spay_tool { $output = ""; if (!isset($_input_charset)) { - $_input_charset = $_input_charset ; + $_input_charset = $_input_charset; } - if ($_input_charset == $_output_charset || $input ==null) { + if ($_input_charset == $_output_charset || $input == null) { $output = $input; } elseif (function_exists("mb_convert_encoding")) { $output = mb_convert_encoding($input, $_output_charset, $_input_charset); @@ -196,59 +202,59 @@ class Spay_tool } return $output; } - + public static function getConfig() { $alipay_config = array(); - + $alipay_config['partner'] = Config::get('alipay_id'); - + //收款支付宝账号,以2088开头由16位纯数字组成的字符串,一般情况下收款账号就是签约账号 $alipay_config['seller_id'] = $alipay_config['partner']; - + // MD5密钥,安全检验码,由数字和字母组成的32位字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm $alipay_config['key'] = Config::get('alipay_key'); - + // 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 - $alipay_config['notify_url'] = Config::get('baseUrl')."/purchase/notify"; - + $alipay_config['notify_url'] = Config::get('baseUrl') . "/purchase/notify"; + // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 - + //此处请填 访问地址+"/user/code" - $alipay_config['return_url'] = Config::get('baseUrl')."/user/code"; - + $alipay_config['return_url'] = Config::get('baseUrl') . "/user/code"; + //签名方式 - $alipay_config['sign_type'] = strtoupper('MD5'); - + $alipay_config['sign_type'] = strtoupper('MD5'); + //字符编码格式 目前支持 gbk 或 utf-8 - $alipay_config['input_charset']= strtolower('utf-8'); - + $alipay_config['input_charset'] = strtolower('utf-8'); + //ca证书路径地址,用于curl中ssl校验 //请保证cacert.pem文件在当前文件夹目录中 - $alipay_config['cacert'] = ""; - + $alipay_config['cacert'] = ""; + //访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http - $alipay_config['transport'] = 'http'; - + $alipay_config['transport'] = 'http'; + // 支付类型 ,无需修改 $alipay_config['payment_type'] = "1"; - + // 产品类型,无需修改 $alipay_config['service'] = "create_direct_pay_by_user"; - + //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ - - + + //↓↓↓↓↓↓↓↓↓↓ 请在这里配置防钓鱼信息,如果没开通防钓鱼功能,为空即可 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ - + // 防钓鱼时间戳 若要使用请调用类文件submit中的query_timestamp函数 $alipay_config['anti_phishing_key'] = ""; - + // 客户端的IP地址 非局域网的外网IP地址,如:221.0.0.1 $alipay_config['exter_invoke_ip'] = ""; - + //↑↑↑↑↑↑↑↑↑↑请在这里配置防钓鱼信息,如果没开通防钓鱼功能,为空即可 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ - + return $alipay_config; } } diff --git a/app/Services/Gateway/TomatoPay.php b/app/Services/Gateway/TomatoPay.php index 60ea3f15..39014dc8 100644 --- a/app/Services/Gateway/TomatoPay.php +++ b/app/Services/Gateway/TomatoPay.php @@ -1,9 +1,12 @@ getParam('type'); $price = $request->getParam('price'); - if($price <= 0){ - return json_encode(['errcode'=>-1,'errmsg'=>"非法的金额."]); + if ($price <= 0) { + return json_encode(['errcode' => -1, 'errmsg' => "非法的金额."]); } $user = Auth::getUser(); $settings = Config::get("tomatopay")[$type]; @@ -21,59 +24,59 @@ class TomatoPay extends AbstractPayment $pl->total = $price; $pl->tradeno = self::generateGuid(); $pl->save(); - $fqaccount=$settings['account']; - $fqkey=$settings['token']; + $fqaccount = $settings['account']; + $fqkey = $settings['token']; $fqmchid = $settings['mchid']; - $fqtype = 1; - $fqtrade = $pl->tradeno; - $fqcny = $price; + $fqtype = 1; + $fqtrade = $pl->tradeno; + $fqcny = $price; $data = [ 'account' => $settings['account'], - 'mchid' => $settings['mchid'], - 'type' => 1, - 'trade' => $pl->tradeno, - 'cny' => $price, + 'mchid' => $settings['mchid'], + 'type' => 1, + 'trade' => $pl->tradeno, + 'cny' => $price, ]; - $signs = md5("mchid=".$fqmchid."&account=".$fqaccount."&cny=".$fqcny."&type=1&trade=".$fqtrade.$fqkey); - $url="https://b.fanqieui.com/gateways/".$type.".php?account=".$fqaccount."&mchid=".$fqmchid."&type=".$fqtype."&trade=".$fqtrade."&cny=".$fqcny."&signs=".$signs; - $result = ""; - $result = json_encode(array('code'=>$result,'errcode'=>0,'pid' =>$pl->id)); + $signs = md5("mchid=" . $fqmchid . "&account=" . $fqaccount . "&cny=" . $fqcny . "&type=1&trade=" . $fqtrade . $fqkey); + $url = "https://b.fanqieui.com/gateways/" . $type . ".php?account=" . $fqaccount . "&mchid=" . $fqmchid . "&type=" . $fqtype . "&trade=" . $fqtrade . "&cny=" . $fqcny . "&signs=" . $signs; + $result = ""; + $result = json_encode(array('code' => $result, 'errcode' => 0, 'pid' => $pl->id)); return $result; } - + public function notify($request, $response, $args) { - $type = $args['type']; - $settings = Config::get("tomatopay")[$type]; - $order_data = $_REQUEST; - $transid = $order_data['trade_no']; //转账交易号 - $invoiceid = $order_data['out_trade_no']; //订单号 - $amount = $order_data['total_fee']; //获取递过来的总价格 - $status = $order_data['trade_status']; //获取传递过来的交易状态 - $signs = $order_data['sign']; - - $security = array(); - $security['out_trade_no'] = $invoiceid; - $security['total_fee'] = $amount; - $security['trade_no'] = $transid; - $security['trade_status'] = $status; -foreach ($security as $k=>$v) -{ - $o.= "$k=".urlencode($v)."&"; -} -$sign = md5(substr($o,0,-1).$settings['token']); + $type = $args['type']; + $settings = Config::get("tomatopay")[$type]; + $order_data = $_REQUEST; + $transid = $order_data['trade_no']; //转账交易号 + $invoiceid = $order_data['out_trade_no']; //订单号 + $amount = $order_data['total_fee']; //获取递过来的总价格 + $status = $order_data['trade_status']; //获取传递过来的交易状态 + $signs = $order_data['sign']; + $security = array(); + $security['out_trade_no'] = $invoiceid; + $security['total_fee'] = $amount; + $security['trade_no'] = $transid; + $security['trade_status'] = $status; + foreach ($security as $k => $v) { + $o .= "$k=" . urlencode($v) . "&"; + } + $sign = md5(substr($o, 0, -1) . $settings['token']); + + + if ($sign == $signs) { + $this->postPayment($order_data['out_trade_no'], "在线支付"); + echo 'success'; + if ($ispost == 0) header("Location: /user/code"); - if ($sign == $signs) { - $this->postPayment($order_data['out_trade_no'], "在线支付"); - echo 'success'; - if($ispost==0) header("Location: /user/code"); - - }else{ - echo '验证失败'; + } else { + echo '验证失败'; } } + public function getPurchaseHTML() { return ' @@ -151,10 +154,12 @@ $sign = md5(substr($o,0,-1).$settings['token']); '; } + public function getReturnHTML($request, $response, $args) { } + public function getStatus($request, $response, $args) { // TODO: Implement getStatus() method. diff --git a/app/Services/Gateway/TrimePay.php b/app/Services/Gateway/TrimePay.php index 45f10cd6..d48894ad 100644 --- a/app/Services/Gateway/TrimePay.php +++ b/app/Services/Gateway/TrimePay.php @@ -7,6 +7,7 @@ */ namespace App\Services\Gateway; + use App\Services\View; use App\Services\Auth; use App\Services\Config; @@ -17,32 +18,36 @@ class TrimePay extends AbstractPayment private $appSecret; private $gatewayUri; + /** * 签名初始化 - * @param merKey 签名密钥 + * @param merKey 签名密钥 */ - public function __construct($appSecret) { + public function __construct($appSecret) + { $this->appSecret = $appSecret; $this->gatewayUri = 'https://api.Trimepay.com/gateway/'; } /** - * @name 准备签名/验签字符串 + * @name 准备签名/验签字符串 */ - public function prepareSign($data) { + public function prepareSign($data) + { ksort($data); return http_build_query($data); } /** - * @name 生成签名 - * @param sourceData - * @return 签名数据 + * @name 生成签名 + * @param sourceData + * @return 签名数据 */ - public function sign($data) { - $signature = strtolower(md5(md5($data).$this->appSecret)); + public function sign($data) + { + $signature = strtolower(md5(md5($data) . $this->appSecret)); return $signature; } @@ -52,7 +57,8 @@ class TrimePay extends AbstractPayment * @param sourceData 原数据 * @return */ - public function verify($data, $signature) { + public function verify($data, $signature) + { $mySign = $this->sign($data); if ($mySign === $signature) { return true; @@ -61,12 +67,13 @@ class TrimePay extends AbstractPayment } } - public function post($data, $type = "pay"){ - if ($type == "pay"){ + public function post($data, $type = "pay") + { + if ($type == "pay") { $this->gatewayUri .= "pay/go"; } else if ($type == "refund") { $this->gatewayUri .= "refund/go"; - } else if ($type == "pre"){ + } else if ($type == "pre") { $this->gatewayUri .= "pay/pre"; } else { $this->gatewayUri .= "query/go"; @@ -86,15 +93,14 @@ class TrimePay extends AbstractPayment } - public function purchase($request, $response, $args) { $price = $request->getParam('price'); $type = $request->getParam('type'); - if($price <= 0){ - return json_encode(['code'=>-1,'errmsg'=>"非法的金额."]); + if ($price <= 0) { + return json_encode(['code' => -1, 'errmsg' => "非法的金额."]); } $user = Auth::getUser(); $pl = new Paylist(); @@ -108,8 +114,8 @@ class TrimePay extends AbstractPayment $data['payType'] = $type; $data['merchantTradeNo'] = $pl->tradeno; $data['totalFee'] = (float)$price * 100; - $data['notifyUrl'] = Config::get("baseUrl")."/payment/notify"; - $data['returnUrl'] = Config::get("baseUrl")."/user/payment/return"; + $data['notifyUrl'] = Config::get("baseUrl") . "/payment/notify"; + $data['returnUrl'] = Config::get("baseUrl") . "/user/payment/return"; $params = self::prepareSign($data); $data['sign'] = self::sign($params); switch ($type) { @@ -123,7 +129,8 @@ class TrimePay extends AbstractPayment return json_encode($result); } - public function query($tradeNo){ + public function query($tradeNo) + { $data['appId'] = Config::get('trimepay_appid'); $data['merchantTradeNo'] = $tradeNo; $params = self::prepareSign($data); @@ -135,11 +142,11 @@ class TrimePay extends AbstractPayment public function notify($request, $response, $args) { $data = array(); - $data['payStatus']=$request->getParam('payStatus'); - $data['payFee']=$request->getParam('payFee'); - $data['callbackTradeNo']=$request->getParam('callbackTradeNo'); - $data['payType']=$request->getParam('payType'); - $data['merchantTradeNo']=$request->getParam('merchantTradeNo'); + $data['payStatus'] = $request->getParam('payStatus'); + $data['payFee'] = $request->getParam('payFee'); + $data['callbackTradeNo'] = $request->getParam('callbackTradeNo'); + $data['payType'] = $request->getParam('payType'); + $data['merchantTradeNo'] = $request->getParam('merchantTradeNo'); //file_put_contents(BASE_PATH.'/storage/trimepay_notify.log', json_encode($data)."\r\n", FILE_APPEND); // 准备待签名数据 @@ -150,12 +157,13 @@ class TrimePay extends AbstractPayment //file_put_contents('./trimepay_notify_success.log', json_encode($data)."\r\n", FILE_APPEND); self::postPayment($data['merchantTradeNo'], "TrimePay"); echo 'SUCCESS'; - }else{ + } else { echo 'FAIL'; } } - public function refund($merchantTradeNo){ + public function refund($merchantTradeNo) + { $data['appId'] = Config::get('trimepay_appid'); $data['merchantTradeNo'] = $merchantTradeNo; $params = self::prepareSign($data); @@ -173,17 +181,17 @@ class TrimePay extends AbstractPayment public function getReturnHTML($request, $response, $args) { $pid = $_GET['merchantTradeNo']; - $p = Paylist::where('tradeno','=',$pid)->first(); + $p = Paylist::where('tradeno', '=', $pid)->first(); $money = $p->total; - if ($p->status == 1){ + if ($p->status == 1) { $success = 1; } else { $data = array(); - $data['payStatus']=$request->getParam('payStatus'); - $data['payFee']=$request->getParam('payFee'); - $data['callbackTradeNo']=$request->getParam('callbackTradeNo'); - $data['payType']=$request->getParam('payType'); - $data['merchantTradeNo']=$request->getParam('merchantTradeNo'); + $data['payStatus'] = $request->getParam('payStatus'); + $data['payFee'] = $request->getParam('payFee'); + $data['callbackTradeNo'] = $request->getParam('callbackTradeNo'); + $data['payType'] = $request->getParam('payType'); + $data['merchantTradeNo'] = $request->getParam('merchantTradeNo'); // 准备待签名数据 $str_to_sign = self::prepareSign($data); // 验证签名 diff --git a/app/Services/Gateway/YftPay.php b/app/Services/Gateway/YftPay.php index cc9f1979..11175d24 100755 --- a/app/Services/Gateway/YftPay.php +++ b/app/Services/Gateway/YftPay.php @@ -59,8 +59,8 @@ class YftPay extends AbstractPayment if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } - $orderList = YftOrder::where("price",">=", 0)->orderBy("id", "asc")->paginate(15, ['*'], 'page', $pageNum); - $count = sizeof(YftOrder::where("price",">=", 0)->get()); + $orderList = YftOrder::where("price", ">=", 0)->orderBy("id", "asc")->paginate(15, ['*'], 'page', $pageNum); + $count = sizeof(YftOrder::where("price", ">=", 0)->get()); $countPage = ceil($count / 15); $orderList->setPath('/admin/yftOrder'); @@ -231,9 +231,9 @@ class YftPay extends AbstractPayment $accesskey = Config::get('yft_accesskey'); //生成订单号 - // 密码字符集,可任意添加你需要的字符 + // 密码字符集,可任意添加你需要的字符 $date = time(); - $date = "yft".date("YmdHis",$date); + $date = "yft" . date("YmdHis", $date); $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $password = ""; for ($i = 0; $i < 8; $i++) { @@ -242,7 +242,7 @@ class YftPay extends AbstractPayment // 第二种是取字符数组 $chars 的任意元素 $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } - $ss_order_no = $date.$password; + $ss_order_no = $date . $password; /************************************************************/ //构造要请求的参数数组,无需改动 diff --git a/app/Services/Gateway/YftPayConfig.php b/app/Services/Gateway/YftPayConfig.php index f67e7c65..755a421f 100644 --- a/app/Services/Gateway/YftPayConfig.php +++ b/app/Services/Gateway/YftPayConfig.php @@ -2,7 +2,8 @@ namespace App\Services\Gateway; -class YftPayConfig{ +class YftPayConfig +{ public $pay_config; diff --git a/app/Services/Jwt.php b/app/Services/Jwt.php index 99324af2..ca722137 100644 --- a/app/Services/Jwt.php +++ b/app/Services/Jwt.php @@ -15,7 +15,7 @@ class Jwt { return JwtClient::encode($input, self::getKey()); } - + public static function encode_withkey($input, $key) { return JwtClient::encode($input, $key); diff --git a/app/Services/Mail/Mailgun.php b/app/Services/Mail/Mailgun.php index 2743a866..d9f17263 100644 --- a/app/Services/Mail/Mailgun.php +++ b/app/Services/Mail/Mailgun.php @@ -31,28 +31,27 @@ class Mailgun extends Base public function send($to, $subject, $text, $files) { - $inline=array(); - foreach($files as $file){ - array_push($inline,array('filePath'=>$file, 'filename'=>basename($file))); - } - if(count($inline)==0){ - $this->mg->messages()->send($this->domain,[ - 'from' => $this->sender, - 'to' => $to, - 'subject' => $subject, - 'html' => $text - ] - ); - } - else{ - $this->mg->messages()->send($this->domain,[ - 'from' => $this->sender, - 'to' => $to, - 'subject' => $subject, - 'html' => $text, - 'inline' => $inline - ] - ); - } + $inline = array(); + foreach ($files as $file) { + array_push($inline, array('filePath' => $file, 'filename' => basename($file))); + } + if (count($inline) == 0) { + $this->mg->messages()->send($this->domain, [ + 'from' => $this->sender, + 'to' => $to, + 'subject' => $subject, + 'html' => $text + ] + ); + } else { + $this->mg->messages()->send($this->domain, [ + 'from' => $this->sender, + 'to' => $to, + 'subject' => $subject, + 'html' => $text, + 'inline' => $inline + ] + ); + } } } diff --git a/app/Services/Mail/SendGrid.php b/app/Services/Mail/SendGrid.php index 6f836e16..56d0d2fe 100644 --- a/app/Services/Mail/SendGrid.php +++ b/app/Services/Mail/SendGrid.php @@ -42,7 +42,7 @@ class SendGrid extends Base $attachment->setContentId("backup"); $mail->addAttachment($attachment); } - + $response = $this->sg->client->mail()->send()->post($mail); echo $response->body(); } diff --git a/app/Services/Mail/Smtp.php b/app/Services/Mail/Smtp.php index 896156c7..bb7a14fd 100644 --- a/app/Services/Mail/Smtp.php +++ b/app/Services/Mail/Smtp.php @@ -21,9 +21,9 @@ class Smtp extends Base $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $this->config['username']; // SMTP username $mail->Password = $this->config['passsword']; // SMTP password - if (Config::get('smtp_ssl') == 'true') { - $mail->SMTPSecure = (Config::get('smtp_port') =='587'?'tls':'ssl'); // Enable TLS encryption, `ssl` also accepted - } + if (Config::get('smtp_ssl') == 'true') { + $mail->SMTPSecure = (Config::get('smtp_port') == '587' ? 'tls' : 'ssl'); // Enable TLS encryption, `ssl` also accepted + } $mail->Port = $this->config['port']; // TCP port to connect to $mail->setFrom($this->config['sender'], $this->config['name']); $mail->CharSet = 'UTF-8'; diff --git a/app/Services/Payment.php b/app/Services/Payment.php index 035f003a..3962bcf6 100644 --- a/app/Services/Payment.php +++ b/app/Services/Payment.php @@ -15,12 +15,13 @@ use App\Services\Gateway\{ class Payment { - public static function getClient(){ + public static function getClient() + { $method = Config::get("payment_system"); - switch($method){ + switch ($method) { case("codepay"): return new Codepay(); - case("tomatopay"): + case("tomatopay"): return new TomatoPay(); case("doiampay"): return new DoiAMPay(); @@ -41,27 +42,32 @@ class Payment } } - public static function notify($request, $response, $args){ + public static function notify($request, $response, $args) + { return self::getClient()->notify($request, $response, $args); } - public static function returnHTML($request, $response, $args){ + public static function returnHTML($request, $response, $args) + { return self::getClient()->getReturnHTML($request, $response, $args); } - public static function purchaseHTML(){ - if (self::getClient() != NULL) { - return self::getClient()->getPurchaseHTML(); - } else { - return ''; - } + public static function purchaseHTML() + { + if (self::getClient() != NULL) { + return self::getClient()->getPurchaseHTML(); + } else { + return ''; + } } - public static function getStatus($request, $response, $args){ + public static function getStatus($request, $response, $args) + { return self::getClient()->getStatus($request, $response, $args); } - public static function purchase($request, $response, $args){ + public static function purchase($request, $response, $args) + { return self::getClient()->purchase($request, $response, $args); } } diff --git a/app/Services/RedisClient.php b/app/Services/RedisClient.php index 9e0816c5..dca0bfb1 100644 --- a/app/Services/RedisClient.php +++ b/app/Services/RedisClient.php @@ -13,9 +13,9 @@ class RedisClient { $config = [ 'scheme' => Config::get('redis_scheme'), -'password' => Config::get('redis_password'), - 'host' => Config::get('redis_host'), - 'port' => Config::get('redis_port'), + 'password' => Config::get('redis_password'), + 'host' => Config::get('redis_host'), + 'port' => Config::get('redis_port'), 'database' => Config::get('redis_database'), ]; $this->client = new Client($config); diff --git a/app/Services/Slim.php b/app/Services/Slim.php index 9f97c07e..ccd3eca1 100644 --- a/app/Services/Slim.php +++ b/app/Services/Slim.php @@ -14,7 +14,6 @@ use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware; /*** * The slim documents: http://www.slimframework.com/docs/objects/router.html */ - class Slim { public $app; @@ -30,7 +29,7 @@ class Slim // Make a Slim App $app = new App([ 'settings' => [ - 'debug' => $debug, + 'debug' => $debug, 'whoops.editor' => 'sublime', 'displayErrorDetails' => $debug ] diff --git a/app/Services/Token/Base.php b/app/Services/Token/Base.php index c8b818d2..89d71c0d 100644 --- a/app/Services/Token/Base.php +++ b/app/Services/Token/Base.php @@ -7,6 +7,8 @@ use App\Models\User; abstract class Base { abstract public function store($token, User $user, $expireTime); + abstract public function delete($token); + abstract public function get($token); } diff --git a/app/Services/Token/Dynamodb.php b/app/Services/Token/Dynamodb.php index 596d65a1..31c59816 100644 --- a/app/Services/Token/Dynamodb.php +++ b/app/Services/Token/Dynamodb.php @@ -22,9 +22,9 @@ class Dynamodb extends Base $result = $this->client->putItem(array( 'TableName' => $this->tableName, 'Item' => array( - 'token' => array('S' => $token), - 'user_id' => array('N' => (string)$user->id), - 'create_time' => array('N' => (string)time()), + 'token' => array('S' => $token), + 'user_id' => array('N' => (string)$user->id), + 'create_time' => array('N' => (string)time()), 'expire_time' => array('N' => (string)$expireTime) ) )); @@ -36,7 +36,7 @@ class Dynamodb extends Base $this->client->deleteItem(array( 'TableName' => $this->tableName, 'Key' => array( - 'token' => array('S' => $token), + 'token' => array('S' => $token), ) )); } @@ -46,8 +46,8 @@ class Dynamodb extends Base $result = $this->client->getItem(array( 'ConsistentRead' => true, 'TableName' => $this->tableName, - 'Key' => array( - 'token' => array('S' => $token), + 'Key' => array( + 'token' => array('S' => $token), ) )); $token = new Token(); diff --git a/app/Services/View.php b/app/Services/View.php index 004a6bfb..2e244bd0 100644 --- a/app/Services/View.php +++ b/app/Services/View.php @@ -12,23 +12,23 @@ class View public static function getSmarty() { - $smarty=new smarty(); //实例化smarty - + $smarty = new smarty(); //实例化smarty + $user = Auth::getUser(); - + if ($user->isLogin) { - $theme=$user->theme; + $theme = $user->theme; } else { - $theme=Config::get('theme'); + $theme = Config::get('theme'); } - + $can_backtoadmin = 0; if (Utils\Cookie::get('old_uid') && Utils\Cookie::get('old_email') && Utils\Cookie::get('old_key') && Utils\Cookie::get('old_ip') && Utils\Cookie::get('old_expire_in') && Utils\Cookie::get('old_local')) { $can_backtoadmin = 1; } - $smarty->settemplatedir(BASE_PATH.'/resources/views/'.$theme.'/'); //设置模板文件存放目录 - $smarty->setcompiledir(BASE_PATH.'/storage/framework/smarty/compile/'); //设置生成文件存放目录 - $smarty->setcachedir(BASE_PATH.'/storage/framework/smarty/cache/'); //设置缓存文件存放目录 + $smarty->settemplatedir(BASE_PATH . '/resources/views/' . $theme . '/'); //设置模板文件存放目录 + $smarty->setcompiledir(BASE_PATH . '/storage/framework/smarty/compile/'); //设置生成文件存放目录 + $smarty->setcachedir(BASE_PATH . '/storage/framework/smarty/cache/'); //设置缓存文件存放目录 // add config $smarty->assign('config', Config::getPublicConfig()); $smarty->assign('user', $user); @@ -37,7 +37,7 @@ class View if (View::$connection) { $smarty->assign('queryLog', View::$connection->connection('default')->getQueryLog()); $optTime = microtime(true) - View::$beginTime; - $smarty->assign('optTime', $optTime * 1000); + $smarty->assign('optTime', $optTime * 1000); } return $smarty; diff --git a/app/Utils/AntiXSS.php b/app/Utils/AntiXSS.php index 7034a6a1..f40af5a8 100644 --- a/app/Utils/AntiXSS.php +++ b/app/Utils/AntiXSS.php @@ -16,1905 +16,1905 @@ namespace App\Utils; class AntiXSS { - /** - * @var array - */ - protected static $entitiesFallback = array( - "\t" => ' ', - "\n" => ' ', - '!' => '!', - '"' => '"', - '#' => '#', - '$' => '$', - '%' => '%', - '&' => '&', - "'" => ''', - '(' => '(', - ')' => ')', - '*' => '*', - '+' => '+', - ',' => ',', - '.' => '.', - '/' => '/', - ':' => ':', - ';' => ';', - '<' => '<', - '<⃒' => '<⃒', - '=' => '=', - '=⃥' => '=⃥', - '>' => '>', - '>⃒' => '&nvgt', - '?' => '?', - '@' => '@', - '[' => '[', - ']' => ']', - '^' => '^', - '_' => '_', - '`' => '`', - 'fj' => 'fj', - '{' => '{', - '|' => '|', - '}' => '}', - ' ' => ' ', - '¡' => '¡', - '¢' => '¢', - '£' => '£', - '¤' => '¤', - '¥' => '¥', - '¦' => '¦', - '§' => '§', - '¨' => '¨', - '©' => '©', - 'ª' => 'ª', - '«' => '«', - '¬' => '¬', - '­' => '­', - '®' => '®', - '¯' => '¯', - '°' => '°', - '±' => '±', - '²' => '²', - '³' => '³', - '´' => '´', - 'µ' => 'µ', - '¶' => '¶', - '·' => '·', - '¸' => '¸', - '¹' => '¹', - 'º' => 'º', - '»' => '»', - '¼' => '¼', - '½' => '½', - '¾' => '¾', - '¿' => '¿', - 'À' => 'À', - 'Á' => 'Á', - 'Â' => 'Â', - 'Ã' => 'Ã', - 'Ä' => 'Ä', - 'Å' => 'Å', - 'Æ' => 'Æ', - 'Ç' => 'Ç', - 'È' => 'È', - 'É' => 'É', - 'Ê' => 'Ê', - 'Ë' => 'Ë', - 'Ì' => 'Ì', - 'Í' => 'Í', - 'Î' => 'Î', - 'Ï' => 'Ï', - 'Ð' => 'Ð', - 'Ñ' => 'Ñ', - 'Ò' => 'Ò', - 'Ó' => 'Ó', - 'Ô' => 'Ô', - 'Õ' => 'Õ', - 'Ö' => 'Ö', - '×' => '×', - 'Ø' => 'Ø', - 'Ù' => 'Ù', - 'Ú' => 'Ú', - 'Û' => 'Û', - 'Ü' => 'Ü', - 'Ý' => 'Ý', - 'Þ' => 'Þ', - 'ß' => 'ß', - 'à' => 'à', - 'á' => 'á', - 'â' => 'â', - 'ã' => 'ã', - 'ä' => 'ä', - 'å' => 'å', - 'æ' => 'æ', - 'ç' => 'ç', - 'è' => 'è', - 'é' => 'é', - 'ê' => 'ê', - 'ë' => 'ë', - 'ì' => 'ì', - 'í' => 'í', - 'î' => 'î', - 'ï' => 'ï', - 'ð' => 'ð', - 'ñ' => 'ñ', - 'ò' => 'ò', - 'ó' => 'ó', - 'ô' => 'ô', - 'õ' => 'õ', - 'ö' => 'ö', - '÷' => '÷', - 'ø' => 'ø', - 'ù' => 'ù', - 'ú' => 'ú', - 'û' => 'û', - 'ü' => 'ü', - 'ý' => 'ý', - 'þ' => 'þ', - 'ÿ' => 'ÿ', - 'Ā' => 'Ā', - 'ā' => 'ā', - 'Ă' => 'Ă', - 'ă' => 'ă', - 'Ą' => 'Ą', - 'ą' => 'ą', - 'Ć' => 'Ć', - 'ć' => 'ć', - 'Ĉ' => 'Ĉ', - 'ĉ' => 'ĉ', - 'Ċ' => 'Ċ', - 'ċ' => 'ċ', - 'Č' => 'Č', - 'č' => 'č', - 'Ď' => 'Ď', - 'ď' => 'ď', - 'Đ' => 'Đ', - 'đ' => 'đ', - 'Ē' => 'Ē', - 'ē' => 'ē', - 'Ė' => 'Ė', - 'ė' => 'ė', - 'Ę' => 'Ę', - 'ę' => 'ę', - 'Ě' => 'Ě', - 'ě' => 'ě', - 'Ĝ' => 'Ĝ', - 'ĝ' => 'ĝ', - 'Ğ' => 'Ğ', - 'ğ' => 'ğ', - 'Ġ' => 'Ġ', - 'ġ' => 'ġ', - 'Ģ' => 'Ģ', - 'Ĥ' => 'Ĥ', - 'ĥ' => 'ĥ', - 'Ħ' => 'Ħ', - 'ħ' => 'ħ', - 'Ĩ' => 'Ĩ', - 'ĩ' => 'ĩ', - 'Ī' => 'Ī', - 'ī' => 'ī', - 'Į' => 'Į', - 'į' => 'į', - 'İ' => 'İ', - 'ı' => 'ı', - 'IJ' => 'IJ', - 'ij' => 'ij', - 'Ĵ' => 'Ĵ', - 'ĵ' => 'ĵ', - 'Ķ' => 'Ķ', - 'ķ' => 'ķ', - 'ĸ' => 'ĸ', - 'Ĺ' => 'Ĺ', - 'ĺ' => 'ĺ', - 'Ļ' => 'Ļ', - 'ļ' => 'ļ', - 'Ľ' => 'Ľ', - 'ľ' => 'ľ', - 'Ŀ' => 'Ŀ', - 'ŀ' => 'ŀ', - 'Ł' => 'Ł', - 'ł' => 'ł', - 'Ń' => 'Ń', - 'ń' => 'ń', - 'Ņ' => 'Ņ', - 'ņ' => 'ņ', - 'Ň' => 'Ň', - 'ň' => 'ň', - 'ʼn' => 'ʼn', - 'Ŋ' => 'Ŋ', - 'ŋ' => 'ŋ', - 'Ō' => 'Ō', - 'ō' => 'ō', - 'Ő' => 'Ő', - 'ő' => 'ő', - 'Œ' => 'Œ', - 'œ' => 'œ', - 'Ŕ' => 'Ŕ', - 'ŕ' => 'ŕ', - 'Ŗ' => 'Ŗ', - 'ŗ' => 'ŗ', - 'Ř' => 'Ř', - 'ř' => 'ř', - 'Ś' => 'Ś', - 'ś' => 'ś', - 'Ŝ' => 'Ŝ', - 'ŝ' => 'ŝ', - 'Ş' => 'Ş', - 'ş' => 'ş', - 'Š' => 'Š', - 'š' => 'š', - 'Ţ' => 'Ţ', - 'ţ' => 'ţ', - 'Ť' => 'Ť', - 'ť' => 'ť', - 'Ŧ' => 'Ŧ', - 'ŧ' => 'ŧ', - 'Ũ' => 'Ũ', - 'ũ' => 'ũ', - 'Ū' => 'Ū', - 'ū' => 'ū', - 'Ŭ' => 'Ŭ', - 'ŭ' => 'ŭ', - 'Ů' => 'Ů', - 'ů' => 'ů', - 'Ű' => 'Ű', - 'ű' => 'ű', - 'Ų' => 'Ų', - 'ų' => 'ų', - 'Ŵ' => 'Ŵ', - 'ŵ' => 'ŵ', - 'Ŷ' => 'Ŷ', - 'ŷ' => 'ŷ', - 'Ÿ' => 'Ÿ', - 'Ź' => 'Ź', - 'ź' => 'ź', - 'Ż' => 'Ż', - 'ż' => 'ż', - 'Ž' => 'Ž', - 'ž' => 'ž', - 'ƒ' => 'ƒ', - 'Ƶ' => 'Ƶ', - 'ǵ' => 'ǵ', - 'ȷ' => 'ȷ', - 'ˆ' => 'ˆ', - 'ˇ' => 'ˇ', - '˘' => '˘', - '˙' => '˙', - '˚' => '˚', - '˛' => '˛', - '˜' => '˜', - '˝' => '˝', - '̑' => '̑', - 'Α' => 'Α', - 'Β' => 'Β', - 'Γ' => 'Γ', - 'Δ' => 'Δ', - 'Ε' => 'Ε', - 'Ζ' => 'Ζ', - 'Η' => 'Η', - 'Θ' => 'Θ', - 'Ι' => 'Ι', - 'Κ' => 'Κ', - 'Λ' => 'Λ', - 'Μ' => 'Μ', - 'Ν' => 'Ν', - 'Ξ' => 'Ξ', - 'Ο' => 'Ο', - 'Π' => 'Π', - 'Ρ' => 'Ρ', - 'Σ' => 'Σ', - 'Τ' => 'Τ', - 'Υ' => 'Υ', - 'Φ' => 'Φ', - 'Χ' => 'Χ', - 'Ψ' => 'Ψ', - 'Ω' => 'Ω', - 'α' => 'α', - 'β' => 'β', - 'γ' => 'γ', - 'δ' => 'δ', - 'ε' => 'ε', - 'ζ' => 'ζ', - 'η' => 'η', - 'θ' => 'θ', - 'ι' => 'ι', - 'κ' => 'κ', - 'λ' => 'λ', - 'μ' => 'μ', - 'ν' => 'ν', - 'ξ' => 'ξ', - 'ο' => 'ο', - 'π' => 'π', - 'ρ' => 'ρ', - 'ς' => 'ς', - 'σ' => 'σ', - 'τ' => 'τ', - 'υ' => 'υ', - 'φ' => 'φ', - 'χ' => 'χ', - 'ψ' => 'ψ', - 'ω' => 'ω', - 'ϑ' => 'ϑ', - 'ϒ' => 'ϒ', - 'ϕ' => 'ϕ', - 'ϖ' => 'ϖ', - 'Ϝ' => 'Ϝ', - 'ϝ' => 'ϝ', - 'ϰ' => 'ϰ', - 'ϱ' => 'ϱ', - 'ϵ' => 'ϵ', - '϶' => '϶', - 'Ё' => 'Ё', - 'Ђ' => 'Ђ', - 'Ѓ' => 'Ѓ', - 'Є' => 'Є', - 'Ѕ' => 'Ѕ', - 'І' => 'І', - 'Ї' => 'Ї', - 'Ј' => 'Ј', - 'Љ' => 'Љ', - 'Њ' => 'Њ', - 'Ћ' => 'Ћ', - 'Ќ' => 'Ќ', - 'Ў' => 'Ў', - 'Џ' => 'Џ', - 'А' => 'А', - 'Б' => 'Б', - 'В' => 'В', - 'Г' => 'Г', - 'Д' => 'Д', - 'Е' => 'Е', - 'Ж' => 'Ж', - 'З' => 'З', - 'И' => 'И', - 'Й' => 'Й', - 'К' => 'К', - 'Л' => 'Л', - 'М' => 'М', - 'Н' => 'Н', - 'О' => 'О', - 'П' => 'П', - 'Р' => 'Р', - 'С' => 'С', - 'Т' => 'Т', - 'У' => 'У', - 'Ф' => 'Ф', - 'Х' => 'Х', - 'Ц' => 'Ц', - 'Ч' => 'Ч', - 'Ш' => 'Ш', - 'Щ' => 'Щ', - 'Ъ' => 'Ъ', - 'Ы' => 'Ы', - 'Ь' => 'Ь', - 'Э' => 'Э', - 'Ю' => 'Ю', - 'Я' => 'Я', - 'а' => 'а', - 'б' => 'б', - 'в' => 'в', - 'г' => 'г', - 'д' => 'д', - 'е' => 'е', - 'ж' => 'ж', - 'з' => 'з', - 'и' => 'и', - 'й' => 'й', - 'к' => 'к', - 'л' => 'л', - 'м' => 'м', - 'н' => 'н', - 'о' => 'о', - 'п' => 'п', - 'р' => 'р', - 'с' => 'с', - 'т' => 'т', - 'у' => 'у', - 'ф' => 'ф', - 'х' => 'х', - 'ц' => 'ц', - 'ч' => 'ч', - 'ш' => 'ш', - 'щ' => 'щ', - 'ъ' => 'ъ', - 'ы' => 'ы', - 'ь' => 'ь', - 'э' => 'э', - 'ю' => 'ю', - 'я' => 'я', - 'ё' => 'ё', - 'ђ' => 'ђ', - 'ѓ' => 'ѓ', - 'є' => 'є', - 'ѕ' => 'ѕ', - 'і' => 'і', - 'ї' => 'ї', - 'ј' => 'ј', - 'љ' => 'љ', - 'њ' => 'њ', - 'ћ' => 'ћ', - 'ќ' => 'ќ', - 'ў' => 'ў', - 'џ' => 'џ', - ' ' => ' ', - ' ' => ' ', - ' ' => ' ', - ' ' => ' ', - ' ' => ' ', - ' ' => ' ', - ' ' => ' ', - ' ' => ' ', - '​' => '​', - '‌' => '‌', - '‍' => '‍', - '‎' => '‎', - '‏' => '‏', - '‐' => '‐', - '–' => '–', - '—' => '—', - '―' => '―', - '‖' => '‖', - '‘' => '‘', - '’' => '’', - '‚' => '‚', - '“' => '“', - '”' => '”', - '„' => '„', - '†' => '†', - '‡' => '‡', - '•' => '•', - '‥' => '‥', - '…' => '…', - '‰' => '‰', - '‱' => '‱', - '′' => '′', - '″' => '″', - '‴' => '‴', - '‵' => '‵', - '‹' => '‹', - '›' => '›', - '‾' => '‾', - '⁁' => '⁁', - '⁃' => '⁃', - '⁄' => '⁄', - '⁏' => '⁏', - '⁗' => '⁗', - ' ' => ' ', - '  ' => '  ', - '⁠' => '⁠', - '⁡' => '⁡', - '⁢' => '⁢', - '⁣' => '⁣', - '€' => '€', - '⃛' => '⃛', - '⃜' => '⃜', - 'ℂ' => 'ℂ', - '℅' => '℅', - 'ℊ' => 'ℊ', - 'ℋ' => 'ℋ', - 'ℌ' => 'ℌ', - 'ℍ' => 'ℍ', - 'ℎ' => 'ℎ', - 'ℏ' => 'ℏ', - 'ℐ' => 'ℐ', - 'ℑ' => 'ℑ', - 'ℒ' => 'ℒ', - 'ℓ' => 'ℓ', - 'ℕ' => 'ℕ', - '№' => '№', - '℗' => '℗', - '℘' => '℘', - 'ℙ' => 'ℙ', - 'ℚ' => 'ℚ', - 'ℛ' => 'ℛ', - 'ℜ' => 'ℜ', - 'ℝ' => 'ℝ', - '℞' => '℞', - '™' => '™', - 'ℤ' => 'ℤ', - '℧' => '℧', - 'ℨ' => 'ℨ', - '℩' => '℩', - 'ℬ' => 'ℬ', - 'ℭ' => 'ℭ', - 'ℯ' => 'ℯ', - 'ℰ' => 'ℰ', - 'ℱ' => 'ℱ', - 'ℳ' => 'ℳ', - 'ℴ' => 'ℴ', - 'ℵ' => 'ℵ', - 'ℶ' => 'ℶ', - 'ℷ' => 'ℷ', - 'ℸ' => 'ℸ', - 'ⅅ' => 'ⅅ', - 'ⅆ' => 'ⅆ', - 'ⅇ' => 'ⅇ', - 'ⅈ' => 'ⅈ', - '⅓' => '⅓', - '⅔' => '⅔', - '⅕' => '⅕', - '⅖' => '⅖', - '⅗' => '⅗', - '⅘' => '⅘', - '⅙' => '⅙', - '⅚' => '⅚', - '⅛' => '⅛', - '⅜' => '⅜', - '⅝' => '⅝', - '⅞' => '⅞', - '←' => '←', - '↑' => '↑', - '→' => '→', - '↓' => '↓', - '↔' => '↔', - '↕' => '↕', - '↖' => '↖', - '↗' => '↗', - '↘' => '↘', - '↙' => '↙', - '↚' => '↚', - '↛' => '↛', - '↝' => '↝', - '↝̸' => '↝̸', - '↞' => '↞', - '↟' => '↟', - '↠' => '↠', - '↡' => '↡', - '↢' => '↢', - '↣' => '↣', - '↤' => '↤', - '↥' => '↥', - '↦' => '↦', - '↧' => '↧', - '↩' => '↩', - '↪' => '↪', - '↫' => '↫', - '↬' => '↬', - '↭' => '↭', - '↮' => '↮', - '↰' => '↰', - '↱' => '↱', - '↲' => '↲', - '↳' => '↳', - '↵' => '↵', - '↶' => '↶', - '↷' => '↷', - '↺' => '↺', - '↻' => '↻', - '↼' => '↼', - '↽' => '↽', - '↾' => '↾', - '↿' => '↿', - '⇀' => '⇀', - '⇁' => '⇁', - '⇂' => '⇂', - '⇃' => '⇃', - '⇄' => '⇄', - '⇅' => '⇅', - '⇆' => '⇆', - '⇇' => '⇇', - '⇈' => '⇈', - '⇉' => '⇉', - '⇊' => '⇊', - '⇋' => '⇋', - '⇌' => '⇌', - '⇍' => '⇍', - '⇎' => '⇎', - '⇏' => '⇏', - '⇐' => '⇐', - '⇑' => '⇑', - '⇒' => '⇒', - '⇓' => '⇓', - '⇔' => '⇔', - '⇕' => '⇕', - '⇖' => '⇖', - '⇗' => '⇗', - '⇘' => '⇘', - '⇙' => '⇙', - '⇚' => '⇚', - '⇛' => '⇛', - '⇝' => '⇝', - '⇤' => '⇤', - '⇥' => '⇥', - '⇵' => '⇵', - '⇽' => '⇽', - '⇾' => '⇾', - '⇿' => '⇿', - '∀' => '∀', - '∁' => '∁', - '∂' => '∂', - '∂̸' => '∂̸', - '∃' => '∃', - '∄' => '∄', - '∅' => '∅', - '∇' => '∇', - '∈' => '∈', - '∉' => '∉', - '∋' => '∋', - '∌' => '∌', - '∏' => '∏', - '∐' => '∐', - '∑' => '∑', - '−' => '−', - '∓' => '∓', - '∔' => '∔', - '∖' => '∖', - '∗' => '∗', - '∘' => '∘', - '√' => '√', - '∝' => '∝', - '∞' => '∞', - '∟' => '∟', - '∠' => '∠', - '∠⃒' => '∠⃒', - '∡' => '∡', - '∢' => '∢', - '∣' => '∣', - '∤' => '∤', - '∥' => '∥', - '∦' => '∦', - '∧' => '∧', - '∨' => '∨', - '∩' => '∩', - '∩︀' => '∩︀', - '∪' => '∪', - '∪︀' => '&cups', - '∫' => '∫', - '∬' => '∬', - '∭' => '∭', - '∮' => '∮', - '∯' => '∯', - '∰' => '∰', - '∱' => '∱', - '∲' => '∲', - '∳' => '∳', - '∴' => '∴', - '∵' => '∵', - '∶' => '∶', - '∷' => '∷', - '∸' => '∸', - '∺' => '∺', - '∻' => '∻', - '∼' => '∼', - '∼⃒' => '∼⃒', - '∽' => '∽', - '∽̱' => '∽̱', - '∾' => '∾', - '∾̳' => '∾̳', - '∿' => '∿', - '≀' => '≀', - '≁' => '≁', - '≂' => '≂', - '≂̸' => '≂̸', - '≃' => '≃', - '≄' => '≄', - '≅' => '≅', - '≆' => '≆', - '≇' => '≇', - '≈' => '≈', - '≉' => '≉', - '≊' => '≊', - '≋' => '≋', - '≋̸' => '≋̸', - '≌' => '≌', - '≍' => '≍', - '≍⃒' => '≍⃒', - '≎' => '≎', - '≎̸' => '≎̸', - '≏' => '≏', - '≏̸' => '≏̸', - '≐' => '≐', - '≐̸' => '≐̸', - '≑' => '≑', - '≒' => '≒', - '≓' => '≓', - '≔' => '≔', - '≕' => '≕', - '≖' => '≖', - '≗' => '≗', - '≙' => '≙', - '≚' => '≚', - '≜' => '≜', - '≟' => '≟', - '≠' => '≠', - '≡' => '≡', - '≡⃥' => '≡⃥', - '≢' => '≢', - '≤' => '≤', - '≤⃒' => '≤⃒', - '≥' => '≥', - '≥⃒' => '≥⃒', - '≦' => '≦', - '≦̸' => '≦̸', - '≧' => '≧', - '≧̸' => '≧̸', - '≨' => '≨', - '≨︀' => '≨︀', - '≩' => '≩', - '≩︀' => '≩︀', - '≪' => '≪', - '≪̸' => '≪̸', - '≪⃒' => '≪⃒', - '≫' => '≫', - '≫̸' => '≫̸', - '≫⃒' => '≫⃒', - '≬' => '≬', - '≭' => '≭', - '≮' => '≮', - '≯' => '≯', - '≰' => '≰', - '≱' => '≱', - '≲' => '≲', - '≳' => '≳', - '≴' => '≴', - '≵' => '≵', - '≶' => '≶', - '≷' => '≷', - '≸' => '≸', - '≹' => '≹', - '≺' => '≺', - '≻' => '≻', - '≼' => '≼', - '≽' => '≽', - '≾' => '≾', - '≿' => '≿', - '≿̸' => '≿̸', - '⊀' => '⊀', - '⊁' => '⊁', - '⊂' => '⊂', - '⊂⃒' => '⊂⃒', - '⊃' => '⊃', - '⊃⃒' => '⊃⃒', - '⊄' => '⊄', - '⊅' => '⊅', - '⊆' => '⊆', - '⊇' => '⊇', - '⊈' => '⊈', - '⊉' => '⊉', - '⊊' => '⊊', - '⊊︀' => '⊊︀', - '⊋' => '⊋', - '⊋︀' => '⊋︀', - '⊍' => '⊍', - '⊎' => '⊎', - '⊏' => '⊏', - '⊏̸' => '⊏̸', - '⊐' => '⊐', - '⊐̸' => '⊐̸', - '⊑' => '⊑', - '⊒' => '⊒', - '⊓' => '⊓', - '⊓︀' => '⊓︀', - '⊔' => '⊔', - '⊔︀' => '⊔︀', - '⊕' => '⊕', - '⊖' => '⊖', - '⊗' => '⊗', - '⊘' => '⊘', - '⊙' => '⊙', - '⊚' => '⊚', - '⊛' => '⊛', - '⊝' => '⊝', - '⊞' => '⊞', - '⊟' => '⊟', - '⊠' => '⊠', - '⊡' => '⊡', - '⊢' => '⊢', - '⊣' => '⊣', - '⊤' => '⊤', - '⊥' => '⊥', - '⊧' => '⊧', - '⊨' => '⊨', - '⊩' => '⊩', - '⊪' => '⊪', - '⊫' => '⊫', - '⊬' => '⊬', - '⊭' => '⊭', - '⊮' => '⊮', - '⊯' => '⊯', - '⊰' => '⊰', - '⊲' => '⊲', - '⊳' => '⊳', - '⊴' => '⊴', - '⊴⃒' => '⊴⃒', - '⊵' => '⊵', - '⊵⃒' => '⊵⃒', - '⊶' => '⊶', - '⊷' => '⊷', - '⊸' => '⊸', - '⊹' => '⊹', - '⊺' => '⊺', - '⊻' => '⊻', - '⊽' => '⊽', - '⊾' => '⊾', - '⊿' => '⊿', - '⋀' => '⋀', - '⋁' => '⋁', - '⋂' => '⋂', - '⋃' => '⋃', - '⋄' => '⋄', - '⋅' => '⋅', - '⋆' => '⋆', - '⋇' => '⋇', - '⋈' => '⋈', - '⋉' => '⋉', - '⋊' => '⋊', - '⋋' => '⋋', - '⋌' => '⋌', - '⋍' => '⋍', - '⋎' => '⋎', - '⋏' => '⋏', - '⋐' => '⋐', - '⋑' => '⋑', - '⋒' => '⋒', - '⋓' => '⋓', - '⋔' => '⋔', - '⋕' => '⋕', - '⋖' => '⋖', - '⋗' => '⋗', - '⋘' => '⋘', - '⋘̸' => '⋘̸', - '⋙' => '⋙', - '⋙̸' => '⋙̸', - '⋚' => '⋚', - '⋚︀' => '⋚︀', - '⋛' => '⋛', - '⋛︀' => '⋛︀', - '⋞' => '⋞', - '⋟' => '⋟', - '⋠' => '⋠', - '⋡' => '⋡', - '⋢' => '⋢', - '⋣' => '⋣', - '⋦' => '⋦', - '⋧' => '⋧', - '⋨' => '⋨', - '⋩' => '⋩', - '⋪' => '⋪', - '⋫' => '⋫', - '⋬' => '⋬', - '⋭' => '⋭', - '⋮' => '⋮', - '⋯' => '⋯', - '⋰' => '⋰', - '⋱' => '⋱', - '⋲' => '⋲', - '⋳' => '⋳', - '⋴' => '⋴', - '⋵' => '⋵', - '⋵̸' => '⋵̸', - '⋶' => '⋶', - '⋷' => '⋷', - '⋹' => '⋹', - '⋹̸' => '⋹̸', - '⋺' => '⋺', - '⋻' => '⋻', - '⋼' => '⋼', - '⋽' => '⋽', - '⋾' => '⋾', - '⌅' => '⌅', - '⌆' => '⌆', - '⌈' => '⌈', - '⌉' => '⌉', - '⌊' => '⌊', - '⌋' => '⌋', - '⌌' => '⌌', - '⌍' => '⌍', - '⌎' => '⌎', - '⌏' => '⌏', - '⌐' => '⌐', - '⌒' => '⌒', - '⌓' => '⌓', - '⌕' => '⌕', - '⌖' => '⌖', - '⌜' => '⌜', - '⌝' => '⌝', - '⌞' => '⌞', - '⌟' => '⌟', - '⌢' => '⌢', - '⌣' => '⌣', - '⌭' => '⌭', - '⌮' => '⌮', - '⌶' => '⌶', - '⌽' => '⌽', - '⌿' => '⌿', - '⍼' => '⍼', - '⎰' => '⎰', - '⎱' => '⎱', - '⎴' => '⎴', - '⎵' => '⎵', - '⎶' => '⎶', - '⏜' => '⏜', - '⏝' => '⏝', - '⏞' => '⏞', - '⏟' => '⏟', - '⏢' => '⏢', - '⏧' => '⏧', - '␣' => '␣', - 'Ⓢ' => 'Ⓢ', - '─' => '─', - '│' => '│', - '┌' => '┌', - '┐' => '┐', - '└' => '└', - '┘' => '┘', - '├' => '├', - '┤' => '┤', - '┬' => '┬', - '┴' => '┴', - '┼' => '┼', - '═' => '═', - '║' => '║', - '╒' => '╒', - '╓' => '╓', - '╔' => '╔', - '╕' => '╕', - '╖' => '╖', - '╗' => '╗', - '╘' => '╘', - '╙' => '╙', - '╚' => '╚', - '╛' => '╛', - '╜' => '╜', - '╝' => '╝', - '╞' => '╞', - '╟' => '╟', - '╠' => '╠', - '╡' => '╡', - '╢' => '╢', - '╣' => '╣', - '╤' => '╤', - '╥' => '╥', - '╦' => '╦', - '╧' => '╧', - '╨' => '╨', - '╩' => '╩', - '╪' => '╪', - '╫' => '╫', - '╬' => '╬', - '▀' => '▀', - '▄' => '▄', - '█' => '█', - '░' => '░', - '▒' => '▒', - '▓' => '▓', - '□' => '□', - '▪' => '▪', - '▫' => '▫', - '▭' => '▭', - '▮' => '▮', - '▱' => '▱', - '△' => '△', - '▴' => '▴', - '▵' => '▵', - '▸' => '▸', - '▹' => '▹', - '▽' => '▽', - '▾' => '▾', - '▿' => '▿', - '◂' => '◂', - '◃' => '◃', - '◊' => '◊', - '○' => '○', - '◬' => '◬', - '◯' => '◯', - '◸' => '◸', - '◹' => '◹', - '◺' => '◺', - '◻' => '◻', - '◼' => '◼', - '★' => '★', - '☆' => '☆', - '☎' => '☎', - '♀' => '♀', - '♂' => '♂', - '♠' => '♠', - '♣' => '♣', - '♥' => '♥', - '♦' => '♦', - '♪' => '♪', - '♭' => '♭', - '♮' => '♮', - '♯' => '♯', - '✓' => '✓', - '✗' => '✗', - '✠' => '✠', - '✶' => '✶', - '❘' => '❘', - '❲' => '❲', - '❳' => '❳', - '⟈' => '⟈', - '⟉' => '⟉', - '⟦' => '⟦', - '⟧' => '⟧', - '⟨' => '⟨', - '⟩' => '⟩', - '⟪' => '⟪', - '⟫' => '⟫', - '⟬' => '⟬', - '⟭' => '⟭', - '⟵' => '⟵', - '⟶' => '⟶', - '⟷' => '⟷', - '⟸' => '⟸', - '⟹' => '⟹', - '⟺' => '⟺', - '⟼' => '⟼', - '⟿' => '⟿', - '⤂' => '⤂', - '⤃' => '⤃', - '⤄' => '⤄', - '⤅' => '⤅', - '⤌' => '⤌', - '⤍' => '⤍', - '⤎' => '⤎', - '⤏' => '⤏', - '⤐' => '⤐', - '⤑' => '⤑', - '⤒' => '⤒', - '⤓' => '⤓', - '⤖' => '⤖', - '⤙' => '⤙', - '⤚' => '⤚', - '⤛' => '⤛', - '⤜' => '⤜', - '⤝' => '⤝', - '⤞' => '⤞', - '⤟' => '⤟', - '⤠' => '⤠', - '⤣' => '⤣', - '⤤' => '⤤', - '⤥' => '⤥', - '⤦' => '⤦', - '⤧' => '⤧', - '⤨' => '⤨', - '⤩' => '⤩', - '⤪' => '⤪', - '⤳' => '⤳', - '⤳̸' => '⤳̸', - '⤵' => '⤵', - '⤶' => '⤶', - '⤷' => '⤷', - '⤸' => '⤸', - '⤹' => '⤹', - '⤼' => '⤼', - '⤽' => '⤽', - '⥅' => '⥅', - '⥈' => '⥈', - '⥉' => '⥉', - '⥊' => '⥊', - '⥋' => '⥋', - '⥎' => '⥎', - '⥏' => '⥏', - '⥐' => '⥐', - '⥑' => '⥑', - '⥒' => '⥒', - '⥓' => '⥓', - '⥔' => '⥔', - '⥕' => '⥕', - '⥖' => '⥖', - '⥗' => '⥗', - '⥘' => '⥘', - '⥙' => '⥙', - '⥚' => '⥚', - '⥛' => '⥛', - '⥜' => '⥜', - '⥝' => '⥝', - '⥞' => '⥞', - '⥟' => '⥟', - '⥠' => '⥠', - '⥡' => '⥡', - '⥢' => '⥢', - '⥣' => '⥣', - '⥤' => '⥤', - '⥥' => '⥥', - '⥦' => '⥦', - '⥧' => '⥧', - '⥨' => '⥨', - '⥩' => '⥩', - '⥪' => '⥪', - '⥫' => '⥫', - '⥬' => '⥬', - '⥭' => '⥭', - '⥮' => '⥮', - '⥯' => '⥯', - '⥰' => '⥰', - '⥱' => '⥱', - '⥲' => '⥲', - '⥳' => '⥳', - '⥴' => '⥴', - '⥵' => '⥵', - '⥶' => '⥶', - '⥸' => '⥸', - '⥹' => '⥹', - '⥻' => '⥻', - '⥼' => '⥼', - '⥽' => '⥽', - '⥾' => '⥾', - '⥿' => '⥿', - '⦅' => '⦅', - '⦆' => '⦆', - '⦋' => '⦋', - '⦌' => '⦌', - '⦍' => '⦍', - '⦎' => '⦎', - '⦏' => '⦏', - '⦐' => '⦐', - '⦑' => '⦑', - '⦒' => '⦒', - '⦓' => '⦓', - '⦔' => '⦔', - '⦕' => '⦕', - '⦖' => '⦖', - '⦚' => '⦚', - '⦜' => '⦜', - '⦝' => '⦝', - '⦤' => '⦤', - '⦥' => '⦥', - '⦦' => '⦦', - '⦧' => '⦧', - '⦨' => '⦨', - '⦩' => '⦩', - '⦪' => '⦪', - '⦫' => '⦫', - '⦬' => '⦬', - '⦭' => '⦭', - '⦮' => '⦮', - '⦯' => '⦯', - '⦰' => '⦰', - '⦱' => '⦱', - '⦲' => '⦲', - '⦳' => '⦳', - '⦴' => '⦴', - '⦵' => '⦵', - '⦶' => '⦶', - '⦷' => '⦷', - '⦹' => '⦹', - '⦻' => '⦻', - '⦼' => '⦼', - '⦾' => '⦾', - '⦿' => '⦿', - '⧀' => '⧀', - '⧁' => '⧁', - '⧂' => '⧂', - '⧃' => '⧃', - '⧄' => '⧄', - '⧅' => '⧅', - '⧉' => '⧉', - '⧍' => '⧍', - '⧎' => '⧎', - '⧏' => '⧏', - '⧏̸' => '⧏̸', - '⧐' => '⧐', - '⧐̸' => '⧐̸', - '⧜' => '⧜', - '⧝' => '⧝', - '⧞' => '⧞', - '⧣' => '⧣', - '⧤' => '⧤', - '⧥' => '⧥', - '⧫' => '⧫', - '⧴' => '⧴', - '⧶' => '⧶', - '⨀' => '⨀', - '⨁' => '⨁', - '⨂' => '⨂', - '⨄' => '⨄', - '⨆' => '⨆', - '⨌' => '⨌', - '⨍' => '⨍', - '⨐' => '⨐', - '⨑' => '⨑', - '⨒' => '⨒', - '⨓' => '⨓', - '⨔' => '⨔', - '⨕' => '⨕', - '⨖' => '⨖', - '⨗' => '⨗', - '⨢' => '⨢', - '⨣' => '⨣', - '⨤' => '⨤', - '⨥' => '⨥', - '⨦' => '⨦', - '⨧' => '⨧', - '⨩' => '⨩', - '⨪' => '⨪', - '⨭' => '⨭', - '⨮' => '⨮', - '⨯' => '⨯', - '⨰' => '⨰', - '⨱' => '⨱', - '⨳' => '⨳', - '⨴' => '⨴', - '⨵' => '⨵', - '⨶' => '⨶', - '⨷' => '⨷', - '⨸' => '⨸', - '⨹' => '⨹', - '⨺' => '⨺', - '⨻' => '⨻', - '⨼' => '⨼', - '⨿' => '⨿', - '⩀' => '⩀', - '⩂' => '⩂', - '⩃' => '⩃', - '⩄' => '⩄', - '⩅' => '⩅', - '⩆' => '⩆', - '⩇' => '⩇', - '⩈' => '⩈', - '⩉' => '⩉', - '⩊' => '⩊', - '⩋' => '⩋', - '⩌' => '⩌', - '⩍' => '⩍', - '⩐' => '⩐', - '⩓' => '⩓', - '⩔' => '⩔', - '⩕' => '⩕', - '⩖' => '⩖', - '⩗' => '⩗', - '⩘' => '⩘', - '⩚' => '⩚', - '⩛' => '⩛', - '⩜' => '⩜', - '⩝' => '⩝', - '⩟' => '⩟', - '⩦' => '⩦', - '⩪' => '⩪', - '⩭' => '⩭', - '⩭̸' => '⩭̸', - '⩮' => '⩮', - '⩯' => '⩯', - '⩰' => '⩰', - '⩰̸' => '⩰̸', - '⩱' => '⩱', - '⩲' => '⩲', - '⩳' => '⩳', - '⩴' => '⩴', - '⩵' => '⩵', - '⩷' => '⩷', - '⩸' => '⩸', - '⩹' => '⩹', - '⩺' => '⩺', - '⩻' => '⩻', - '⩼' => '⩼', - '⩽' => '⩽', - '⩽̸' => '⩽̸', - '⩾' => '⩾', - '⩾̸' => '⩾̸', - '⩿' => '⩿', - '⪀' => '⪀', - '⪁' => '⪁', - '⪂' => '⪂', - '⪃' => '⪃', - '⪄' => '⪄', - '⪅' => '⪅', - '⪆' => '⪆', - '⪇' => '⪇', - '⪈' => '⪈', - '⪉' => '⪉', - '⪊' => '⪊', - '⪋' => '⪋', - '⪌' => '⪌', - '⪍' => '⪍', - '⪎' => '⪎', - '⪏' => '⪏', - '⪐' => '⪐', - '⪑' => '⪑', - '⪒' => '⪒', - '⪓' => '⪓', - '⪔' => '⪔', - '⪕' => '⪕', - '⪖' => '⪖', - '⪗' => '⪗', - '⪘' => '⪘', - '⪙' => '⪙', - '⪚' => '⪚', - '⪝' => '⪝', - '⪞' => '⪞', - '⪟' => '⪟', - '⪠' => '⪠', - '⪡' => '⪡', - '⪡̸' => '⪡̸', - '⪢' => '⪢', - '⪢̸' => '⪢̸', - '⪤' => '⪤', - '⪥' => '⪥', - '⪦' => '⪦', - '⪧' => '⪧', - '⪨' => '⪨', - '⪩' => '⪩', - '⪪' => '⪪', - '⪫' => '⪫', - '⪬' => '⪬', - '⪬︀' => '⪬︀', - '⪭' => '⪭', - '⪭︀' => '⪭︀', - '⪮' => '⪮', - '⪯' => '⪯', - '⪯̸' => '⪯̸', - '⪰' => '⪰', - '⪰̸' => '⪰̸', - '⪳' => '⪳', - '⪴' => '⪴', - '⪵' => '⪵', - '⪶' => '⪶', - '⪷' => '⪷', - '⪸' => '⪸', - '⪹' => '⪹', - '⪺' => '⪺', - '⪻' => '⪻', - '⪼' => '⪼', - '⪽' => '⪽', - '⪾' => '⪾', - '⪿' => '⪿', - '⫀' => '⫀', - '⫁' => '⫁', - '⫂' => '⫂', - '⫃' => '⫃', - '⫄' => '⫄', - '⫅' => '⫅', - '⫅̸' => '⫅̸', - '⫆' => '⫆', - '⫆̸' => '⫆̸', - '⫇' => '⫇', - '⫈' => '⫈', - '⫋' => '⫋', - '⫋︀' => '⫋︀', - '⫌' => '⫌', - '⫌︀' => '⫌︀', - '⫏' => '⫏', - '⫐' => '⫐', - '⫑' => '⫑', - '⫒' => '⫒', - '⫓' => '⫓', - '⫔' => '⫔', - '⫕' => '⫕', - '⫖' => '⫖', - '⫗' => '⫗', - '⫘' => '⫘', - '⫙' => '⫙', - '⫚' => '⫚', - '⫛' => '⫛', - '⫤' => '⫤', - '⫦' => '⫦', - '⫧' => '⫧', - '⫨' => '⫨', - '⫩' => '⫩', - '⫫' => '⫫', - '⫬' => '⫬', - '⫭' => '⫭', - '⫮' => '⫮', - '⫯' => '⫯', - '⫰' => '⫰', - '⫱' => '⫱', - '⫲' => '⫲', - '⫳' => '⫳', - '⫽' => '⫽', - '⫽⃥' => '⫽⃥', - 'ff' => 'ff', - 'fi' => 'fi', - 'fl' => 'fl', - 'ffi' => 'ffi', - 'ffl' => 'ffl', - '𝒜' => '𝒜', - '𝒞' => '𝒞', - '𝒟' => '𝒟', - '𝒢' => '𝒢', - '𝒥' => '𝒥', - '𝒦' => '𝒦', - '𝒩' => '𝒩', - '𝒪' => '𝒪', - '𝒫' => '𝒫', - '𝒬' => '𝒬', - '𝒮' => '𝒮', - '𝒯' => '𝒯', - '𝒰' => '𝒰', - '𝒱' => '𝒱', - '𝒲' => '𝒲', - '𝒳' => '𝒳', - '𝒴' => '𝒴', - '𝒵' => '𝒵', - '𝒶' => '𝒶', - '𝒷' => '𝒷', - '𝒸' => '𝒸', - '𝒹' => '𝒹', - '𝒻' => '𝒻', - '𝒽' => '𝒽', - '𝒾' => '𝒾', - '𝒿' => '𝒿', - '𝓀' => '𝓀', - '𝓁' => '𝓁', - '𝓂' => '𝓂', - '𝓃' => '𝓃', - '𝓅' => '𝓅', - '𝓆' => '𝓆', - '𝓇' => '𝓇', - '𝓈' => '𝓈', - '𝓉' => '𝓉', - '𝓊' => '𝓊', - '𝓋' => '𝓋', - '𝓌' => '𝓌', - '𝓍' => '𝓍', - '𝓎' => '𝓎', - '𝓏' => '𝓏', - '𝔄' => '𝔄', - '𝔅' => '𝔅', - '𝔇' => '𝔇', - '𝔈' => '𝔈', - '𝔉' => '𝔉', - '𝔊' => '𝔊', - '𝔍' => '𝔍', - '𝔎' => '𝔎', - '𝔏' => '𝔏', - '𝔐' => '𝔐', - '𝔑' => '𝔑', - '𝔒' => '𝔒', - '𝔓' => '𝔓', - '𝔔' => '𝔔', - '𝔖' => '𝔖', - '𝔗' => '𝔗', - '𝔘' => '𝔘', - '𝔙' => '𝔙', - '𝔚' => '𝔚', - '𝔛' => '𝔛', - '𝔜' => '𝔜', - '𝔞' => '𝔞', - '𝔟' => '𝔟', - '𝔠' => '𝔠', - '𝔡' => '𝔡', - '𝔢' => '𝔢', - '𝔣' => '𝔣', - '𝔤' => '𝔤', - '𝔥' => '𝔥', - '𝔦' => '𝔦', - '𝔧' => '𝔧', - '𝔨' => '𝔨', - '𝔩' => '𝔩', - '𝔪' => '𝔪', - '𝔫' => '𝔫', - '𝔬' => '𝔬', - '𝔭' => '𝔭', - '𝔮' => '𝔮', - '𝔯' => '𝔯', - '𝔰' => '𝔰', - '𝔱' => '𝔱', - '𝔲' => '𝔲', - '𝔳' => '𝔳', - '𝔴' => '𝔴', - '𝔵' => '𝔵', - '𝔶' => '𝔶', - '𝔷' => '𝔷', - '𝔸' => '𝔸', - '𝔹' => '𝔹', - '𝔻' => '𝔻', - '𝔼' => '𝔼', - '𝔽' => '𝔽', - '𝔾' => '𝔾', - '𝕀' => '𝕀', - '𝕁' => '𝕁', - '𝕂' => '𝕂', - '𝕃' => '𝕃', - '𝕄' => '𝕄', - '𝕆' => '𝕆', - '𝕊' => '𝕊', - '𝕋' => '𝕋', - '𝕌' => '𝕌', - '𝕍' => '𝕍', - '𝕎' => '𝕎', - '𝕏' => '𝕏', - '𝕐' => '𝕐', - '𝕒' => '𝕒', - '𝕓' => '𝕓', - '𝕔' => '𝕔', - '𝕕' => '𝕕', - '𝕖' => '𝕖', - '𝕗' => '𝕗', - '𝕘' => '𝕘', - '𝕙' => '𝕙', - '𝕚' => '𝕚', - '𝕛' => '𝕛', - '𝕜' => '𝕜', - '𝕝' => '𝕝', - '𝕞' => '𝕞', - '𝕟' => '𝕟', - '𝕠' => '𝕠', - '𝕡' => '𝕡', - '𝕢' => '𝕢', - '𝕣' => '𝕣', - '𝕤' => '𝕤', - '𝕥' => '𝕥', - '𝕦' => '𝕦', - '𝕧' => '𝕧', - '𝕨' => '𝕨', - '𝕩' => '𝕩', - '𝕪' => '𝕪', - '𝕫' => '𝕫', - ); - - /** - * List of never allowed regex replacements - * - * @var array - */ - protected static $_never_allowed_regex = array( - // default javascript - 'javascript\s*:', - // default javascript - '(document|(document\.)?window)\.(location|on\w*)', - // Java: jar-protocol is an XSS hazard - 'jar\s*:', - // Mac (will not run the script, but open it in AppleScript Editor) - 'applescript\s*:', - // IE: https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#VBscript_in_an_image - 'vbscript\s*:', - // IE, surprise! - 'wscript\s*:', - // IE - 'jscript\s*:', - // IE: https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#VBscript_in_an_image - 'vbs\s*:', - // https://html5sec.org/#behavior - 'behavior\s:', - // ? - 'Redirect\s+30\d', - // data-attribute + base64 - "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?", - // remove Netscape 4 JS entities - '&\s*\{[^}]*(\}\s*;?|$)', - // old IE, old Netscape - 'expression\s*(\(|&\#40;)', - // old Netscape - 'mocha\s*:', - // old Netscape - 'livescript\s*:', - ); - - /** - * XSS Hash - random Hash for protecting URLs. - * - * @var string - */ - protected $_xss_hash; + /** + * @var array + */ + protected static $entitiesFallback = array( + "\t" => ' ', + "\n" => ' ', + '!' => '!', + '"' => '"', + '#' => '#', + '$' => '$', + '%' => '%', + '&' => '&', + "'" => ''', + '(' => '(', + ')' => ')', + '*' => '*', + '+' => '+', + ',' => ',', + '.' => '.', + '/' => '/', + ':' => ':', + ';' => ';', + '<' => '<', + '<⃒' => '<⃒', + '=' => '=', + '=⃥' => '=⃥', + '>' => '>', + '>⃒' => '&nvgt', + '?' => '?', + '@' => '@', + '[' => '[', + ']' => ']', + '^' => '^', + '_' => '_', + '`' => '`', + 'fj' => 'fj', + '{' => '{', + '|' => '|', + '}' => '}', + ' ' => ' ', + '¡' => '¡', + '¢' => '¢', + '£' => '£', + '¤' => '¤', + '¥' => '¥', + '¦' => '¦', + '§' => '§', + '¨' => '¨', + '©' => '©', + 'ª' => 'ª', + '«' => '«', + '¬' => '¬', + '­' => '­', + '®' => '®', + '¯' => '¯', + '°' => '°', + '±' => '±', + '²' => '²', + '³' => '³', + '´' => '´', + 'µ' => 'µ', + '¶' => '¶', + '·' => '·', + '¸' => '¸', + '¹' => '¹', + 'º' => 'º', + '»' => '»', + '¼' => '¼', + '½' => '½', + '¾' => '¾', + '¿' => '¿', + 'À' => 'À', + 'Á' => 'Á', + 'Â' => 'Â', + 'Ã' => 'Ã', + 'Ä' => 'Ä', + 'Å' => 'Å', + 'Æ' => 'Æ', + 'Ç' => 'Ç', + 'È' => 'È', + 'É' => 'É', + 'Ê' => 'Ê', + 'Ë' => 'Ë', + 'Ì' => 'Ì', + 'Í' => 'Í', + 'Î' => 'Î', + 'Ï' => 'Ï', + 'Ð' => 'Ð', + 'Ñ' => 'Ñ', + 'Ò' => 'Ò', + 'Ó' => 'Ó', + 'Ô' => 'Ô', + 'Õ' => 'Õ', + 'Ö' => 'Ö', + '×' => '×', + 'Ø' => 'Ø', + 'Ù' => 'Ù', + 'Ú' => 'Ú', + 'Û' => 'Û', + 'Ü' => 'Ü', + 'Ý' => 'Ý', + 'Þ' => 'Þ', + 'ß' => 'ß', + 'à' => 'à', + 'á' => 'á', + 'â' => 'â', + 'ã' => 'ã', + 'ä' => 'ä', + 'å' => 'å', + 'æ' => 'æ', + 'ç' => 'ç', + 'è' => 'è', + 'é' => 'é', + 'ê' => 'ê', + 'ë' => 'ë', + 'ì' => 'ì', + 'í' => 'í', + 'î' => 'î', + 'ï' => 'ï', + 'ð' => 'ð', + 'ñ' => 'ñ', + 'ò' => 'ò', + 'ó' => 'ó', + 'ô' => 'ô', + 'õ' => 'õ', + 'ö' => 'ö', + '÷' => '÷', + 'ø' => 'ø', + 'ù' => 'ù', + 'ú' => 'ú', + 'û' => 'û', + 'ü' => 'ü', + 'ý' => 'ý', + 'þ' => 'þ', + 'ÿ' => 'ÿ', + 'Ā' => 'Ā', + 'ā' => 'ā', + 'Ă' => 'Ă', + 'ă' => 'ă', + 'Ą' => 'Ą', + 'ą' => 'ą', + 'Ć' => 'Ć', + 'ć' => 'ć', + 'Ĉ' => 'Ĉ', + 'ĉ' => 'ĉ', + 'Ċ' => 'Ċ', + 'ċ' => 'ċ', + 'Č' => 'Č', + 'č' => 'č', + 'Ď' => 'Ď', + 'ď' => 'ď', + 'Đ' => 'Đ', + 'đ' => 'đ', + 'Ē' => 'Ē', + 'ē' => 'ē', + 'Ė' => 'Ė', + 'ė' => 'ė', + 'Ę' => 'Ę', + 'ę' => 'ę', + 'Ě' => 'Ě', + 'ě' => 'ě', + 'Ĝ' => 'Ĝ', + 'ĝ' => 'ĝ', + 'Ğ' => 'Ğ', + 'ğ' => 'ğ', + 'Ġ' => 'Ġ', + 'ġ' => 'ġ', + 'Ģ' => 'Ģ', + 'Ĥ' => 'Ĥ', + 'ĥ' => 'ĥ', + 'Ħ' => 'Ħ', + 'ħ' => 'ħ', + 'Ĩ' => 'Ĩ', + 'ĩ' => 'ĩ', + 'Ī' => 'Ī', + 'ī' => 'ī', + 'Į' => 'Į', + 'į' => 'į', + 'İ' => 'İ', + 'ı' => 'ı', + 'IJ' => 'IJ', + 'ij' => 'ij', + 'Ĵ' => 'Ĵ', + 'ĵ' => 'ĵ', + 'Ķ' => 'Ķ', + 'ķ' => 'ķ', + 'ĸ' => 'ĸ', + 'Ĺ' => 'Ĺ', + 'ĺ' => 'ĺ', + 'Ļ' => 'Ļ', + 'ļ' => 'ļ', + 'Ľ' => 'Ľ', + 'ľ' => 'ľ', + 'Ŀ' => 'Ŀ', + 'ŀ' => 'ŀ', + 'Ł' => 'Ł', + 'ł' => 'ł', + 'Ń' => 'Ń', + 'ń' => 'ń', + 'Ņ' => 'Ņ', + 'ņ' => 'ņ', + 'Ň' => 'Ň', + 'ň' => 'ň', + 'ʼn' => 'ʼn', + 'Ŋ' => 'Ŋ', + 'ŋ' => 'ŋ', + 'Ō' => 'Ō', + 'ō' => 'ō', + 'Ő' => 'Ő', + 'ő' => 'ő', + 'Œ' => 'Œ', + 'œ' => 'œ', + 'Ŕ' => 'Ŕ', + 'ŕ' => 'ŕ', + 'Ŗ' => 'Ŗ', + 'ŗ' => 'ŗ', + 'Ř' => 'Ř', + 'ř' => 'ř', + 'Ś' => 'Ś', + 'ś' => 'ś', + 'Ŝ' => 'Ŝ', + 'ŝ' => 'ŝ', + 'Ş' => 'Ş', + 'ş' => 'ş', + 'Š' => 'Š', + 'š' => 'š', + 'Ţ' => 'Ţ', + 'ţ' => 'ţ', + 'Ť' => 'Ť', + 'ť' => 'ť', + 'Ŧ' => 'Ŧ', + 'ŧ' => 'ŧ', + 'Ũ' => 'Ũ', + 'ũ' => 'ũ', + 'Ū' => 'Ū', + 'ū' => 'ū', + 'Ŭ' => 'Ŭ', + 'ŭ' => 'ŭ', + 'Ů' => 'Ů', + 'ů' => 'ů', + 'Ű' => 'Ű', + 'ű' => 'ű', + 'Ų' => 'Ų', + 'ų' => 'ų', + 'Ŵ' => 'Ŵ', + 'ŵ' => 'ŵ', + 'Ŷ' => 'Ŷ', + 'ŷ' => 'ŷ', + 'Ÿ' => 'Ÿ', + 'Ź' => 'Ź', + 'ź' => 'ź', + 'Ż' => 'Ż', + 'ż' => 'ż', + 'Ž' => 'Ž', + 'ž' => 'ž', + 'ƒ' => 'ƒ', + 'Ƶ' => 'Ƶ', + 'ǵ' => 'ǵ', + 'ȷ' => 'ȷ', + 'ˆ' => 'ˆ', + 'ˇ' => 'ˇ', + '˘' => '˘', + '˙' => '˙', + '˚' => '˚', + '˛' => '˛', + '˜' => '˜', + '˝' => '˝', + '̑' => '̑', + 'Α' => 'Α', + 'Β' => 'Β', + 'Γ' => 'Γ', + 'Δ' => 'Δ', + 'Ε' => 'Ε', + 'Ζ' => 'Ζ', + 'Η' => 'Η', + 'Θ' => 'Θ', + 'Ι' => 'Ι', + 'Κ' => 'Κ', + 'Λ' => 'Λ', + 'Μ' => 'Μ', + 'Ν' => 'Ν', + 'Ξ' => 'Ξ', + 'Ο' => 'Ο', + 'Π' => 'Π', + 'Ρ' => 'Ρ', + 'Σ' => 'Σ', + 'Τ' => 'Τ', + 'Υ' => 'Υ', + 'Φ' => 'Φ', + 'Χ' => 'Χ', + 'Ψ' => 'Ψ', + 'Ω' => 'Ω', + 'α' => 'α', + 'β' => 'β', + 'γ' => 'γ', + 'δ' => 'δ', + 'ε' => 'ε', + 'ζ' => 'ζ', + 'η' => 'η', + 'θ' => 'θ', + 'ι' => 'ι', + 'κ' => 'κ', + 'λ' => 'λ', + 'μ' => 'μ', + 'ν' => 'ν', + 'ξ' => 'ξ', + 'ο' => 'ο', + 'π' => 'π', + 'ρ' => 'ρ', + 'ς' => 'ς', + 'σ' => 'σ', + 'τ' => 'τ', + 'υ' => 'υ', + 'φ' => 'φ', + 'χ' => 'χ', + 'ψ' => 'ψ', + 'ω' => 'ω', + 'ϑ' => 'ϑ', + 'ϒ' => 'ϒ', + 'ϕ' => 'ϕ', + 'ϖ' => 'ϖ', + 'Ϝ' => 'Ϝ', + 'ϝ' => 'ϝ', + 'ϰ' => 'ϰ', + 'ϱ' => 'ϱ', + 'ϵ' => 'ϵ', + '϶' => '϶', + 'Ё' => 'Ё', + 'Ђ' => 'Ђ', + 'Ѓ' => 'Ѓ', + 'Є' => 'Є', + 'Ѕ' => 'Ѕ', + 'І' => 'І', + 'Ї' => 'Ї', + 'Ј' => 'Ј', + 'Љ' => 'Љ', + 'Њ' => 'Њ', + 'Ћ' => 'Ћ', + 'Ќ' => 'Ќ', + 'Ў' => 'Ў', + 'Џ' => 'Џ', + 'А' => 'А', + 'Б' => 'Б', + 'В' => 'В', + 'Г' => 'Г', + 'Д' => 'Д', + 'Е' => 'Е', + 'Ж' => 'Ж', + 'З' => 'З', + 'И' => 'И', + 'Й' => 'Й', + 'К' => 'К', + 'Л' => 'Л', + 'М' => 'М', + 'Н' => 'Н', + 'О' => 'О', + 'П' => 'П', + 'Р' => 'Р', + 'С' => 'С', + 'Т' => 'Т', + 'У' => 'У', + 'Ф' => 'Ф', + 'Х' => 'Х', + 'Ц' => 'Ц', + 'Ч' => 'Ч', + 'Ш' => 'Ш', + 'Щ' => 'Щ', + 'Ъ' => 'Ъ', + 'Ы' => 'Ы', + 'Ь' => 'Ь', + 'Э' => 'Э', + 'Ю' => 'Ю', + 'Я' => 'Я', + 'а' => 'а', + 'б' => 'б', + 'в' => 'в', + 'г' => 'г', + 'д' => 'д', + 'е' => 'е', + 'ж' => 'ж', + 'з' => 'з', + 'и' => 'и', + 'й' => 'й', + 'к' => 'к', + 'л' => 'л', + 'м' => 'м', + 'н' => 'н', + 'о' => 'о', + 'п' => 'п', + 'р' => 'р', + 'с' => 'с', + 'т' => 'т', + 'у' => 'у', + 'ф' => 'ф', + 'х' => 'х', + 'ц' => 'ц', + 'ч' => 'ч', + 'ш' => 'ш', + 'щ' => 'щ', + 'ъ' => 'ъ', + 'ы' => 'ы', + 'ь' => 'ь', + 'э' => 'э', + 'ю' => 'ю', + 'я' => 'я', + 'ё' => 'ё', + 'ђ' => 'ђ', + 'ѓ' => 'ѓ', + 'є' => 'є', + 'ѕ' => 'ѕ', + 'і' => 'і', + 'ї' => 'ї', + 'ј' => 'ј', + 'љ' => 'љ', + 'њ' => 'њ', + 'ћ' => 'ћ', + 'ќ' => 'ќ', + 'ў' => 'ў', + 'џ' => 'џ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + '​' => '​', + '‌' => '‌', + '‍' => '‍', + '‎' => '‎', + '‏' => '‏', + '‐' => '‐', + '–' => '–', + '—' => '—', + '―' => '―', + '‖' => '‖', + '‘' => '‘', + '’' => '’', + '‚' => '‚', + '“' => '“', + '”' => '”', + '„' => '„', + '†' => '†', + '‡' => '‡', + '•' => '•', + '‥' => '‥', + '…' => '…', + '‰' => '‰', + '‱' => '‱', + '′' => '′', + '″' => '″', + '‴' => '‴', + '‵' => '‵', + '‹' => '‹', + '›' => '›', + '‾' => '‾', + '⁁' => '⁁', + '⁃' => '⁃', + '⁄' => '⁄', + '⁏' => '⁏', + '⁗' => '⁗', + ' ' => ' ', + '  ' => '  ', + '⁠' => '⁠', + '⁡' => '⁡', + '⁢' => '⁢', + '⁣' => '⁣', + '€' => '€', + '⃛' => '⃛', + '⃜' => '⃜', + 'ℂ' => 'ℂ', + '℅' => '℅', + 'ℊ' => 'ℊ', + 'ℋ' => 'ℋ', + 'ℌ' => 'ℌ', + 'ℍ' => 'ℍ', + 'ℎ' => 'ℎ', + 'ℏ' => 'ℏ', + 'ℐ' => 'ℐ', + 'ℑ' => 'ℑ', + 'ℒ' => 'ℒ', + 'ℓ' => 'ℓ', + 'ℕ' => 'ℕ', + '№' => '№', + '℗' => '℗', + '℘' => '℘', + 'ℙ' => 'ℙ', + 'ℚ' => 'ℚ', + 'ℛ' => 'ℛ', + 'ℜ' => 'ℜ', + 'ℝ' => 'ℝ', + '℞' => '℞', + '™' => '™', + 'ℤ' => 'ℤ', + '℧' => '℧', + 'ℨ' => 'ℨ', + '℩' => '℩', + 'ℬ' => 'ℬ', + 'ℭ' => 'ℭ', + 'ℯ' => 'ℯ', + 'ℰ' => 'ℰ', + 'ℱ' => 'ℱ', + 'ℳ' => 'ℳ', + 'ℴ' => 'ℴ', + 'ℵ' => 'ℵ', + 'ℶ' => 'ℶ', + 'ℷ' => 'ℷ', + 'ℸ' => 'ℸ', + 'ⅅ' => 'ⅅ', + 'ⅆ' => 'ⅆ', + 'ⅇ' => 'ⅇ', + 'ⅈ' => 'ⅈ', + '⅓' => '⅓', + '⅔' => '⅔', + '⅕' => '⅕', + '⅖' => '⅖', + '⅗' => '⅗', + '⅘' => '⅘', + '⅙' => '⅙', + '⅚' => '⅚', + '⅛' => '⅛', + '⅜' => '⅜', + '⅝' => '⅝', + '⅞' => '⅞', + '←' => '←', + '↑' => '↑', + '→' => '→', + '↓' => '↓', + '↔' => '↔', + '↕' => '↕', + '↖' => '↖', + '↗' => '↗', + '↘' => '↘', + '↙' => '↙', + '↚' => '↚', + '↛' => '↛', + '↝' => '↝', + '↝̸' => '↝̸', + '↞' => '↞', + '↟' => '↟', + '↠' => '↠', + '↡' => '↡', + '↢' => '↢', + '↣' => '↣', + '↤' => '↤', + '↥' => '↥', + '↦' => '↦', + '↧' => '↧', + '↩' => '↩', + '↪' => '↪', + '↫' => '↫', + '↬' => '↬', + '↭' => '↭', + '↮' => '↮', + '↰' => '↰', + '↱' => '↱', + '↲' => '↲', + '↳' => '↳', + '↵' => '↵', + '↶' => '↶', + '↷' => '↷', + '↺' => '↺', + '↻' => '↻', + '↼' => '↼', + '↽' => '↽', + '↾' => '↾', + '↿' => '↿', + '⇀' => '⇀', + '⇁' => '⇁', + '⇂' => '⇂', + '⇃' => '⇃', + '⇄' => '⇄', + '⇅' => '⇅', + '⇆' => '⇆', + '⇇' => '⇇', + '⇈' => '⇈', + '⇉' => '⇉', + '⇊' => '⇊', + '⇋' => '⇋', + '⇌' => '⇌', + '⇍' => '⇍', + '⇎' => '⇎', + '⇏' => '⇏', + '⇐' => '⇐', + '⇑' => '⇑', + '⇒' => '⇒', + '⇓' => '⇓', + '⇔' => '⇔', + '⇕' => '⇕', + '⇖' => '⇖', + '⇗' => '⇗', + '⇘' => '⇘', + '⇙' => '⇙', + '⇚' => '⇚', + '⇛' => '⇛', + '⇝' => '⇝', + '⇤' => '⇤', + '⇥' => '⇥', + '⇵' => '⇵', + '⇽' => '⇽', + '⇾' => '⇾', + '⇿' => '⇿', + '∀' => '∀', + '∁' => '∁', + '∂' => '∂', + '∂̸' => '∂̸', + '∃' => '∃', + '∄' => '∄', + '∅' => '∅', + '∇' => '∇', + '∈' => '∈', + '∉' => '∉', + '∋' => '∋', + '∌' => '∌', + '∏' => '∏', + '∐' => '∐', + '∑' => '∑', + '−' => '−', + '∓' => '∓', + '∔' => '∔', + '∖' => '∖', + '∗' => '∗', + '∘' => '∘', + '√' => '√', + '∝' => '∝', + '∞' => '∞', + '∟' => '∟', + '∠' => '∠', + '∠⃒' => '∠⃒', + '∡' => '∡', + '∢' => '∢', + '∣' => '∣', + '∤' => '∤', + '∥' => '∥', + '∦' => '∦', + '∧' => '∧', + '∨' => '∨', + '∩' => '∩', + '∩︀' => '∩︀', + '∪' => '∪', + '∪︀' => '&cups', + '∫' => '∫', + '∬' => '∬', + '∭' => '∭', + '∮' => '∮', + '∯' => '∯', + '∰' => '∰', + '∱' => '∱', + '∲' => '∲', + '∳' => '∳', + '∴' => '∴', + '∵' => '∵', + '∶' => '∶', + '∷' => '∷', + '∸' => '∸', + '∺' => '∺', + '∻' => '∻', + '∼' => '∼', + '∼⃒' => '∼⃒', + '∽' => '∽', + '∽̱' => '∽̱', + '∾' => '∾', + '∾̳' => '∾̳', + '∿' => '∿', + '≀' => '≀', + '≁' => '≁', + '≂' => '≂', + '≂̸' => '≂̸', + '≃' => '≃', + '≄' => '≄', + '≅' => '≅', + '≆' => '≆', + '≇' => '≇', + '≈' => '≈', + '≉' => '≉', + '≊' => '≊', + '≋' => '≋', + '≋̸' => '≋̸', + '≌' => '≌', + '≍' => '≍', + '≍⃒' => '≍⃒', + '≎' => '≎', + '≎̸' => '≎̸', + '≏' => '≏', + '≏̸' => '≏̸', + '≐' => '≐', + '≐̸' => '≐̸', + '≑' => '≑', + '≒' => '≒', + '≓' => '≓', + '≔' => '≔', + '≕' => '≕', + '≖' => '≖', + '≗' => '≗', + '≙' => '≙', + '≚' => '≚', + '≜' => '≜', + '≟' => '≟', + '≠' => '≠', + '≡' => '≡', + '≡⃥' => '≡⃥', + '≢' => '≢', + '≤' => '≤', + '≤⃒' => '≤⃒', + '≥' => '≥', + '≥⃒' => '≥⃒', + '≦' => '≦', + '≦̸' => '≦̸', + '≧' => '≧', + '≧̸' => '≧̸', + '≨' => '≨', + '≨︀' => '≨︀', + '≩' => '≩', + '≩︀' => '≩︀', + '≪' => '≪', + '≪̸' => '≪̸', + '≪⃒' => '≪⃒', + '≫' => '≫', + '≫̸' => '≫̸', + '≫⃒' => '≫⃒', + '≬' => '≬', + '≭' => '≭', + '≮' => '≮', + '≯' => '≯', + '≰' => '≰', + '≱' => '≱', + '≲' => '≲', + '≳' => '≳', + '≴' => '≴', + '≵' => '≵', + '≶' => '≶', + '≷' => '≷', + '≸' => '≸', + '≹' => '≹', + '≺' => '≺', + '≻' => '≻', + '≼' => '≼', + '≽' => '≽', + '≾' => '≾', + '≿' => '≿', + '≿̸' => '≿̸', + '⊀' => '⊀', + '⊁' => '⊁', + '⊂' => '⊂', + '⊂⃒' => '⊂⃒', + '⊃' => '⊃', + '⊃⃒' => '⊃⃒', + '⊄' => '⊄', + '⊅' => '⊅', + '⊆' => '⊆', + '⊇' => '⊇', + '⊈' => '⊈', + '⊉' => '⊉', + '⊊' => '⊊', + '⊊︀' => '⊊︀', + '⊋' => '⊋', + '⊋︀' => '⊋︀', + '⊍' => '⊍', + '⊎' => '⊎', + '⊏' => '⊏', + '⊏̸' => '⊏̸', + '⊐' => '⊐', + '⊐̸' => '⊐̸', + '⊑' => '⊑', + '⊒' => '⊒', + '⊓' => '⊓', + '⊓︀' => '⊓︀', + '⊔' => '⊔', + '⊔︀' => '⊔︀', + '⊕' => '⊕', + '⊖' => '⊖', + '⊗' => '⊗', + '⊘' => '⊘', + '⊙' => '⊙', + '⊚' => '⊚', + '⊛' => '⊛', + '⊝' => '⊝', + '⊞' => '⊞', + '⊟' => '⊟', + '⊠' => '⊠', + '⊡' => '⊡', + '⊢' => '⊢', + '⊣' => '⊣', + '⊤' => '⊤', + '⊥' => '⊥', + '⊧' => '⊧', + '⊨' => '⊨', + '⊩' => '⊩', + '⊪' => '⊪', + '⊫' => '⊫', + '⊬' => '⊬', + '⊭' => '⊭', + '⊮' => '⊮', + '⊯' => '⊯', + '⊰' => '⊰', + '⊲' => '⊲', + '⊳' => '⊳', + '⊴' => '⊴', + '⊴⃒' => '⊴⃒', + '⊵' => '⊵', + '⊵⃒' => '⊵⃒', + '⊶' => '⊶', + '⊷' => '⊷', + '⊸' => '⊸', + '⊹' => '⊹', + '⊺' => '⊺', + '⊻' => '⊻', + '⊽' => '⊽', + '⊾' => '⊾', + '⊿' => '⊿', + '⋀' => '⋀', + '⋁' => '⋁', + '⋂' => '⋂', + '⋃' => '⋃', + '⋄' => '⋄', + '⋅' => '⋅', + '⋆' => '⋆', + '⋇' => '⋇', + '⋈' => '⋈', + '⋉' => '⋉', + '⋊' => '⋊', + '⋋' => '⋋', + '⋌' => '⋌', + '⋍' => '⋍', + '⋎' => '⋎', + '⋏' => '⋏', + '⋐' => '⋐', + '⋑' => '⋑', + '⋒' => '⋒', + '⋓' => '⋓', + '⋔' => '⋔', + '⋕' => '⋕', + '⋖' => '⋖', + '⋗' => '⋗', + '⋘' => '⋘', + '⋘̸' => '⋘̸', + '⋙' => '⋙', + '⋙̸' => '⋙̸', + '⋚' => '⋚', + '⋚︀' => '⋚︀', + '⋛' => '⋛', + '⋛︀' => '⋛︀', + '⋞' => '⋞', + '⋟' => '⋟', + '⋠' => '⋠', + '⋡' => '⋡', + '⋢' => '⋢', + '⋣' => '⋣', + '⋦' => '⋦', + '⋧' => '⋧', + '⋨' => '⋨', + '⋩' => '⋩', + '⋪' => '⋪', + '⋫' => '⋫', + '⋬' => '⋬', + '⋭' => '⋭', + '⋮' => '⋮', + '⋯' => '⋯', + '⋰' => '⋰', + '⋱' => '⋱', + '⋲' => '⋲', + '⋳' => '⋳', + '⋴' => '⋴', + '⋵' => '⋵', + '⋵̸' => '⋵̸', + '⋶' => '⋶', + '⋷' => '⋷', + '⋹' => '⋹', + '⋹̸' => '⋹̸', + '⋺' => '⋺', + '⋻' => '⋻', + '⋼' => '⋼', + '⋽' => '⋽', + '⋾' => '⋾', + '⌅' => '⌅', + '⌆' => '⌆', + '⌈' => '⌈', + '⌉' => '⌉', + '⌊' => '⌊', + '⌋' => '⌋', + '⌌' => '⌌', + '⌍' => '⌍', + '⌎' => '⌎', + '⌏' => '⌏', + '⌐' => '⌐', + '⌒' => '⌒', + '⌓' => '⌓', + '⌕' => '⌕', + '⌖' => '⌖', + '⌜' => '⌜', + '⌝' => '⌝', + '⌞' => '⌞', + '⌟' => '⌟', + '⌢' => '⌢', + '⌣' => '⌣', + '⌭' => '⌭', + '⌮' => '⌮', + '⌶' => '⌶', + '⌽' => '⌽', + '⌿' => '⌿', + '⍼' => '⍼', + '⎰' => '⎰', + '⎱' => '⎱', + '⎴' => '⎴', + '⎵' => '⎵', + '⎶' => '⎶', + '⏜' => '⏜', + '⏝' => '⏝', + '⏞' => '⏞', + '⏟' => '⏟', + '⏢' => '⏢', + '⏧' => '⏧', + '␣' => '␣', + 'Ⓢ' => 'Ⓢ', + '─' => '─', + '│' => '│', + '┌' => '┌', + '┐' => '┐', + '└' => '└', + '┘' => '┘', + '├' => '├', + '┤' => '┤', + '┬' => '┬', + '┴' => '┴', + '┼' => '┼', + '═' => '═', + '║' => '║', + '╒' => '╒', + '╓' => '╓', + '╔' => '╔', + '╕' => '╕', + '╖' => '╖', + '╗' => '╗', + '╘' => '╘', + '╙' => '╙', + '╚' => '╚', + '╛' => '╛', + '╜' => '╜', + '╝' => '╝', + '╞' => '╞', + '╟' => '╟', + '╠' => '╠', + '╡' => '╡', + '╢' => '╢', + '╣' => '╣', + '╤' => '╤', + '╥' => '╥', + '╦' => '╦', + '╧' => '╧', + '╨' => '╨', + '╩' => '╩', + '╪' => '╪', + '╫' => '╫', + '╬' => '╬', + '▀' => '▀', + '▄' => '▄', + '█' => '█', + '░' => '░', + '▒' => '▒', + '▓' => '▓', + '□' => '□', + '▪' => '▪', + '▫' => '▫', + '▭' => '▭', + '▮' => '▮', + '▱' => '▱', + '△' => '△', + '▴' => '▴', + '▵' => '▵', + '▸' => '▸', + '▹' => '▹', + '▽' => '▽', + '▾' => '▾', + '▿' => '▿', + '◂' => '◂', + '◃' => '◃', + '◊' => '◊', + '○' => '○', + '◬' => '◬', + '◯' => '◯', + '◸' => '◸', + '◹' => '◹', + '◺' => '◺', + '◻' => '◻', + '◼' => '◼', + '★' => '★', + '☆' => '☆', + '☎' => '☎', + '♀' => '♀', + '♂' => '♂', + '♠' => '♠', + '♣' => '♣', + '♥' => '♥', + '♦' => '♦', + '♪' => '♪', + '♭' => '♭', + '♮' => '♮', + '♯' => '♯', + '✓' => '✓', + '✗' => '✗', + '✠' => '✠', + '✶' => '✶', + '❘' => '❘', + '❲' => '❲', + '❳' => '❳', + '⟈' => '⟈', + '⟉' => '⟉', + '⟦' => '⟦', + '⟧' => '⟧', + '⟨' => '⟨', + '⟩' => '⟩', + '⟪' => '⟪', + '⟫' => '⟫', + '⟬' => '⟬', + '⟭' => '⟭', + '⟵' => '⟵', + '⟶' => '⟶', + '⟷' => '⟷', + '⟸' => '⟸', + '⟹' => '⟹', + '⟺' => '⟺', + '⟼' => '⟼', + '⟿' => '⟿', + '⤂' => '⤂', + '⤃' => '⤃', + '⤄' => '⤄', + '⤅' => '⤅', + '⤌' => '⤌', + '⤍' => '⤍', + '⤎' => '⤎', + '⤏' => '⤏', + '⤐' => '⤐', + '⤑' => '⤑', + '⤒' => '⤒', + '⤓' => '⤓', + '⤖' => '⤖', + '⤙' => '⤙', + '⤚' => '⤚', + '⤛' => '⤛', + '⤜' => '⤜', + '⤝' => '⤝', + '⤞' => '⤞', + '⤟' => '⤟', + '⤠' => '⤠', + '⤣' => '⤣', + '⤤' => '⤤', + '⤥' => '⤥', + '⤦' => '⤦', + '⤧' => '⤧', + '⤨' => '⤨', + '⤩' => '⤩', + '⤪' => '⤪', + '⤳' => '⤳', + '⤳̸' => '⤳̸', + '⤵' => '⤵', + '⤶' => '⤶', + '⤷' => '⤷', + '⤸' => '⤸', + '⤹' => '⤹', + '⤼' => '⤼', + '⤽' => '⤽', + '⥅' => '⥅', + '⥈' => '⥈', + '⥉' => '⥉', + '⥊' => '⥊', + '⥋' => '⥋', + '⥎' => '⥎', + '⥏' => '⥏', + '⥐' => '⥐', + '⥑' => '⥑', + '⥒' => '⥒', + '⥓' => '⥓', + '⥔' => '⥔', + '⥕' => '⥕', + '⥖' => '⥖', + '⥗' => '⥗', + '⥘' => '⥘', + '⥙' => '⥙', + '⥚' => '⥚', + '⥛' => '⥛', + '⥜' => '⥜', + '⥝' => '⥝', + '⥞' => '⥞', + '⥟' => '⥟', + '⥠' => '⥠', + '⥡' => '⥡', + '⥢' => '⥢', + '⥣' => '⥣', + '⥤' => '⥤', + '⥥' => '⥥', + '⥦' => '⥦', + '⥧' => '⥧', + '⥨' => '⥨', + '⥩' => '⥩', + '⥪' => '⥪', + '⥫' => '⥫', + '⥬' => '⥬', + '⥭' => '⥭', + '⥮' => '⥮', + '⥯' => '⥯', + '⥰' => '⥰', + '⥱' => '⥱', + '⥲' => '⥲', + '⥳' => '⥳', + '⥴' => '⥴', + '⥵' => '⥵', + '⥶' => '⥶', + '⥸' => '⥸', + '⥹' => '⥹', + '⥻' => '⥻', + '⥼' => '⥼', + '⥽' => '⥽', + '⥾' => '⥾', + '⥿' => '⥿', + '⦅' => '⦅', + '⦆' => '⦆', + '⦋' => '⦋', + '⦌' => '⦌', + '⦍' => '⦍', + '⦎' => '⦎', + '⦏' => '⦏', + '⦐' => '⦐', + '⦑' => '⦑', + '⦒' => '⦒', + '⦓' => '⦓', + '⦔' => '⦔', + '⦕' => '⦕', + '⦖' => '⦖', + '⦚' => '⦚', + '⦜' => '⦜', + '⦝' => '⦝', + '⦤' => '⦤', + '⦥' => '⦥', + '⦦' => '⦦', + '⦧' => '⦧', + '⦨' => '⦨', + '⦩' => '⦩', + '⦪' => '⦪', + '⦫' => '⦫', + '⦬' => '⦬', + '⦭' => '⦭', + '⦮' => '⦮', + '⦯' => '⦯', + '⦰' => '⦰', + '⦱' => '⦱', + '⦲' => '⦲', + '⦳' => '⦳', + '⦴' => '⦴', + '⦵' => '⦵', + '⦶' => '⦶', + '⦷' => '⦷', + '⦹' => '⦹', + '⦻' => '⦻', + '⦼' => '⦼', + '⦾' => '⦾', + '⦿' => '⦿', + '⧀' => '⧀', + '⧁' => '⧁', + '⧂' => '⧂', + '⧃' => '⧃', + '⧄' => '⧄', + '⧅' => '⧅', + '⧉' => '⧉', + '⧍' => '⧍', + '⧎' => '⧎', + '⧏' => '⧏', + '⧏̸' => '⧏̸', + '⧐' => '⧐', + '⧐̸' => '⧐̸', + '⧜' => '⧜', + '⧝' => '⧝', + '⧞' => '⧞', + '⧣' => '⧣', + '⧤' => '⧤', + '⧥' => '⧥', + '⧫' => '⧫', + '⧴' => '⧴', + '⧶' => '⧶', + '⨀' => '⨀', + '⨁' => '⨁', + '⨂' => '⨂', + '⨄' => '⨄', + '⨆' => '⨆', + '⨌' => '⨌', + '⨍' => '⨍', + '⨐' => '⨐', + '⨑' => '⨑', + '⨒' => '⨒', + '⨓' => '⨓', + '⨔' => '⨔', + '⨕' => '⨕', + '⨖' => '⨖', + '⨗' => '⨗', + '⨢' => '⨢', + '⨣' => '⨣', + '⨤' => '⨤', + '⨥' => '⨥', + '⨦' => '⨦', + '⨧' => '⨧', + '⨩' => '⨩', + '⨪' => '⨪', + '⨭' => '⨭', + '⨮' => '⨮', + '⨯' => '⨯', + '⨰' => '⨰', + '⨱' => '⨱', + '⨳' => '⨳', + '⨴' => '⨴', + '⨵' => '⨵', + '⨶' => '⨶', + '⨷' => '⨷', + '⨸' => '⨸', + '⨹' => '⨹', + '⨺' => '⨺', + '⨻' => '⨻', + '⨼' => '⨼', + '⨿' => '⨿', + '⩀' => '⩀', + '⩂' => '⩂', + '⩃' => '⩃', + '⩄' => '⩄', + '⩅' => '⩅', + '⩆' => '⩆', + '⩇' => '⩇', + '⩈' => '⩈', + '⩉' => '⩉', + '⩊' => '⩊', + '⩋' => '⩋', + '⩌' => '⩌', + '⩍' => '⩍', + '⩐' => '⩐', + '⩓' => '⩓', + '⩔' => '⩔', + '⩕' => '⩕', + '⩖' => '⩖', + '⩗' => '⩗', + '⩘' => '⩘', + '⩚' => '⩚', + '⩛' => '⩛', + '⩜' => '⩜', + '⩝' => '⩝', + '⩟' => '⩟', + '⩦' => '⩦', + '⩪' => '⩪', + '⩭' => '⩭', + '⩭̸' => '⩭̸', + '⩮' => '⩮', + '⩯' => '⩯', + '⩰' => '⩰', + '⩰̸' => '⩰̸', + '⩱' => '⩱', + '⩲' => '⩲', + '⩳' => '⩳', + '⩴' => '⩴', + '⩵' => '⩵', + '⩷' => '⩷', + '⩸' => '⩸', + '⩹' => '⩹', + '⩺' => '⩺', + '⩻' => '⩻', + '⩼' => '⩼', + '⩽' => '⩽', + '⩽̸' => '⩽̸', + '⩾' => '⩾', + '⩾̸' => '⩾̸', + '⩿' => '⩿', + '⪀' => '⪀', + '⪁' => '⪁', + '⪂' => '⪂', + '⪃' => '⪃', + '⪄' => '⪄', + '⪅' => '⪅', + '⪆' => '⪆', + '⪇' => '⪇', + '⪈' => '⪈', + '⪉' => '⪉', + '⪊' => '⪊', + '⪋' => '⪋', + '⪌' => '⪌', + '⪍' => '⪍', + '⪎' => '⪎', + '⪏' => '⪏', + '⪐' => '⪐', + '⪑' => '⪑', + '⪒' => '⪒', + '⪓' => '⪓', + '⪔' => '⪔', + '⪕' => '⪕', + '⪖' => '⪖', + '⪗' => '⪗', + '⪘' => '⪘', + '⪙' => '⪙', + '⪚' => '⪚', + '⪝' => '⪝', + '⪞' => '⪞', + '⪟' => '⪟', + '⪠' => '⪠', + '⪡' => '⪡', + '⪡̸' => '⪡̸', + '⪢' => '⪢', + '⪢̸' => '⪢̸', + '⪤' => '⪤', + '⪥' => '⪥', + '⪦' => '⪦', + '⪧' => '⪧', + '⪨' => '⪨', + '⪩' => '⪩', + '⪪' => '⪪', + '⪫' => '⪫', + '⪬' => '⪬', + '⪬︀' => '⪬︀', + '⪭' => '⪭', + '⪭︀' => '⪭︀', + '⪮' => '⪮', + '⪯' => '⪯', + '⪯̸' => '⪯̸', + '⪰' => '⪰', + '⪰̸' => '⪰̸', + '⪳' => '⪳', + '⪴' => '⪴', + '⪵' => '⪵', + '⪶' => '⪶', + '⪷' => '⪷', + '⪸' => '⪸', + '⪹' => '⪹', + '⪺' => '⪺', + '⪻' => '⪻', + '⪼' => '⪼', + '⪽' => '⪽', + '⪾' => '⪾', + '⪿' => '⪿', + '⫀' => '⫀', + '⫁' => '⫁', + '⫂' => '⫂', + '⫃' => '⫃', + '⫄' => '⫄', + '⫅' => '⫅', + '⫅̸' => '⫅̸', + '⫆' => '⫆', + '⫆̸' => '⫆̸', + '⫇' => '⫇', + '⫈' => '⫈', + '⫋' => '⫋', + '⫋︀' => '⫋︀', + '⫌' => '⫌', + '⫌︀' => '⫌︀', + '⫏' => '⫏', + '⫐' => '⫐', + '⫑' => '⫑', + '⫒' => '⫒', + '⫓' => '⫓', + '⫔' => '⫔', + '⫕' => '⫕', + '⫖' => '⫖', + '⫗' => '⫗', + '⫘' => '⫘', + '⫙' => '⫙', + '⫚' => '⫚', + '⫛' => '⫛', + '⫤' => '⫤', + '⫦' => '⫦', + '⫧' => '⫧', + '⫨' => '⫨', + '⫩' => '⫩', + '⫫' => '⫫', + '⫬' => '⫬', + '⫭' => '⫭', + '⫮' => '⫮', + '⫯' => '⫯', + '⫰' => '⫰', + '⫱' => '⫱', + '⫲' => '⫲', + '⫳' => '⫳', + '⫽' => '⫽', + '⫽⃥' => '⫽⃥', + 'ff' => 'ff', + 'fi' => 'fi', + 'fl' => 'fl', + 'ffi' => 'ffi', + 'ffl' => 'ffl', + '𝒜' => '𝒜', + '𝒞' => '𝒞', + '𝒟' => '𝒟', + '𝒢' => '𝒢', + '𝒥' => '𝒥', + '𝒦' => '𝒦', + '𝒩' => '𝒩', + '𝒪' => '𝒪', + '𝒫' => '𝒫', + '𝒬' => '𝒬', + '𝒮' => '𝒮', + '𝒯' => '𝒯', + '𝒰' => '𝒰', + '𝒱' => '𝒱', + '𝒲' => '𝒲', + '𝒳' => '𝒳', + '𝒴' => '𝒴', + '𝒵' => '𝒵', + '𝒶' => '𝒶', + '𝒷' => '𝒷', + '𝒸' => '𝒸', + '𝒹' => '𝒹', + '𝒻' => '𝒻', + '𝒽' => '𝒽', + '𝒾' => '𝒾', + '𝒿' => '𝒿', + '𝓀' => '𝓀', + '𝓁' => '𝓁', + '𝓂' => '𝓂', + '𝓃' => '𝓃', + '𝓅' => '𝓅', + '𝓆' => '𝓆', + '𝓇' => '𝓇', + '𝓈' => '𝓈', + '𝓉' => '𝓉', + '𝓊' => '𝓊', + '𝓋' => '𝓋', + '𝓌' => '𝓌', + '𝓍' => '𝓍', + '𝓎' => '𝓎', + '𝓏' => '𝓏', + '𝔄' => '𝔄', + '𝔅' => '𝔅', + '𝔇' => '𝔇', + '𝔈' => '𝔈', + '𝔉' => '𝔉', + '𝔊' => '𝔊', + '𝔍' => '𝔍', + '𝔎' => '𝔎', + '𝔏' => '𝔏', + '𝔐' => '𝔐', + '𝔑' => '𝔑', + '𝔒' => '𝔒', + '𝔓' => '𝔓', + '𝔔' => '𝔔', + '𝔖' => '𝔖', + '𝔗' => '𝔗', + '𝔘' => '𝔘', + '𝔙' => '𝔙', + '𝔚' => '𝔚', + '𝔛' => '𝔛', + '𝔜' => '𝔜', + '𝔞' => '𝔞', + '𝔟' => '𝔟', + '𝔠' => '𝔠', + '𝔡' => '𝔡', + '𝔢' => '𝔢', + '𝔣' => '𝔣', + '𝔤' => '𝔤', + '𝔥' => '𝔥', + '𝔦' => '𝔦', + '𝔧' => '𝔧', + '𝔨' => '𝔨', + '𝔩' => '𝔩', + '𝔪' => '𝔪', + '𝔫' => '𝔫', + '𝔬' => '𝔬', + '𝔭' => '𝔭', + '𝔮' => '𝔮', + '𝔯' => '𝔯', + '𝔰' => '𝔰', + '𝔱' => '𝔱', + '𝔲' => '𝔲', + '𝔳' => '𝔳', + '𝔴' => '𝔴', + '𝔵' => '𝔵', + '𝔶' => '𝔶', + '𝔷' => '𝔷', + '𝔸' => '𝔸', + '𝔹' => '𝔹', + '𝔻' => '𝔻', + '𝔼' => '𝔼', + '𝔽' => '𝔽', + '𝔾' => '𝔾', + '𝕀' => '𝕀', + '𝕁' => '𝕁', + '𝕂' => '𝕂', + '𝕃' => '𝕃', + '𝕄' => '𝕄', + '𝕆' => '𝕆', + '𝕊' => '𝕊', + '𝕋' => '𝕋', + '𝕌' => '𝕌', + '𝕍' => '𝕍', + '𝕎' => '𝕎', + '𝕏' => '𝕏', + '𝕐' => '𝕐', + '𝕒' => '𝕒', + '𝕓' => '𝕓', + '𝕔' => '𝕔', + '𝕕' => '𝕕', + '𝕖' => '𝕖', + '𝕗' => '𝕗', + '𝕘' => '𝕘', + '𝕙' => '𝕙', + '𝕚' => '𝕚', + '𝕛' => '𝕛', + '𝕜' => '𝕜', + '𝕝' => '𝕝', + '𝕞' => '𝕞', + '𝕟' => '𝕟', + '𝕠' => '𝕠', + '𝕡' => '𝕡', + '𝕢' => '𝕢', + '𝕣' => '𝕣', + '𝕤' => '𝕤', + '𝕥' => '𝕥', + '𝕦' => '𝕦', + '𝕧' => '𝕧', + '𝕨' => '𝕨', + '𝕩' => '𝕩', + '𝕪' => '𝕪', + '𝕫' => '𝕫', + ); - /** - * the replacement-string for not allowed strings - * - * @var string - */ - protected $_replacement = ''; + /** + * List of never allowed regex replacements + * + * @var array + */ + protected static $_never_allowed_regex = array( + // default javascript + 'javascript\s*:', + // default javascript + '(document|(document\.)?window)\.(location|on\w*)', + // Java: jar-protocol is an XSS hazard + 'jar\s*:', + // Mac (will not run the script, but open it in AppleScript Editor) + 'applescript\s*:', + // IE: https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#VBscript_in_an_image + 'vbscript\s*:', + // IE, surprise! + 'wscript\s*:', + // IE + 'jscript\s*:', + // IE: https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#VBscript_in_an_image + 'vbs\s*:', + // https://html5sec.org/#behavior + 'behavior\s:', + // ? + 'Redirect\s+30\d', + // data-attribute + base64 + "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?", + // remove Netscape 4 JS entities + '&\s*\{[^}]*(\}\s*;?|$)', + // old IE, old Netscape + 'expression\s*(\(|&\#40;)', + // old Netscape + 'mocha\s*:', + // old Netscape + 'livescript\s*:', + ); - /** - * list of never allowed strings - * - * @var array - */ - protected $_never_allowed_str = array(); + /** + * XSS Hash - random Hash for protecting URLs. + * + * @var string + */ + protected $_xss_hash; - /** - * list of never allowed strings, afterwards - * - * @var array - */ - protected $_never_allowed_str_afterwards = array(); + /** + * the replacement-string for not allowed strings + * + * @var string + */ + protected $_replacement = ''; - /** - * __construct() - */ - public function __construct() - { - $this->_never_allowed_str = array( - 'document.cookie' => $this->_replacement, - 'document.write' => $this->_replacement, - '.parentNode' => $this->_replacement, - '.innerHTML' => $this->_replacement, - '-moz-binding' => $this->_replacement, - '' => '-->', - ' '<![CDATA[', - ' '<!ENTITY', - ' '<!DOCTYPE', - ' '<!ATTLIST', - '' => '<comment>', - ); + /** + * list of never allowed strings + * + * @var array + */ + protected $_never_allowed_str = array(); - $this->_never_allowed_str_afterwards = array( - 'FSCommand', - 'onAbort', - 'onActivate', - 'onAttribute', - 'onAfterPrint', - 'onAfterScriptExecute', - 'onAfterUpdate', - 'onAnimationEnd', - 'onAnimationIteration', - 'onAnimationStart', - 'onAriaRequest', - 'onAutoComplete', - 'onAutoCompleteError', - 'onBeforeActivate', - 'onBeforeCopy', - 'onBeforeCut', - 'onBeforeDeactivate', - 'onBeforeEditFocus', - 'onBeforePaste', - 'onBeforePrint', - 'onBeforeScriptExecute', - 'onBeforeUnload', - 'onBeforeUpdate', - 'onBegin', - 'onBlur', - 'onBounce', - 'onCancel', - 'onCanPlay', - 'onCanPlayThrough', - 'onCellChange', - 'onChange', - 'onClick', - 'onClose', - 'onCommand', - 'onCompassNeedsCalibration', - 'onContextMenu', - 'onControlSelect', - 'onCopy', - 'onCueChange', - 'onCut', - 'onDataAvailable', - 'onDataSetChanged', - 'onDataSetComplete', - 'onDblClick', - 'onDeactivate', - 'onDeviceLight', - 'onDeviceMotion', - 'onDeviceOrientation', - 'onDeviceProximity', - 'onDrag', - 'onDragDrop', - 'onDragEnd', - 'onDragEnter', - 'onDragLeave', - 'onDragOver', - 'onDragStart', - 'onDrop', - 'onDurationChange', - 'onEmptied', - 'onEnd', - 'onEnded', - 'onError', - 'onErrorUpdate', - 'onExit', - 'onFilterChange', - 'onFinish', - 'onFocus', - 'onFocusIn', - 'onFocusOut', - 'onFormChange', - 'onFormInput', - 'onFullScreenChange', - 'onFullScreenError', - 'onGotPointerCapture', - 'onHashChange', - 'onHelp', - 'onInput', - 'onInvalid', - 'onKeyDown', - 'onKeyPress', - 'onKeyUp', - 'onLanguageChange', - 'onLayoutComplete', - 'onLoad', - 'onLoadedData', - 'onLoadedMetaData', - 'onLoadStart', - 'onLoseCapture', - 'onLostPointerCapture', - 'onMediaComplete', - 'onMediaError', - 'onMessage', - 'onMouseDown', - 'onMouseEnter', - 'onMouseLeave', - 'onMouseMove', - 'onMouseOut', - 'onMouseOver', - 'onMouseUp', - 'onMouseWheel', - 'onMove', - 'onMoveEnd', - 'onMoveStart', - 'onMozFullScreenChange', - 'onMozFullScreenError', - 'onMozPointerLockChange', - 'onMozPointerLockError', - 'onMsContentZoom', - 'onMsFullScreenChange', - 'onMsFullScreenError', - 'onMsGestureChange', - 'onMsGestureDoubleTap', - 'onMsGestureEnd', - 'onMsGestureHold', - 'onMsGestureStart', - 'onMsGestureTap', - 'onMsGotPointerCapture', - 'onMsInertiaStart', - 'onMsLostPointerCapture', - 'onMsManipulationStateChanged', - 'onMsPointerCancel', - 'onMsPointerDown', - 'onMsPointerEnter', - 'onMsPointerLeave', - 'onMsPointerMove', - 'onMsPointerOut', - 'onMsPointerOver', - 'onMsPointerUp', - 'onMsSiteModeJumpListItemRemoved', - 'onMsThumbnailClick', - 'onOffline', - 'onOnline', - 'onOutOfSync', - 'onPage', - 'onPageHide', - 'onPageShow', - 'onPaste', - 'onPause', - 'onPlay', - 'onPlaying', - 'onPointerCancel', - 'onPointerDown', - 'onPointerEnter', - 'onPointerLeave', - 'onPointerLockChange', - 'onPointerLockError', - 'onPointerMove', - 'onPointerOut', - 'onPointerOver', - 'onPointerUp', - 'onPopState', - 'onProgress', - 'onPropertyChange', - 'onRateChange', - 'onReadyStateChange', - 'onReceived', - 'onRepeat', - 'onReset', - 'onResize', - 'onResizeEnd', - 'onResizeStart', - 'onResume', - 'onReverse', - 'onRowDelete', - 'onRowEnter', - 'onRowExit', - 'onRowInserted', - 'onRowsDelete', - 'onRowsEnter', - 'onRowsExit', - 'onRowsInserted', - 'onScroll', - 'onSearch', - 'onSeek', - 'onSeeked', - 'onSeeking', - 'onSelect', - 'onSelectionChange', - 'onSelectStart', - 'onStalled', - 'onStorage', - 'onStorageCommit', - 'onStart', - 'onStop', - 'onShow', - 'onSyncRestored', - 'onSubmit', - 'onSuspend', - 'onSynchRestored', - 'onTimeError', - 'onTimeUpdate', - 'onTrackChange', - 'onTransitionEnd', - 'onToggle', - 'onUnload', - 'onURLFlip', - 'onUserProximity', - 'onVolumeChange', - 'onWaiting', - 'onWebKitAnimationEnd', - 'onWebKitAnimationIteration', - 'onWebKitAnimationStart', - 'onWebKitFullScreenChange', - 'onWebKitFullScreenError', - 'onWebKitTransitionEnd', - 'onWheel', - 'seekSegmentTime', - 'userid', - 'datasrc', - 'datafld', - 'dataformatas', - 'ev:handler', - 'ev:event', - '0;url', - ); - } + /** + * list of never allowed strings, afterwards + * + * @var array + */ + protected $_never_allowed_str_afterwards = array(); - /** - * XSS Clean - * - * Sanitizes data so that Cross Site Scripting Hacks can be - * prevented. This method does a fair amount of work but - * it is extremely thorough, designed to prevent even the - * most obscure XSS attempts. Nothing is ever 100% foolproof, - * of course, but I haven't been able to get anything passed - * the filter. - * - * Note: Should only be used to deal with data upon submission. - * It's not something that should be used for general - * runtime processing. - * - * @link http://channel.bitflux.ch/wiki/XSS_Prevention - * Based in part on some code and ideas from Bitflux. - * - * @link http://ha.ckers.org/xss.html - * To help develop this script I used this great list of - * vulnerabilities along with a few other hacks I've - * harvested from examining vulnerabilities in other programs. - * - * @param mixed $str input data e.g. string or array - * @param bool $is_image whether the input is an image - * - * @return string|array|boolean boolean: will return a boolean, if the "is_image"-parameter is true - * string: will return a string, if the input is a string - * array: will return a array, if the input is a array - */ - public function xss_clean($str, $is_image = false) - { - if (is_array($str)) { - foreach ($str as &$value) { - $value = $this->xss_clean($value); - } - - return $str; - } - - $str = (string)$str; - $strInt = (int)$str; - $strFloat = (float)$str; - /** @noinspection TypeUnsafeComparisonInspection */ - if ( - !$str - || - $str === null - || - is_bool($str) - || - "$strInt" == $str || is_int($str) - || - "$strFloat" == $str || is_float($str) - ) { - return $str; + /** + * __construct() + */ + public function __construct() + { + $this->_never_allowed_str = array( + 'document.cookie' => $this->_replacement, + 'document.write' => $this->_replacement, + '.parentNode' => $this->_replacement, + '.innerHTML' => $this->_replacement, + '-moz-binding' => $this->_replacement, + '' => '-->', + ' '<![CDATA[', + ' '<!ENTITY', + ' '<!DOCTYPE', + ' '<!ATTLIST', + '' => '<comment>', + ); + + $this->_never_allowed_str_afterwards = array( + 'FSCommand', + 'onAbort', + 'onActivate', + 'onAttribute', + 'onAfterPrint', + 'onAfterScriptExecute', + 'onAfterUpdate', + 'onAnimationEnd', + 'onAnimationIteration', + 'onAnimationStart', + 'onAriaRequest', + 'onAutoComplete', + 'onAutoCompleteError', + 'onBeforeActivate', + 'onBeforeCopy', + 'onBeforeCut', + 'onBeforeDeactivate', + 'onBeforeEditFocus', + 'onBeforePaste', + 'onBeforePrint', + 'onBeforeScriptExecute', + 'onBeforeUnload', + 'onBeforeUpdate', + 'onBegin', + 'onBlur', + 'onBounce', + 'onCancel', + 'onCanPlay', + 'onCanPlayThrough', + 'onCellChange', + 'onChange', + 'onClick', + 'onClose', + 'onCommand', + 'onCompassNeedsCalibration', + 'onContextMenu', + 'onControlSelect', + 'onCopy', + 'onCueChange', + 'onCut', + 'onDataAvailable', + 'onDataSetChanged', + 'onDataSetComplete', + 'onDblClick', + 'onDeactivate', + 'onDeviceLight', + 'onDeviceMotion', + 'onDeviceOrientation', + 'onDeviceProximity', + 'onDrag', + 'onDragDrop', + 'onDragEnd', + 'onDragEnter', + 'onDragLeave', + 'onDragOver', + 'onDragStart', + 'onDrop', + 'onDurationChange', + 'onEmptied', + 'onEnd', + 'onEnded', + 'onError', + 'onErrorUpdate', + 'onExit', + 'onFilterChange', + 'onFinish', + 'onFocus', + 'onFocusIn', + 'onFocusOut', + 'onFormChange', + 'onFormInput', + 'onFullScreenChange', + 'onFullScreenError', + 'onGotPointerCapture', + 'onHashChange', + 'onHelp', + 'onInput', + 'onInvalid', + 'onKeyDown', + 'onKeyPress', + 'onKeyUp', + 'onLanguageChange', + 'onLayoutComplete', + 'onLoad', + 'onLoadedData', + 'onLoadedMetaData', + 'onLoadStart', + 'onLoseCapture', + 'onLostPointerCapture', + 'onMediaComplete', + 'onMediaError', + 'onMessage', + 'onMouseDown', + 'onMouseEnter', + 'onMouseLeave', + 'onMouseMove', + 'onMouseOut', + 'onMouseOver', + 'onMouseUp', + 'onMouseWheel', + 'onMove', + 'onMoveEnd', + 'onMoveStart', + 'onMozFullScreenChange', + 'onMozFullScreenError', + 'onMozPointerLockChange', + 'onMozPointerLockError', + 'onMsContentZoom', + 'onMsFullScreenChange', + 'onMsFullScreenError', + 'onMsGestureChange', + 'onMsGestureDoubleTap', + 'onMsGestureEnd', + 'onMsGestureHold', + 'onMsGestureStart', + 'onMsGestureTap', + 'onMsGotPointerCapture', + 'onMsInertiaStart', + 'onMsLostPointerCapture', + 'onMsManipulationStateChanged', + 'onMsPointerCancel', + 'onMsPointerDown', + 'onMsPointerEnter', + 'onMsPointerLeave', + 'onMsPointerMove', + 'onMsPointerOut', + 'onMsPointerOver', + 'onMsPointerUp', + 'onMsSiteModeJumpListItemRemoved', + 'onMsThumbnailClick', + 'onOffline', + 'onOnline', + 'onOutOfSync', + 'onPage', + 'onPageHide', + 'onPageShow', + 'onPaste', + 'onPause', + 'onPlay', + 'onPlaying', + 'onPointerCancel', + 'onPointerDown', + 'onPointerEnter', + 'onPointerLeave', + 'onPointerLockChange', + 'onPointerLockError', + 'onPointerMove', + 'onPointerOut', + 'onPointerOver', + 'onPointerUp', + 'onPopState', + 'onProgress', + 'onPropertyChange', + 'onRateChange', + 'onReadyStateChange', + 'onReceived', + 'onRepeat', + 'onReset', + 'onResize', + 'onResizeEnd', + 'onResizeStart', + 'onResume', + 'onReverse', + 'onRowDelete', + 'onRowEnter', + 'onRowExit', + 'onRowInserted', + 'onRowsDelete', + 'onRowsEnter', + 'onRowsExit', + 'onRowsInserted', + 'onScroll', + 'onSearch', + 'onSeek', + 'onSeeked', + 'onSeeking', + 'onSelect', + 'onSelectionChange', + 'onSelectStart', + 'onStalled', + 'onStorage', + 'onStorageCommit', + 'onStart', + 'onStop', + 'onShow', + 'onSyncRestored', + 'onSubmit', + 'onSuspend', + 'onSynchRestored', + 'onTimeError', + 'onTimeUpdate', + 'onTrackChange', + 'onTransitionEnd', + 'onToggle', + 'onUnload', + 'onURLFlip', + 'onUserProximity', + 'onVolumeChange', + 'onWaiting', + 'onWebKitAnimationEnd', + 'onWebKitAnimationIteration', + 'onWebKitAnimationStart', + 'onWebKitFullScreenChange', + 'onWebKitFullScreenError', + 'onWebKitTransitionEnd', + 'onWheel', + 'seekSegmentTime', + 'userid', + 'datasrc', + 'datafld', + 'dataformatas', + 'ev:handler', + 'ev:event', + '0;url', + ); } - // removes all non-UTF-8 characters - // && - // remove NULL characters (ignored by some browsers) - $str = UTF8::clean($str, true, true, false); + /** + * XSS Clean + * + * Sanitizes data so that Cross Site Scripting Hacks can be + * prevented. This method does a fair amount of work but + * it is extremely thorough, designed to prevent even the + * most obscure XSS attempts. Nothing is ever 100% foolproof, + * of course, but I haven't been able to get anything passed + * the filter. + * + * Note: Should only be used to deal with data upon submission. + * It's not something that should be used for general + * runtime processing. + * + * @link http://channel.bitflux.ch/wiki/XSS_Prevention + * Based in part on some code and ideas from Bitflux. + * + * @link http://ha.ckers.org/xss.html + * To help develop this script I used this great list of + * vulnerabilities along with a few other hacks I've + * harvested from examining vulnerabilities in other programs. + * + * @param mixed $str input data e.g. string or array + * @param bool $is_image whether the input is an image + * + * @return string|array|boolean boolean: will return a boolean, if the "is_image"-parameter is true + * string: will return a string, if the input is a string + * array: will return a array, if the input is a array + */ + public function xss_clean($str, $is_image = false) + { + if (is_array($str)) { + foreach ($str as &$value) { + $value = $this->xss_clean($value); + } - // decode the string - $str = $this->decode_string($str); + return $str; + } - // and again... removes all non-UTF-8 characters - $str = UTF8::clean($str, true, true, false); + $str = (string)$str; + $strInt = (int)$str; + $strFloat = (float)$str; + /** @noinspection TypeUnsafeComparisonInspection */ + if ( + !$str + || + $str === null + || + is_bool($str) + || + "$strInt" == $str || is_int($str) + || + "$strFloat" == $str || is_float($str) + ) { + return $str; + } - // capture converted string for later comparison - if ($is_image === true) { - $converted_string = $str; - } + // removes all non-UTF-8 characters + // && + // remove NULL characters (ignored by some browsers) + $str = UTF8::clean($str, true, true, false); - do { - $old_str = $str; - $str = $this->_do($str, $is_image); - } while ($old_str !== $str); + // decode the string + $str = $this->decode_string($str); - /* + // and again... removes all non-UTF-8 characters + $str = UTF8::clean($str, true, true, false); + + // capture converted string for later comparison + if ($is_image === true) { + $converted_string = $str; + } + + do { + $old_str = $str; + $str = $this->_do($str, $is_image); + } while ($old_str !== $str); + + /* * images are Handled in a special way * * Essentially, we want to know that after all of the character @@ -1926,101 +1926,101 @@ class AntiXSS * string post-removal of XSS, then it fails, as there was unwanted XSS * code found and removed/changed during processing. */ - if ($is_image === true) { - /** @noinspection PhpUndefinedVariableInspection */ - return ($str === $converted_string); + if ($is_image === true) { + /** @noinspection PhpUndefinedVariableInspection */ + return ($str === $converted_string); + } + + return $str; } - return $str; - } + /** + * @param $str + * @param $is_image + * + * @return mixed + */ + protected function _do($str, $is_image) + { + // remove strings that are never allowed + $str = $this->_do_never_allowed($str); - /** - * @param $str - * @param $is_image - * - * @return mixed - */ - protected function _do($str, $is_image) - { - // remove strings that are never allowed - $str = $this->_do_never_allowed($str); + // make php tags safe for displaying + $str = $this->make_php_tags_safe($str, $is_image); - // make php tags safe for displaying - $str = $this->make_php_tags_safe($str, $is_image); + // corrects words before the browser will do it + $str = $this->compact_exploded_javascript($str); - // corrects words before the browser will do it - $str = $this->compact_exploded_javascript($str); + // remove disallowed javascript calls in links, images etc. + $str = $this->remove_disallowed_javascript($str); - // remove disallowed javascript calls in links, images etc. - $str = $this->remove_disallowed_javascript($str); + // remove evil attributes such as style, onclick and xmlns + $str = $this->remove_evil_attributes($str, $is_image); - // remove evil attributes such as style, onclick and xmlns - $str = $this->remove_evil_attributes($str, $is_image); + // sanitize naughty HTML elements + $str = $this->sanitize_naughty_html($str); - // sanitize naughty HTML elements - $str = $this->sanitize_naughty_html($str); + // sanitize naughty JavaScript elements + $str = $this->sanitize_naughty_javascript($str); - // sanitize naughty JavaScript elements - $str = $this->sanitize_naughty_javascript($str); + // final clean up - // final clean up + // This adds a bit of extra precaution in case + // something got through the above filters. + $str = $this->_do_never_allowed($str); + $str = $this->_do_never_allowed_afterwards($str); - // This adds a bit of extra precaution in case - // something got through the above filters. - $str = $this->_do_never_allowed($str); - $str = $this->_do_never_allowed_afterwards($str); + return $str; + } - return $str; - } + /** + * decode the html-tags via "UTF8::html_entity_decode()" or the string via "UTF8::urldecode()" + * + * @param string $str + * + * @return string + */ + protected function decode_string($str) + { + if (preg_match('/<\w+.*/si', $str, $matches) === 1) { + $str = preg_replace_callback( + '/<\w+.*/si', + array( + $this, + '_decode_entity', + ), + $str + ); + } else { + $str = UTF8::urldecode($str); + } - /** - * decode the html-tags via "UTF8::html_entity_decode()" or the string via "UTF8::urldecode()" - * - * @param string $str - * - * @return string - */ - protected function decode_string($str) - { - if (preg_match('/<\w+.*/si', $str, $matches) === 1) { - $str = preg_replace_callback( - '/<\w+.*/si', - array( - $this, - '_decode_entity', - ), - $str - ); - } else { - $str = UTF8::urldecode($str); - } - - return $str; - } - - /** - * Do Never Allowed - * - * @param string $str - * - * @return string - */ - protected function _do_never_allowed($str) - { - static $neverAllowedRegex; + return $str; + } + + /** + * Do Never Allowed + * + * @param string $str + * + * @return string + */ + protected function _do_never_allowed($str) + { + static $neverAllowedRegex; - if (null === $neverAllowedRegex) { - $neverAllowedRegex = implode('|', self::$_never_allowed_regex); - } + if (null === $neverAllowedRegex) { + $neverAllowedRegex = implode('|', self::$_never_allowed_regex); + } - $str = str_ireplace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str); + $str = str_ireplace(array_keys($this->_never_allowed_str), $this->_never_allowed_str, $str); - $str = preg_replace('#' . $neverAllowedRegex . '#is', $this->_replacement, $str); + $str = preg_replace('#' . $neverAllowedRegex . '#is', $this->_replacement, $str); - return (string)$str; - } + return (string)$str; + } - /* + /* * Makes PHP tags safe * * Note: XML tags are inadvertently replaced too: @@ -2034,569 +2034,569 @@ class AntiXSS * * @return string */ - public function make_php_tags_safe($str, $is_image) - { - if ($is_image === true) { - // Images have a tendency to have the PHP short opening and - // closing tags every so often so we skip those and only - // do the long opening tags. - $str = preg_replace('/<\?(php)/i', '<?\\1', $str); - } else { - $str = str_replace( - array( - '', - ), - array( - '<?', - '?>', - ), - $str - ); - } - - return (string)$str; - } - - /** - * Compact any exploded words - * - * This corrects words like: j a v a s c r i p t - * These words are compacted back to their correct state. - * - * @param string $str - * - * @return string - */ - public function compact_exploded_javascript($str) - { - static $wordsCache; - - $words = array( - 'javascript', - 'expression', - 'vbscript', - 'jscript', - 'wscript', - 'vbs', - 'script', - 'base64', - 'applet', - 'alert', - 'document', - 'write', - 'cookie', - 'window', - 'confirm', - 'prompt', - 'eval', - ); + public function make_php_tags_safe($str, $is_image) + { + if ($is_image === true) { + // Images have a tendency to have the PHP short opening and + // closing tags every so often so we skip those and only + // do the long opening tags. + $str = preg_replace('/<\?(php)/i', '<?\\1', $str); + } else { + $str = str_replace( + array( + '', + ), + array( + '<?', + '?>', + ), + $str + ); + } - foreach ($words as $word) { - if (!isset($wordsCache[$word])) { - $word = $wordsCache[$word] = chunk_split($word, 1, '\s*'); - } else { - $word = $wordsCache[$word]; - } - - // We only want to do this when it is followed by a non-word character - // That way valid stuff like "dealer to" does not become "dealerto". - $str = preg_replace_callback( - '#(' . substr($word, 0, -3) . ')(\W)#is', - array( - $this, - '_compact_exploded_words', - ), - $str - ); - } - - return (string)$str; - } - - /** - * Remove disallowed Javascript in links or img tags - * We used to do some version comparisons and use of stripos(), - * but it is dog slow compared to these simplified non-capturing - * preg_match(), especially if the pattern exists in the string - * - * Note: It was reported that not only space characters, but all in - * the following pattern can be parsed as separators between a tag name - * and its attributes: [\d\s"\'`;,\/\=\(\x00\x0B\x09\x0C] - * ... however, remove_invisible_characters() above already strips the - * hex-encoded ones, so we'll skip them below. - * - * @param string $str - * - * @return string - */ - public function remove_disallowed_javascript($str) - { - do { - $original = $str; - - if (preg_match('/]+([^>]*?)(?:>|$)#i', - array( - $this, - '_js_link_removal', - ), - $str - ); - } + return (string)$str; + } - if (preg_match('/]*?)(?:\s?/?>|$)#i', - array( - $this, - '_js_img_removal', - ), - $str + /** + * Compact any exploded words + * + * This corrects words like: j a v a s c r i p t + * These words are compacted back to their correct state. + * + * @param string $str + * + * @return string + */ + public function compact_exploded_javascript($str) + { + static $wordsCache; + + $words = array( + 'javascript', + 'expression', + 'vbscript', + 'jscript', + 'wscript', + 'vbs', + 'script', + 'base64', + 'applet', + 'alert', + 'document', + 'write', + 'cookie', + 'window', + 'confirm', + 'prompt', + 'eval', ); - } - if (preg_match('/script|xss/i', $str)) { - $str = preg_replace('##si', $this->_replacement, $str); - } - } while ($original !== $str); + foreach ($words as $word) { + if (!isset($wordsCache[$word])) { + $word = $wordsCache[$word] = chunk_split($word, 1, '\s*'); + } else { + $word = $wordsCache[$word]; + } - return (string)$str; - } + // We only want to do this when it is followed by a non-word character + // That way valid stuff like "dealer to" does not become "dealerto". + $str = preg_replace_callback( + '#(' . substr($word, 0, -3) . ')(\W)#is', + array( + $this, + '_compact_exploded_words', + ), + $str + ); + } - /** - * Remove Evil HTML Attributes (like event handlers and style) - * - * It removes the evil attribute and either: - * - * - Everything up until a space. For example, everything between the pipes: - * - * - * - * - * - * - Everything inside the quotes. For example, everything between the pipes: - * - * - * - * - * - * @param string $str The string to check - * @param bool $is_image Whether the input is an image - * - * @return string The string with the evil attributes removed - */ - public function remove_evil_attributes($str, $is_image) - { - // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Event_Handlers - - $evil_attributes = array( - 'on\w*', - 'style', - 'xmlns', - 'formaction', - 'form', - 'xlink:href', - 'seekSegmentTime', - 'FSCommand', - 'eval', - ); + return (string)$str; + } - if ($is_image === true) { - /* + /** + * Remove disallowed Javascript in links or img tags + * We used to do some version comparisons and use of stripos(), + * but it is dog slow compared to these simplified non-capturing + * preg_match(), especially if the pattern exists in the string + * + * Note: It was reported that not only space characters, but all in + * the following pattern can be parsed as separators between a tag name + * and its attributes: [\d\s"\'`;,\/\=\(\x00\x0B\x09\x0C] + * ... however, remove_invisible_characters() above already strips the + * hex-encoded ones, so we'll skip them below. + * + * @param string $str + * + * @return string + */ + public function remove_disallowed_javascript($str) + { + do { + $original = $str; + + if (preg_match('/]+([^>]*?)(?:>|$)#i', + array( + $this, + '_js_link_removal', + ), + $str + ); + } + + if (preg_match('/]*?)(?:\s?/?>|$)#i', + array( + $this, + '_js_img_removal', + ), + $str + ); + } + + if (preg_match('/script|xss/i', $str)) { + $str = preg_replace('##si', $this->_replacement, $str); + } + } while ($original !== $str); + + return (string)$str; + } + + /** + * Remove Evil HTML Attributes (like event handlers and style) + * + * It removes the evil attribute and either: + * + * - Everything up until a space. For example, everything between the pipes: + * + * + * + * + * + * - Everything inside the quotes. For example, everything between the pipes: + * + * + * + * + * + * @param string $str The string to check + * @param bool $is_image Whether the input is an image + * + * @return string The string with the evil attributes removed + */ + public function remove_evil_attributes($str, $is_image) + { + // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Event_Handlers + + $evil_attributes = array( + 'on\w*', + 'style', + 'xmlns', + 'formaction', + 'form', + 'xlink:href', + 'seekSegmentTime', + 'FSCommand', + 'eval', + ); + + if ($is_image === true) { + /* * Adobe Photoshop puts XML metadata into JFIF images, * including namespacing, so we have to allow this for images. */ - unset($evil_attributes[array_search('xmlns', $evil_attributes, true)]); - } + unset($evil_attributes[array_search('xmlns', $evil_attributes, true)]); + } - $evil_attributes_string = implode('|', $evil_attributes); + $evil_attributes_string = implode('|', $evil_attributes); - do { - $count = $temp_count = 0; + do { + $count = $temp_count = 0; - // replace occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes) - $str = preg_replace('/(<[^>]+)(?_replacement, $str, -1, $temp_count); - $count += $temp_count; + // replace occurrences of illegal attribute strings with quotes (042 and 047 are octal quotes) + $str = preg_replace('/(<[^>]+)(?_replacement, $str, -1, $temp_count); + $count += $temp_count; - // find occurrences of illegal attribute strings without quotes - $str = preg_replace('/(<[^>]+)(?]*)/is', '$1' . $this->_replacement, $str, -1, $temp_count); - $count += $temp_count; - } while ($count); + // find occurrences of illegal attribute strings without quotes + $str = preg_replace('/(<[^>]+)(?]*)/is', '$1' . $this->_replacement, $str, -1, $temp_count); + $count += $temp_count; + } while ($count); - return (string)$str; - } + return (string)$str; + } - /** - * Sanitize naughty HTML elements - * - * If a tag containing any of the words in the list - * below is found, the tag gets converted to entities. - * - * So this: - * Becomes: <blink> - * - * @param string $str - * - * @return string - */ - public function sanitize_naughty_html($str) - { - $naughty = 'alert|prompt|confirm|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|button|select|isindex|layer|link|meta|keygen|object|plaintext|style|script|textarea|title|math|video|svg|xml|xss|eval'; - $str = preg_replace_callback( - '#<(/*\s*)(' . $naughty . ')([^><]*)([><]*)#is', - array( - $this, - '_sanitize_naughty_html', - ), - $str - ); + /** + * Sanitize naughty HTML elements + * + * If a tag containing any of the words in the list + * below is found, the tag gets converted to entities. + * + * So this: + * Becomes: <blink> + * + * @param string $str + * + * @return string + */ + public function sanitize_naughty_html($str) + { + $naughty = 'alert|prompt|confirm|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|button|select|isindex|layer|link|meta|keygen|object|plaintext|style|script|textarea|title|math|video|svg|xml|xss|eval'; + $str = preg_replace_callback( + '#<(/*\s*)(' . $naughty . ')([^><]*)([><]*)#is', + array( + $this, + '_sanitize_naughty_html', + ), + $str + ); - return (string)$str; - } + return (string)$str; + } - /** - * Sanitize naughty scripting elements - * - * Similar to above, only instead of looking for - * tags it looks for PHP and JavaScript commands - * that are disallowed. Rather than removing the - * code, it simply converts the parenthesis to entities - * rendering the code un-executable. - * - * For example: eval('some code') - * Becomes: eval('some code') - * - * @param string $str - * - * @return string - */ - public function sanitize_naughty_javascript($str) - { - $str = preg_replace( - '#(alert|eval|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', - '\\1\\2(\\3)', - $str - ); + /** + * Sanitize naughty scripting elements + * + * Similar to above, only instead of looking for + * tags it looks for PHP and JavaScript commands + * that are disallowed. Rather than removing the + * code, it simply converts the parenthesis to entities + * rendering the code un-executable. + * + * For example: eval('some code') + * Becomes: eval('some code') + * + * @param string $str + * + * @return string + */ + public function sanitize_naughty_javascript($str) + { + $str = preg_replace( + '#(alert|eval|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', + '\\1\\2(\\3)', + $str + ); - return (string)$str; - } + return (string)$str; + } - /** - * Do Never Allowed Afterwards - * - * clean-up also some string, also if there is no html-tag - * - * @param string $str - * - * @return string - */ - protected function _do_never_allowed_afterwards($str) - { - static $neverAllowedStrAfterwardsRegex; + /** + * Do Never Allowed Afterwards + * + * clean-up also some string, also if there is no html-tag + * + * @param string $str + * + * @return string + */ + protected function _do_never_allowed_afterwards($str) + { + static $neverAllowedStrAfterwardsRegex; - if (null === $neverAllowedStrAfterwardsRegex) { - foreach ($this->_never_allowed_str_afterwards as &$neverAllowedStr) { - $neverAllowedStr .= '.*='; - } - unset($neverAllowedStr); + if (null === $neverAllowedStrAfterwardsRegex) { + foreach ($this->_never_allowed_str_afterwards as &$neverAllowedStr) { + $neverAllowedStr .= '.*='; + } + unset($neverAllowedStr); - $neverAllowedStrAfterwardsRegex = implode('|', $this->_never_allowed_str_afterwards); - } + $neverAllowedStrAfterwardsRegex = implode('|', $this->_never_allowed_str_afterwards); + } - $str = preg_replace('#' . $neverAllowedStrAfterwardsRegex . '#isU', $this->_replacement, $str); + $str = preg_replace('#' . $neverAllowedStrAfterwardsRegex . '#isU', $this->_replacement, $str); - return (string)$str; - } + return (string)$str; + } - /** - * set the replacement-string for not allowed strings - * - * @param string $string - */ - public function setReplacement($string) - { - $this->_replacement = (string)$string; - } + /** + * set the replacement-string for not allowed strings + * + * @param string $string + */ + public function setReplacement($string) + { + $this->_replacement = (string)$string; + } - /** - * Compact Exploded Words - * - * Callback method for xss_clean() to remove whitespace from - * things like 'j a v a s c r i p t'. - * - * @param array $matches - * - * @return string - */ - protected function _compact_exploded_words($matches) - { - return preg_replace('/\s+/', '', $matches[1]) . $matches[2]; - } + /** + * Compact Exploded Words + * + * Callback method for xss_clean() to remove whitespace from + * things like 'j a v a s c r i p t'. + * + * @param array $matches + * + * @return string + */ + protected function _compact_exploded_words($matches) + { + return preg_replace('/\s+/', '', $matches[1]) . $matches[2]; + } - /** - * Sanitize Naughty HTML - * - * Callback method for AntiXSS->sanitize_naughty_html() to remove naughty HTML elements. - * - * @param array $matches - * - * @return string - */ - protected function _sanitize_naughty_html($matches) - { - return '<' . $matches[1] . $matches[2] . $matches[3] // encode opening brace - // encode captured opening or closing brace to prevent recursive vectors: - . str_replace( - array( - '>', - '<', - ), - array( - '>', - '<', - ), - $matches[4] - ); - } - - /** - * JS Image Removal - * - * Callback method for xss_clean() to sanitize image tags. - * - * This limits the PCRE backtracks, making it more performance friendly - * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in - * PHP 5.2+ on image tag heavy strings. - * - * @param array $match - * - * @return string - */ - protected function _js_img_removal($match) - { - return $this->_js_removal($match, 'src'); - } + /** + * Sanitize Naughty HTML + * + * Callback method for AntiXSS->sanitize_naughty_html() to remove naughty HTML elements. + * + * @param array $matches + * + * @return string + */ + protected function _sanitize_naughty_html($matches) + { + return '<' . $matches[1] . $matches[2] . $matches[3] // encode opening brace + // encode captured opening or closing brace to prevent recursive vectors: + . str_replace( + array( + '>', + '<', + ), + array( + '>', + '<', + ), + $matches[4] + ); + } - /** - * JS Removal - * - * Callback method for xss_clean() to sanitize tags. - * - * This limits the PCRE backtracks, making it more performance friendly - * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in - * PHP 5.2+ on image tag heavy strings. - * - * @param array $match - * @param string $search - * - * @return string - */ - protected function _js_removal($match, $search) - { - if (!$match[0]) { - return ''; - } - - $replacer = preg_replace( - '#' . $search . '=.*?(?:(?:alert|prompt|confirm)(?:\((\')*|&\#40;)|javascript:|livescript:|wscript:|vbscript:|mocha:|charset=|window\.|document\.|\.cookie|_filter_attributes(str_replace(array('<', '>',), '', $match[1])) - ); + /** + * JS Image Removal + * + * Callback method for xss_clean() to sanitize image tags. + * + * This limits the PCRE backtracks, making it more performance friendly + * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in + * PHP 5.2+ on image tag heavy strings. + * + * @param array $match + * + * @return string + */ + protected function _js_img_removal($match) + { + return $this->_js_removal($match, 'src'); + } - return str_ireplace($match[1], $replacer, $match[0]); - } + /** + * JS Removal + * + * Callback method for xss_clean() to sanitize tags. + * + * This limits the PCRE backtracks, making it more performance friendly + * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in + * PHP 5.2+ on image tag heavy strings. + * + * @param array $match + * @param string $search + * + * @return string + */ + protected function _js_removal($match, $search) + { + if (!$match[0]) { + return ''; + } - /** - * Filter Attributes - * - * Filters tag attributes for consistency and safety. - * - * @param string $str - * - * @return string - */ - protected function _filter_attributes($str) - { - if ($str === '') { - return ''; - } - - $out = ''; - if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#i', $str, $matches)) { - foreach ($matches[0] as $match) { - $out .= preg_replace('#/\*.*?\*/#s', '', $match); - } - } - - return $out; - } - - /** - * JS Link Removal - * - * Callback method for xss_clean() to sanitize links. - * - * This limits the PCRE backtracks, making it more performance friendly - * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in - * PHP 5.2+ on link-heavy strings. - * - * @param array $match - * - * @return string - */ - protected function _js_link_removal($match) - { - return $this->_js_removal($match, 'href'); - } + $replacer = preg_replace( + '#' . $search . '=.*?(?:(?:alert|prompt|confirm)(?:\((\')*|&\#40;)|javascript:|livescript:|wscript:|vbscript:|mocha:|charset=|window\.|document\.|\.cookie|_filter_attributes(str_replace(array('<', '>',), '', $match[1])) + ); - /** - * HTML Entity Decode Callback - * - * @param array $match - * - * @return string - */ - protected function _decode_entity($match) - { - $hash = $this->xss_hash(); + return str_ireplace($match[1], $replacer, $match[0]); + } - // protect GET variables in URLs - // 901119URL5918AMP18930PROTECT8198 - $match = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-/]+)|i', $hash . '\\1=\\2', $match[0]); + /** + * Filter Attributes + * + * Filters tag attributes for consistency and safety. + * + * @param string $str + * + * @return string + */ + protected function _filter_attributes($str) + { + if ($str === '') { + return ''; + } - // un-protect URL GET vars - return str_replace($this->xss_hash(), '&', $this->_entity_decode($match)); - } + $out = ''; + if (preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#i', $str, $matches)) { + foreach ($matches[0] as $match) { + $out .= preg_replace('#/\*.*?\*/#s', '', $match); + } + } - /** - * XSS Hash - * - * Generates the XSS hash if needed and returns it. - * - * @return string XSS hash - */ - public function xss_hash() - { - if ($this->_xss_hash === null) { - $rand = Bootup::get_random_bytes(16); - - if (!$rand) { - $this->_xss_hash = md5(uniqid(mt_rand(), true)); - } else { - $this->_xss_hash = bin2hex($rand); - } - } - - return $this->_xss_hash; - } - - /** - * @param $str - * - * @return string - */ - protected function _entity_decode($str) - { - static $entities; + return $out; + } - $flags = Bootup::is_php('5.4') ? ENT_QUOTES | ENT_HTML5 : ENT_QUOTES; + /** + * JS Link Removal + * + * Callback method for xss_clean() to sanitize links. + * + * This limits the PCRE backtracks, making it more performance friendly + * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in + * PHP 5.2+ on link-heavy strings. + * + * @param array $match + * + * @return string + */ + protected function _js_link_removal($match) + { + return $this->_js_removal($match, 'href'); + } - // decode - if (strpos($str, $this->xss_hash()) !== false) { - $str = UTF8::html_entity_decode($str, $flags); - } else { - $str = UTF8::urldecode($str); + /** + * HTML Entity Decode Callback + * + * @param array $match + * + * @return string + */ + protected function _decode_entity($match) + { + $hash = $this->xss_hash(); + + // protect GET variables in URLs + // 901119URL5918AMP18930PROTECT8198 + $match = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-/]+)|i', $hash . '\\1=\\2', $match[0]); + + // un-protect URL GET vars + return str_replace($this->xss_hash(), '&', $this->_entity_decode($match)); } - // decode-again, for e.g. HHVM, PHP 5.3, miss configured applications ... - if (preg_match_all('/&[a-z]{2,}[;]{0}/i', $str, $matches)) { - if (null === $entities) { - - // links: - // - http://dev.w3.org/html5/html-author/charref - // - http://www.w3schools.com/charsets/ref_html_entities_n.asp - $entitiesSecurity = array( - '�' => '', - '�' => '', - '' => '', - '' => '', - '>⃒' => '', - '' => '', - '' => '', - '­' => '', - '­' => '', - '­' => '', - ':' => ':', - ':' => ':', - ':' => ':', - '(' => '(', - '(' => '(', - '(' => '(', - ')' => ')', - ')' => ')', - ')' => ')', - '?' => '?', - '?' => '?', - '?' => '?', - '/' => '/', - '/' => '/', - '/' => '/', - ''' => '\'', - ''' => '\'', - ''' => '\'', - '\' => '\\', - '\' => '\\', - '\' => '\\', - ',' => ',', - ',' => ',', - ',' => ',', - '.' => '.', - '.' => '.', - '"' => '"', - '"' => '"', - '"' => '"', - '"' => '"', - '`' => '`', - '`' => '`', - '`' => '`', - '`' => '`', - '.' => '.', - '=' => '=', - '=' => '=', - '=' => '=', - '&newline;' => "\n", - ' ' => "\n", - ' ' => "\n", - '&tab;' => "\t", - ' ' => "\n", - ' ' => "\n", - ); + /** + * XSS Hash + * + * Generates the XSS hash if needed and returns it. + * + * @return string XSS hash + */ + public function xss_hash() + { + if ($this->_xss_hash === null) { + $rand = Bootup::get_random_bytes(16); + + if (!$rand) { + $this->_xss_hash = md5(uniqid(mt_rand(), true)); + } else { + $this->_xss_hash = bin2hex($rand); + } + } - $entitiesTmp = get_html_translation_table(HTML_ENTITIES, $flags); - $entitiesTmp = array_merge(self::$entitiesFallback, $entitiesTmp); + return $this->_xss_hash; + } - $entities = array_merge( - $entitiesSecurity, - array_map('strtolower', array_flip($entitiesTmp)) - ); + /** + * @param $str + * + * @return string + */ + protected function _entity_decode($str) + { + static $entities; + + $flags = Bootup::is_php('5.4') ? ENT_QUOTES | ENT_HTML5 : ENT_QUOTES; + + // decode + if (strpos($str, $this->xss_hash()) !== false) { + $str = UTF8::html_entity_decode($str, $flags); + } else { + $str = UTF8::urldecode($str); } - $replace = array(); - $matches = array_unique(array_map('strtolower', $matches[0])); - foreach ($matches as $match) { - $match .= ';'; - if (array_key_exists($match, $entities) === true) { - $replace[$match] = $entities[$match]; + // decode-again, for e.g. HHVM, PHP 5.3, miss configured applications ... + if (preg_match_all('/&[a-z]{2,}[;]{0}/i', $str, $matches)) { + if (null === $entities) { + + // links: + // - http://dev.w3.org/html5/html-author/charref + // - http://www.w3schools.com/charsets/ref_html_entities_n.asp + $entitiesSecurity = array( + '�' => '', + '�' => '', + '' => '', + '' => '', + '>⃒' => '', + '' => '', + '' => '', + '­' => '', + '­' => '', + '­' => '', + ':' => ':', + ':' => ':', + ':' => ':', + '(' => '(', + '(' => '(', + '(' => '(', + ')' => ')', + ')' => ')', + ')' => ')', + '?' => '?', + '?' => '?', + '?' => '?', + '/' => '/', + '/' => '/', + '/' => '/', + ''' => '\'', + ''' => '\'', + ''' => '\'', + '\' => '\\', + '\' => '\\', + '\' => '\\', + ',' => ',', + ',' => ',', + ',' => ',', + '.' => '.', + '.' => '.', + '"' => '"', + '"' => '"', + '"' => '"', + '"' => '"', + '`' => '`', + '`' => '`', + '`' => '`', + '`' => '`', + '.' => '.', + '=' => '=', + '=' => '=', + '=' => '=', + '&newline;' => "\n", + ' ' => "\n", + ' ' => "\n", + '&tab;' => "\t", + ' ' => "\n", + ' ' => "\n", + ); + + $entitiesTmp = get_html_translation_table(HTML_ENTITIES, $flags); + $entitiesTmp = array_merge(self::$entitiesFallback, $entitiesTmp); + + $entities = array_merge( + $entitiesSecurity, + array_map('strtolower', array_flip($entitiesTmp)) + ); + } + + $replace = array(); + $matches = array_unique(array_map('strtolower', $matches[0])); + foreach ($matches as $match) { + $match .= ';'; + if (array_key_exists($match, $entities) === true) { + $replace[$match] = $entities[$match]; + } } - } - if (count($replace) > 0) { - $str = str_ireplace(array_keys($replace), array_values($replace), $str); + if (count($replace) > 0) { + $str = str_ireplace(array_keys($replace), array_values($replace), $str); + } } - } - return $str; - } + return $str; + } } diff --git a/app/Utils/Check.php b/app/Utils/Check.php index fc6eda1f..27a55dbf 100644 --- a/app/Utils/Check.php +++ b/app/Utils/Check.php @@ -8,7 +8,7 @@ class Check // public static function isEmailLegal($email) { - if (filter_var($email, FILTER_VALIDATE_EMAIL)&&strlen($email)<=32) { + if (filter_var($email, FILTER_VALIDATE_EMAIL) && strlen($email) <= 32) { return true; } else { return false; diff --git a/app/Utils/CloudflareDriver.php b/app/Utils/CloudflareDriver.php index 9ccb5bdb..4503a61f 100644 --- a/app/Utils/CloudflareDriver.php +++ b/app/Utils/CloudflareDriver.php @@ -7,6 +7,7 @@ */ namespace App\Utils; + use App\Services\Config; class CloudflareDriver @@ -44,10 +45,10 @@ class CloudflareDriver $recordCount = $r->result_info->count; $records = $r->result; - if ($recordCount == 0){ + if ($recordCount == 0) { self::addRecord($dns, $zoneID, 'A', $name, $content); - } elseif ($recordCount >= 1){ - foreach ($records as $record){ + } elseif ($recordCount >= 1) { + foreach ($records as $record) { $recordID = $record->id; self::modifyRecord($dns, $zoneID, $recordID, $name, $content, $proxied); } diff --git a/app/Utils/ConfRender.php b/app/Utils/ConfRender.php index 2f1a0a3e..2526bb56 100644 --- a/app/Utils/ConfRender.php +++ b/app/Utils/ConfRender.php @@ -11,8 +11,10 @@ namespace App\Utils; use Smarty; -class ConfRender { - public static function getTemplateRender() { +class ConfRender +{ + public static function getTemplateRender() + { $smarty = new smarty(); $smarty->settemplatedir(BASE_PATH . '/resources/conf/'); diff --git a/app/Utils/Cookie.php b/app/Utils/Cookie.php index 4e34153b..434ba88f 100644 --- a/app/Utils/Cookie.php +++ b/app/Utils/Cookie.php @@ -10,7 +10,7 @@ class Cookie setcookie($key, $value, $time, '/'); } } - + public static function setwithdomain($arg, $time, $domain) { foreach ($arg as $key => $value) { diff --git a/app/Utils/DatatablesHelper.php b/app/Utils/DatatablesHelper.php index 372119bb..355b87c2 100644 --- a/app/Utils/DatatablesHelper.php +++ b/app/Utils/DatatablesHelper.php @@ -12,6 +12,7 @@ class DatatablesHelper implements DatabaseInterface { protected $escape = []; protected $connection; + public function __construct($config = null) { $capsule = new Capsule; @@ -22,28 +23,32 @@ class DatatablesHelper implements DatabaseInterface } catch (QueryException $e) { } } + public function connect() { return $this; } + public function query($query) { $data = $this->connection->select($query, $this->escape); $row = []; foreach ($data as $item) { - $row[] = (array) $item; + $row[] = (array)$item; } return $row; } + public function count($query) { $query = "Select count(*) as rowcount," . substr($query, 6); $data = $this->connection->select($query, $this->escape); return $data[0]->rowcount; } + public function escape($string) { - $this->escape[':escape' . (count($this->escape) + 1) ] = '%' . $string . '%'; + $this->escape[':escape' . (count($this->escape) + 1)] = '%' . $string . '%'; return ":escape" . (count($this->escape)); } } diff --git a/app/Utils/Discord.php b/app/Utils/Discord.php index a16842e5..429ed2ee 100644 --- a/app/Utils/Discord.php +++ b/app/Utils/Discord.php @@ -6,68 +6,71 @@ use App\Models\User; use App\Services\Config; use App\Controllers\LinkController; -class Discord{ - public static function set(){ - $loop = \React\EventLoop\Factory::create(); - $client = new \CharlotteDunois\Yasmin\Client(array(), $loop); - $client->on('error', function ($error) { - echo $error.PHP_EOL; - }); - - $client->on('ready', function () use ($client) { - echo 'Logged in as '.$client->user->tag.' created on '.$client->user->createdAt->format('d.m.Y H:i:s').PHP_EOL; - }); +class Discord +{ + public static function set() + { + $loop = \React\EventLoop\Factory::create(); + $client = new \CharlotteDunois\Yasmin\Client(array(), $loop); + $client->on('error', function ($error) { + echo $error . PHP_EOL; + }); - $client->on('message', function ($message) { - //echo 'Received Message from '.$message->author->tag.' in '.($message->channel->type === 'text' ? 'channel #'.$message->channel->name : 'DM').' with '.$message->attachments->count().' attachment(s) and '.\count($message->embeds).' embed(s)'.PHP_EOL; - if(strpos($message->content, '!bind') === 0) { - bindQR($client, $message); - } - elseif(strpos($message->content, '!checkin') === 0) { - checkin($client, $message); - } - elseif(strpos($message->content, '!traffic') === 0) { - traffic($client, $message); - } - }); + $client->on('ready', function () use ($client) { + echo 'Logged in as ' . $client->user->tag . ' created on ' . $client->user->createdAt->format('d.m.Y H:i:s') . PHP_EOL; + }); - $client->login(Config::get('discord_token'))->done(); - $loop->run(); - echo('ÉèÖóɹ¦£¡'.PHP_EOL); - } - - public static function bindQR($client, $message){ - $message->channel->send("ÕýÔڽâÂ룬ÇëÉԺ󡣡£¡£"); - $attachments=$message->attachments->toArray(); - reset($attachments); - $qrcode_text=QRcode::decod(current($attachments)->url); - if($qrcode_text==null){ - $message->channel->send("½âÂëʧ°Ü"); - return; - } - - if (substr($qrcode_text, 0, 11) == 'mod://bind/' && strlen($qrcode_text) == 27) { - $uid = TelegramSessionManager::verify_bind_session(substr($qrcode_text, 11)); - if ($uid == 0) { - $message->channel->send("°ó¶¨ʧ°ܣ¬¶þάÂëÎÞЧ£º" . substr($qrcode_text, 11)."¶þάÂëµÄÓÐЧÆÚΪ10·ÖÖӣ¬Ç볢ÊÔˢÐÂÍøվµġ°×ÊÁϱ༭¡±ҳÃæÒԸüжþάÂë"); - return; - } - $user = User::where('id', $uid)->first(); - $user->discord = $message->author->id; - $user->im_type = 5; - $user->im_value = $message->author->username; - $user->save(); - $reply['message']= "°󶨳ɹ¦£¬ÓÊÏ䣺" . $user->email; - } - - $message->channel->send("δ֪ÄÚÈݶþάÂë"); - } + $client->on('message', function ($message) { + //echo 'Received Message from '.$message->author->tag.' in '.($message->channel->type === 'text' ? 'channel #'.$message->channel->name : 'DM').' with '.$message->attachments->count().' attachment(s) and '.\count($message->embeds).' embed(s)'.PHP_EOL; + if (strpos($message->content, '!bind') === 0) { + bindQR($client, $message); + } elseif (strpos($message->content, '!checkin') === 0) { + checkin($client, $message); + } elseif (strpos($message->content, '!traffic') === 0) { + traffic($client, $message); + } + }); - public static function checkin($client, $message){ - - } + $client->login(Config::get('discord_token'))->done(); + $loop->run(); + echo('���óɹ���' . PHP_EOL); + } - public static function traffic($client, $message){ - - } + public static function bindQR($client, $message) + { + $message->channel->send("���ڽ��룬���Ժ󡣡���"); + $attachments = $message->attachments->toArray(); + reset($attachments); + $qrcode_text = QRcode::decod(current($attachments)->url); + if ($qrcode_text == null) { + $message->channel->send("����ʧ��"); + return; + } + + if (substr($qrcode_text, 0, 11) == 'mod://bind/' && strlen($qrcode_text) == 27) { + $uid = TelegramSessionManager::verify_bind_session(substr($qrcode_text, 11)); + if ($uid == 0) { + $message->channel->send("��ʧ�ܣ���ά����Ч��" . substr($qrcode_text, 11) . "��ά�����Ч��Ϊ10���ӣ��볢��ˢ����վ�ġ����ϱ༭��ҳ���Ը��¶�ά��"); + return; + } + $user = User::where('id', $uid)->first(); + $user->discord = $message->author->id; + $user->im_type = 5; + $user->im_value = $message->author->username; + $user->save(); + $reply['message'] = "�󶨳ɹ������䣺" . $user->email; + } + + $message->channel->send("δ֪���ݶ�ά��"); + } + + public static function checkin($client, $message) + { + + } + + public static function traffic($client, $message) + { + + } } \ No newline at end of file diff --git a/app/Utils/DoiAMPay.php b/app/Utils/DoiAMPay.php index 34c737d0..4461d501 100644 --- a/app/Utils/DoiAMPay.php +++ b/app/Utils/DoiAMPay.php @@ -1,4 +1,5 @@ assign("enabled",Config::get("doiampay")['enabled'])->fetch("user/doiam.tpl"); + public static function render() + { + return View::getSmarty()->assign("enabled", Config::get("doiampay")['enabled'])->fetch("user/doiam.tpl"); } - public function handle($request, $response, $args){ + public function handle($request, $response, $args) + { $type = $request->getParam('type'); $price = $request->getParam('price'); - if(Config::get("doiampay")['enabled'][$type]==0){ - return json_encode(['errcode'=>-1,'errmsg'=>"非法的支付方式."]); + if (Config::get("doiampay")['enabled'][$type] == 0) { + return json_encode(['errcode' => -1, 'errmsg' => "非法的支付方式."]); } - if($price <= 0){ - return json_encode(['errcode'=>-1,'errmsg'=>"非法的金额."]); + if ($price <= 0) { + return json_encode(['errcode' => -1, 'errmsg' => "非法的金额."]); } $user = Auth::getUser(); $settings = Config::get("doiampay")['mchdata'][$type]; @@ -43,118 +47,135 @@ class DoiAMPay{ 'price' => $price, 'phone' => $settings['phone'], 'mchid' => $settings['mchid'], - 'subject' => Config::get("appName")."充值".$price."元", - 'body' => Config::get("appName")."充值".$price."元", + 'subject' => Config::get("appName") . "充值" . $price . "元", + 'body' => Config::get("appName") . "充值" . $price . "元", 'type' => 'Mod', ]; - $data = DoiAM::sign($data,$settings['token']); - $ret = DoiAM::post("https://api.daimiyun.cn/v2/".$type."/create",$data); - $result = json_decode($ret,true); - if($result and $result['errcode']==0){ - $result['pid']=$pl->id; + $data = DoiAM::sign($data, $settings['token']); + $ret = DoiAM::post("https://api.daimiyun.cn/v2/" . $type . "/create", $data); + $result = json_decode($ret, true); + if ($result and $result['errcode'] == 0) { + $result['pid'] = $pl->id; return json_Encode($result); - }else{ + } else { return json_encode([ - 'errcode'=>-1, - 'errmsg' => "接口调用失败!".$ret, + 'errcode' => -1, + 'errmsg' => "接口调用失败!" . $ret, ]); } return $result; } - public function status($request, $response, $args){ + + public function status($request, $response, $args) + { return json_encode(Paylist::find($_POST['pid'])); } - public function handle_return($request, $response, $args){ + + public function handle_return($request, $response, $args) + { $money = $_GET['money']; - echo "您已经成功支付 $money 元,正在跳转.."; - echo << location.href="/user/code"; HTML; return; } - public function handle_callback($request, $response, $args){ + + public function handle_callback($request, $response, $args) + { $order_data = $_POST; - $status = $order_data['status']; //获取传递过来的交易状态 + $status = $order_data['status']; //获取传递过来的交易状态 $invoiceid = $order_data['out_trade_no']; //订单号 - $transid = $order_data['trade_no']; //转账交易号 - $amount = $order_data['money']; //获取递过来的总价格 - if(!DoiAM::checksign($_POST,Config::get("doiampay")['mchdata'][$args['type']]['token'])){ - return (json_encode(array('errcode'=>2333))); + $transid = $order_data['trade_no']; //转账交易号 + $amount = $order_data['money']; //获取递过来的总价格 + if (!DoiAM::checksign($_POST, Config::get("doiampay")['mchdata'][$args['type']]['token'])) { + return (json_encode(array('errcode' => 2333))); } if ($status == 'success') { - $p=Paylist::find($invoiceid); - if($p->status==1){ - return json_encode(['errcode'=>0]); + $p = Paylist::find($invoiceid); + if ($p->status == 1) { + return json_encode(['errcode' => 0]); } - $p->status=1; + $p->status = 1; $p->save(); $user = User::find($p->userid); $user->money += $p->total; $user->save(); - $codeq=new Code(); - $codeq->code=['wepay' => "微信" , 'qqpay' => 'QQ支付','alipay' => "支付宝"][$args['type']]."充值"; - $codeq->isused=1; - $codeq->type=-1; - $codeq->number=$p->total; - $codeq->usedatetime=date("Y-m-d H:i:s"); - $codeq->userid=$user->id; + $codeq = new Code(); + $codeq->code = ['wepay' => "微信", 'qqpay' => 'QQ支付', 'alipay' => "支付宝"][$args['type']] . "充值"; + $codeq->isused = 1; + $codeq->type = -1; + $codeq->number = $p->total; + $codeq->usedatetime = date("Y-m-d H:i:s"); + $codeq->userid = $user->id; $codeq->save(); - if ($user->ref_by!=""&&$user->ref_by!=0&&$user->ref_by!=null) { - $gift_user=User::where("id", "=", $user->ref_by)->first(); - $gift_user->money=($gift_user->money+($codeq->number*(Config::get('code_payback')/100))); + if ($user->ref_by != "" && $user->ref_by != 0 && $user->ref_by != null) { + $gift_user = User::where("id", "=", $user->ref_by)->first(); + $gift_user->money = ($gift_user->money + ($codeq->number * (Config::get('code_payback') / 100))); $gift_user->save(); - $Payback=new Payback(); - $Payback->total=$codeq->number; - $Payback->userid=$user->id; - $Payback->ref_by=$user->ref_by; - $Payback->ref_get=$codeq->number*(Config::get('code_payback')/100); - $Payback->datetime=time(); + $Payback = new Payback(); + $Payback->total = $codeq->number; + $Payback->userid = $user->id; + $Payback->ref_by = $user->ref_by; + $Payback->ref_get = $codeq->number * (Config::get('code_payback') / 100); + $Payback->datetime = time(); $Payback->save(); } - return json_encode(['errcode'=>0]); - }else{ + return json_encode(['errcode' => 0]); + } else { return ''; } } } -class DoiAM{ - public static function sort(&$array){ + +class DoiAM +{ + public static function sort(&$array) + { ksort($array); } - public static function getsign($array,$key){ + + public static function getsign($array, $key) + { unset($array['sign']); self::sort($array); - $sss=http_build_query($array); - $sign=hash("sha256",$sss.$key); - $sign=sha1($sign.hash("sha256",$key)); + $sss = http_build_query($array); + $sign = hash("sha256", $sss . $key); + $sign = sha1($sign . hash("sha256", $key)); return $sign; } - public static function sign($array,$key){ - $array['sign']=self::getSign($array,$key); + + public static function sign($array, $key) + { + $array['sign'] = self::getSign($array, $key); return $array; } - public static function checksign($array,$key){ + + public static function checksign($array, $key) + { $new = $array; - $new=self::sign($new,$key); - if(!isset($array['sign'])){ + $new = self::sign($new, $key); + if (!isset($array['sign'])) { return false; } - return $array['sign']==$new['sign']; + return $array['sign'] == $new['sign']; } - public static function post($url, $data = null){ - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); - if (!empty($data)){ - curl_setopt($curl, CURLOPT_POST, 1); - curl_setopt($curl, CURLOPT_POSTFIELDS, $data); - } - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - $output = curl_exec($curl); - curl_close($curl); - return $output; + + public static function post($url, $data = null) + { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); + if (!empty($data)) { + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); + } + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + $output = curl_exec($curl); + curl_close($curl); + return $output; } } diff --git a/app/Utils/GA.php b/app/Utils/GA.php index cfb2955f..698d6737 100644 --- a/app/Utils/GA.php +++ b/app/Utils/GA.php @@ -10,7 +10,6 @@ namespace App\Utils; * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://www.phpgangsta.de/ */ - class GA { protected $_codeLength = 6; @@ -50,7 +49,7 @@ class GA $secretkey = $this->_base32Decode($secret); // Pack time into binary string - $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice); + $time = chr(0) . chr(0) . chr(0) . chr(0) . pack('N*', $timeSlice); // Hash it with users secret key $hm = hash_hmac('SHA1', $time, $secretkey, true); // Use last nipple of result as index/offset @@ -78,18 +77,18 @@ class GA */ public function getQRCodeGoogleUrl($name, $secret, $title = null) { - $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.''); + $urlencoded = urlencode('otpauth://totp/' . $name . '?secret=' . $secret . ''); if (isset($title)) { - $urlencoded .= urlencode('&issuer='.urlencode($title)); + $urlencoded .= urlencode('&issuer=' . urlencode($title)); } - return 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl='.$urlencoded.''; + return 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=' . $urlencoded . ''; } - + public function getUrl($name, $secret, $title = null) { - $urlencoded = 'otpauth://totp/'.$name.'?secret='.$secret.''; + $urlencoded = 'otpauth://totp/' . $name . '?secret=' . $secret . ''; if (isset($title)) { - $urlencoded .= '&issuer='.urlencode($title); + $urlencoded .= '&issuer=' . urlencode($title); } return $urlencoded; } @@ -160,7 +159,7 @@ class GA $secret = str_replace('=', '', $secret); $secret = str_split($secret); $binaryString = ""; - for ($i = 0; $i < count($secret); $i = $i+8) { + for ($i = 0; $i < count($secret); $i = $i + 8) { $x = ""; if (!in_array($secret[$i], $base32chars)) { return false; @@ -170,7 +169,7 @@ class GA } $eightBits = str_split($x, 8); for ($z = 0; $z < count($eightBits); $z++) { - $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y:""; + $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : ""; } } return $binaryString; diff --git a/app/Utils/Geetest.php b/app/Utils/Geetest.php index 83801bdd..6538ad6e 100644 --- a/app/Utils/Geetest.php +++ b/app/Utils/Geetest.php @@ -21,7 +21,7 @@ class Geetest $_SESSION['user_id'] = $user_id; return $ret; } - + public static function verify($geetest_challenge, $geetest_validate, $geetest_seccode) { session_start(); diff --git a/app/Utils/GeetestLib.php b/app/Utils/GeetestLib.php index fe864b05..471c09f1 100644 --- a/app/Utils/GeetestLib.php +++ b/app/Utils/GeetestLib.php @@ -12,13 +12,13 @@ class GeetestLib const GT_SDK_VERSION = 'php_3.2.0'; public static $connectTimeout = 3; - public static $socketTimeout = 3; + public static $socketTimeout = 3; private $response; public function __construct($captcha_id, $private_key) { - $this->captcha_id = $captcha_id; + $this->captcha_id = $captcha_id; $this->private_key = $private_key; } @@ -51,10 +51,10 @@ class GeetestLib */ private function success_process($challenge) { - $challenge = md5($challenge . $this->private_key); - $result = array( - 'success' => 1, - 'gt' => $this->captcha_id, + $challenge = md5($challenge . $this->private_key); + $result = array( + 'success' => 1, + 'gt' => $this->captcha_id, 'challenge' => $challenge ); $this->response = $result; @@ -65,12 +65,12 @@ class GeetestLib */ private function failback_process() { - $rnd1 = md5(rand(0, 100)); - $rnd2 = md5(rand(0, 100)); - $challenge = $rnd1 . substr($rnd2, 0, 2); - $result = array( - 'success' => 0, - 'gt' => $this->captcha_id, + $rnd1 = md5(rand(0, 100)); + $rnd2 = md5(rand(0, 100)); + $challenge = $rnd1 . substr($rnd2, 0, 2); + $result = array( + 'success' => 0, + 'gt' => $this->captcha_id, 'challenge' => $challenge ); $this->response = $result; @@ -110,12 +110,12 @@ class GeetestLib } $data = array( "seccode" => $seccode, - "sdk" => self::GT_SDK_VERSION, + "sdk" => self::GT_SDK_VERSION, ); if (($user_id != null) and (is_string($user_id))) { $data["user_id"] = $user_id; } - $url = "http://api.geetest.com/validate.php"; + $url = "http://api.geetest.com/validate.php"; $codevalidate = $this->post_request($url, $data); if ($codevalidate == md5($seccode)) { return 1; @@ -139,12 +139,12 @@ class GeetestLib public function fail_validate($challenge, $validate, $seccode) { if ($validate) { - $value = explode("_", $validate); - $ans = $this->decode_response($challenge, $value['0']); - $bg_idx = $this->decode_response($challenge, $value['1']); + $value = explode("_", $validate); + $ans = $this->decode_response($challenge, $value['0']); + $bg_idx = $this->decode_response($challenge, $value['1']); $grp_idx = $this->decode_response($challenge, $value['2']); - $x_pos = $this->get_failback_pic_ans($bg_idx, $grp_idx); - $answer = abs($ans - $x_pos); + $x_pos = $this->get_failback_pic_ans($bg_idx, $grp_idx); + $answer = abs($ans - $x_pos); if ($answer < 4) { return 1; } else { @@ -196,14 +196,14 @@ class GeetestLib curl_close($ch); } else { - $opts = array( + $opts = array( 'http' => array( - 'method' => "GET", + 'method' => "GET", 'timeout' => self::$connectTimeout + self::$socketTimeout, ) ); $context = stream_context_create($opts); - $data = file_get_contents($url, false, $context); + $data = file_get_contents($url, false, $context); } return $data; @@ -246,16 +246,16 @@ class GeetestLib curl_close($ch); } else { if ($postdata) { - $opts = array( + $opts = array( 'http' => array( - 'method' => 'POST', - 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n", + 'method' => 'POST', + 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n", 'content' => $data, 'timeout' => self::$connectTimeout + self::$socketTimeout ) ); $context = stream_context_create($opts); - $data = file_get_contents($url, false, $context); + $data = file_get_contents($url, false, $context); } } @@ -275,13 +275,13 @@ class GeetestLib if (strlen($string) > 100) { return 0; } - $key = array(); - $chongfu = array(); - $shuzi = array("0" => 1, "1" => 2, "2" => 5, "3" => 10, "4" => 50); - $count = 0; - $res = 0; + $key = array(); + $chongfu = array(); + $shuzi = array("0" => 1, "1" => 2, "2" => 5, "3" => 10, "4" => 50); + $count = 0; + $res = 0; $array_challenge = str_split($challenge); - $array_value = str_split($string); + $array_value = str_split($string); for ($i = 0; $i < strlen($challenge); $i++) { $item = $array_challenge[$i]; if (in_array($item, $chongfu)) { @@ -312,11 +312,11 @@ class GeetestLib if (strlen($x_str) != 5) { return 0; } - $sum_val = 0; + $sum_val = 0; $x_pos_sup = 200; - $sum_val = base_convert($x_str, 16, 10); - $result = $sum_val % $x_pos_sup; - $result = ($result < 40) ? 40 : $result; + $sum_val = base_convert($x_str, 16, 10); + $result = $sum_val % $x_pos_sup; + $result = ($result < 40) ? 40 : $result; return $result; } @@ -329,7 +329,7 @@ class GeetestLib private function get_failback_pic_ans($full_bg_index, $img_grp_index) { $full_bg_name = substr(md5($full_bg_index), 0, 9); - $bg_name = substr(md5($img_grp_index), 10, 9); + $bg_name = substr(md5($img_grp_index), 10, 9); $answer_decode = ""; // 通过两个字符串奇数和偶数位拼接产生答案位 @@ -341,7 +341,7 @@ class GeetestLib } } $x_decode = substr($answer_decode, 4, 5); - $x_pos = $this->get_x_pos_from_str($x_decode); + $x_pos = $this->get_x_pos_from_str($x_decode); return $x_pos; } @@ -354,11 +354,11 @@ class GeetestLib */ private function decodeRandBase($challenge) { - $base = substr($challenge, 32, 2); + $base = substr($challenge, 32, 2); $tempArray = array(); for ($i = 0; $i < strlen($base); $i++) { $tempAscii = ord($base[$i]); - $result = ($tempAscii > 57) ? ($tempAscii - 87) : ($tempAscii - 48); + $result = ($tempAscii > 57) ? ($tempAscii - 87) : ($tempAscii - 48); array_push($tempArray, $result); } $decodeRes = $tempArray['0'] * 36 + $tempArray['1']; diff --git a/app/Utils/HTTPSocket.php b/app/Utils/HTTPSocket.php index 319b4e49..19c24be3 100644 --- a/app/Utils/HTTPSocket.php +++ b/app/Utils/HTTPSocket.php @@ -1,4 +1,5 @@ * @package HTTPSocket * @version 2.7.2 - * 2.7.2 * added x-use-https header check * added max number of location redirects * added custom settable message if x-use-https is found, so users can be told where to set their scripts * if a redirect host is https, add ssl:// to remote_host - * 2.7.1 * added isset to headers['location'], line 306 - */ class HTTPSocket { public $version = '2.7.2'; - + /* all vars are private except $error, $query_cache, and $doFollowLocationHeader */ public $method = 'GET'; @@ -123,7 +121,7 @@ class HTTPSocket if (preg_match('!^http://!i', $request) || preg_match('!^https://!i', $request)) { $location = parse_url($request); if (preg_match('!^https://!i', $request)) { - $this->connect('ssl://'.$location['host'], $location['port']); + $this->connect('ssl://' . $location['host'], $location['port']); } else { $this->connect($location['host'], $location['port']); } @@ -142,7 +140,7 @@ class HTTPSocket 'User-Agent' => "HTTPSocket/$this->version", 'Host' => ($this->remote_port == 80 ? $this->remote_host : "$this->remote_host:$this->remote_port"), 'Accept' => '*/*', - 'Connection' => 'Close' ); + 'Connection' => 'Close'); foreach ($this->extra_headers as $key => $value) { $array_headers[$key] = $value; @@ -155,7 +153,7 @@ class HTTPSocket $pairs = array(); foreach ($content as $key => $value) { - $pairs[] = "$key=".urlencode($value); + $pairs[] = "$key=" . urlencode($value); } $content = join('&', $pairs); @@ -183,7 +181,7 @@ class HTTPSocket // if we have a username and password, add the header if (isset($this->remote_uname) && isset($this->remote_passwd)) { - $array_headers['Authorization'] = 'Basic '.base64_encode("$this->remote_uname:$this->remote_passwd"); + $array_headers['Authorization'] = 'Basic ' . base64_encode("$this->remote_uname:$this->remote_passwd"); } // for DA skins: if $this->remote_passwd is NULL, try to use the login key system @@ -195,8 +193,7 @@ class HTTPSocket if ($this->method == 'POST') { $array_headers['Content-type'] = 'application/x-www-form-urlencoded'; $array_headers['Content-length'] = strlen($content); - } - // else method is GET or HEAD. we don't support anything else right now. + } // else method is GET or HEAD. we don't support anything else right now. else { if ($content) { $request .= "?$content"; @@ -240,21 +237,21 @@ class HTTPSocket $elapsedTime = time() - $startTime; if ($elapsedTime > 0) { - $this->lastTransferSpeed = ($length/1024)/$elapsedTime; + $this->lastTransferSpeed = ($length / 1024) / $elapsedTime; } if ($doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck) { - $this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~".(($length/1024)/$elapsedTime)."), dropping connection..."; + $this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~" . (($length / 1024) / $elapsedTime) . "), dropping connection..."; $this->result_status_code = 503; break; } } if ($this->lastTransferSpeed == 0) { - $this->lastTransferSpeed = $length/1024; + $this->lastTransferSpeed = $length / 1024; } } - + list($this->result_header, $this->result_body) = preg_split("/\r\n\r\n/", $this->result, 2); if ($this->bind_host) { @@ -282,13 +279,13 @@ class HTTPSocket // now, if we're being passed a location header, should we follow it? if ($this->doFollowLocationHeader) { //dont bother if we didn't even setup the script correctly - if (isset($headers['x-use-https']) && $headers['x-use-https']=='yes') { + if (isset($headers['x-use-https']) && $headers['x-use-https'] == 'yes') { die($this->ssl_setting_message); } if (isset($headers['location'])) { if ($this->max_redirects <= 0) { - die("Too many redirects on: ".$headers['location']); + die("Too many redirects on: " . $headers['location']); } $this->max_redirects--; @@ -377,8 +374,8 @@ class HTTPSocket public function fetch_header($header = '') { $array_headers = preg_split("/\r\n/", $this->result_header); - - $array_return = array( 0 => $array_headers[0] ); + + $array_return = array(0 => $array_headers[0]); unset($array_headers[0]); foreach ($array_headers as $pair) { diff --git a/app/Utils/Pay.php b/app/Utils/Pay.php index bd61e6a2..580a05f1 100644 --- a/app/Utils/Pay.php +++ b/app/Utils/Pay.php @@ -1,5 +1,7 @@ fp = 0; if (($this->fp = fopen($filename, 'rb')) !== false) { @@ -33,210 +34,206 @@ class QQWry } } - + public function __destruct() { if ($this->fp) { fclose($this->fp); } - + $this->fp = 0; } - - + + private function getlong() { $result = unpack('Vlong', fread($this->fp, 4)); - + return $result['long']; } - - + + private function getlong3() { - $result = unpack('Vlong', fread($this->fp, 3).chr(0)); - + $result = unpack('Vlong', fread($this->fp, 3) . chr(0)); + return $result['long']; } - - + + private function packip($ip) { return pack('N', intval(ip2long($ip))); } - - + + private function getstring($data = "") { $char = fread($this->fp, 1); - + while (ord($char) > 0) { $data .= $char; - + $char = fread($this->fp, 1); } - + return $data; } - + private function getarea() { $byte = fread($this->fp, 1); - + switch (ord($byte)) { - + case 0: - + $area = ""; - + break; - + case 1: - + case 2: - + fseek($this->fp, $this->getlong3()); - + $area = $this->getstring(); - + break; - + default: - + $area = $this->getstring($byte); - + break; - + } - + return $area; } - - + + public function getlocation($ip) { if (!$this->fp) { return null; } - + $location['ip'] = gethostbyname($ip); - + $ip = $this->packip($location['ip']); - - - - - + + $l = 0; - + $u = $this->totalip; - + $findip = $this->lastip; - + while ($l <= $u) { $i = floor(($l + $u) / 2); - + fseek($this->fp, $this->firstip + $i * 7); - + $beginip = strrev(fread($this->fp, 4)); - + if ($ip < $beginip) { $u = $i - 1; } else { fseek($this->fp, $this->getlong3()); - + $endip = strrev(fread($this->fp, 4)); - + if ($ip > $endip) { $l = $i + 1; } else { $findip = $this->firstip + $i * 7; - + break; } } } - - - + + fseek($this->fp, $findip); - + $location['beginip'] = long2ip($this->getlong()); - + $offset = $this->getlong3(); - + fseek($this->fp, $offset); - + $location['endip'] = long2ip($this->getlong()); - + $byte = fread($this->fp, 1); - + switch (ord($byte)) { - + case 1: - + $countryOffset = $this->getlong3(); - + fseek($this->fp, $countryOffset); - + $byte = fread($this->fp, 1); - + switch (ord($byte)) { - + case 2: - + fseek($this->fp, $this->getlong3()); - + $location['country'] = $this->getstring(); - + fseek($this->fp, $countryOffset + 4); - + $location['area'] = $this->getarea(); - + break; - + default: - + $location['country'] = $this->getstring($byte); - + $location['area'] = $this->getarea(); - + break; - + } - + break; - + case 2: - + fseek($this->fp, $this->getlong3()); - + $location['country'] = $this->getstring(); - + fseek($this->fp, $offset + 8); - + $location['area'] = $this->getarea(); - + break; - + default: - + $location['country'] = $this->getstring($byte); - + $location['area'] = $this->getarea(); - + break; - + } - + if ($location['country'] == " CZ88.NET") { $location['country'] = "未知"; } - + if ($location['area'] == " CZ88.NET") { $location['area'] = ""; } - + return $location; } } diff --git a/app/Utils/QRcode.php b/app/Utils/QRcode.php index 3e33a6cb..cbdc430f 100644 --- a/app/Utils/QRcode.php +++ b/app/Utils/QRcode.php @@ -20,18 +20,18 @@ class QRcode return QRcode::zxing_decode($url); } } - + public static function online_decode($url) { $data = array(); $data['fileurl'] = $url; $param = http_build_query($data, '', '&'); - + $sock = new HTTPSocket; $sock->connect("api.qrserver.com", 80); $sock->set_method('GET'); $sock->query('/v1/read-qr-code/', $param); - + $raw_text = $sock->fetch_body(); $result_array = json_decode($raw_text, true); if (isset($result_array[0])) { @@ -39,48 +39,48 @@ class QRcode } return null; } - + public static function phpzbar_decode($url) { - $filepath = BASE_PATH."/storage/".time().rand(1, 100).".png"; + $filepath = BASE_PATH . "/storage/" . time() . rand(1, 100) . ".png"; $img = file_get_contents($url); file_put_contents($filepath, $img); - + /* Create new image object */ $image = new \ZBarCodeImage($filepath); - + /* Create a barcode scanner */ $scanner = new \ZBarCodeScanner(); - + /* Scan the image */ $barcode = $scanner->scan($image); - + unlink($filepath); - + return (isset($barcode[0]['data']) ? $barcode[0]['data'] : null); } - + public static function zxing_local_decode($url) { - $filepath = BASE_PATH."/storage/".time().rand(1, 100).".png"; + $filepath = BASE_PATH . "/storage/" . time() . rand(1, 100) . ".png"; $img = file_get_contents($url); file_put_contents($filepath, $img); - + $qrcode = new \QrReader($filepath); $text = $qrcode->text(); //return decoded text from QR Code - + unlink($filepath); - + if ($text == null || $text == "") { return null; } - + return $text; } - + public static function zxing_decode($url) { - $raw_text = file_get_contents("https://zxing.org/w/decode?u=".urlencode($url)); + $raw_text = file_get_contents("https://zxing.org/w/decode?u=" . urlencode($url)); return Tools::get_middle_text($raw_text, "Raw text
", "
Raw bytes
");
     }
 }
diff --git a/app/Utils/Radius.php b/app/Utils/Radius.php
index 3c9d9cb5..677d0bcd 100644
--- a/app/Utils/Radius.php
+++ b/app/Utils/Radius.php
@@ -17,33 +17,33 @@ class Radius
      */
     public static function Add($user, $pwd)
     {
-        if (Config::get('enable_radius')=='true') {
-            $email=$user->email;
-            $email=str_replace("@", "", $email);
-            $email=str_replace(".", "", $email);
+        if (Config::get('enable_radius') == 'true') {
+            $email = $user->email;
+            $email = str_replace("@", "", $email);
+            $email = str_replace(".", "", $email);
 
-            $exists=RadiusRadCheck::where("username", $email)->first();
+            $exists = RadiusRadCheck::where("username", $email)->first();
 
-            if ($exists==null) {
+            if ($exists == null) {
                 $rb = RadiusBan::where('userid', $user->id)->first();
                 if ($rb != null) {
                     return;
                 }
 
-                $newRad=new RadiusRadCheck();
-                $newRad->username=$email;
-                $newRad->attribute="Cleartext-Password";
-                $newRad->op=":=";
-                $newRad->value=$pwd;
+                $newRad = new RadiusRadCheck();
+                $newRad->username = $email;
+                $newRad->attribute = "Cleartext-Password";
+                $newRad->op = ":=";
+                $newRad->value = $pwd;
                 $newRad->save();
 
-                $newRad=new RadiusRadUserGroup();
-                $newRad->username=$email;
-                $newRad->groupname="user";
-                $newRad->priority="0";
+                $newRad = new RadiusRadUserGroup();
+                $newRad->username = $email;
+                $newRad->groupname = "user";
+                $newRad->priority = "0";
                 $newRad->save();
             } else {
-                $exists->value=$pwd;
+                $exists->value = $pwd;
                 $exists->save();
             }
         }
@@ -52,14 +52,14 @@ class Radius
 
     public static function Delete($email)
     {
-        if (Config::get('enable_radius')=='true') {
-            $email=str_replace("@", "", $email);
-            $email=str_replace(".", "", $email);
+        if (Config::get('enable_radius') == 'true') {
+            $email = str_replace("@", "", $email);
+            $email = str_replace(".", "", $email);
 
 
-            $exists=RadiusRadCheck::where("username", $email)->first();
+            $exists = RadiusRadCheck::where("username", $email)->first();
 
-            if ($exists!=null) {
+            if ($exists != null) {
                 RadiusRadCheck::where("username", $email)->delete();
                 RadiusRadUserGroup::where("username", $email)->delete();
             }
@@ -68,21 +68,21 @@ class Radius
 
     public static function ChangeUserName($origin_email, $new_email, $passwd)
     {
-        if (Config::get('enable_radius')=='true') {
-            $email1=str_replace("@", "", $origin_email);
-            $email1=str_replace(".", "", $email1);
-            $email2=str_replace("@", "", $new_email);
-            $email2=str_replace(".", "", $email2);
+        if (Config::get('enable_radius') == 'true') {
+            $email1 = str_replace("@", "", $origin_email);
+            $email1 = str_replace(".", "", $email1);
+            $email2 = str_replace("@", "", $new_email);
+            $email2 = str_replace(".", "", $email2);
 
-            $exists=RadiusRadCheck::where("username", $email1)->first();
+            $exists = RadiusRadCheck::where("username", $email1)->first();
 
-            if ($exists!=null) {
-                $exists->username=$email2;
-                $exists->value=$passwd;
+            if ($exists != null) {
+                $exists->username = $email2;
+                $exists->value = $passwd;
                 $exists->save();
 
-                $exists=RadiusRadUserGroup::where("username", $email1)->first();
-                $exists->username=$email2;
+                $exists = RadiusRadUserGroup::where("username", $email1)->first();
+                $exists->username = $email2;
                 $exists->save();
             } else {
                 $user = User::where('email', '=', $origin_email)->first();
@@ -91,17 +91,17 @@ class Radius
                     return;
                 }
 
-                $newRad=new RadiusRadCheck();
-                $newRad->username=$email2;
-                $newRad->attribute="Cleartext-Password";
-                $newRad->op=":=";
-                $newRad->value=$passwd;
+                $newRad = new RadiusRadCheck();
+                $newRad->username = $email2;
+                $newRad->attribute = "Cleartext-Password";
+                $newRad->op = ":=";
+                $newRad->value = $passwd;
                 $newRad->save();
 
-                $newRad=new RadiusRadUserGroup();
-                $newRad->username=$email2;
-                $newRad->groupname="user";
-                $newRad->priority="0";
+                $newRad = new RadiusRadUserGroup();
+                $newRad->username = $email2;
+                $newRad->groupname = "user";
+                $newRad->priority = "0";
                 $newRad->save();
             }
         }
@@ -109,15 +109,15 @@ class Radius
 
     public static function AddNas($ip, $name)
     {
-        if (Config::get('enable_radius')=='true') {
-            $exists=RadiusNas::where("shortname", $ip)->first();
-            if ($exists==null) {
-                $exists=new RadiusNas();
-                $exists->nasname=$ip;
-                $exists->shortname=$ip;
-                $exists->type="other";
-                $exists->secret=Config::get('radius_secret');
-                $exists->description=$ip;
+        if (Config::get('enable_radius') == 'true') {
+            $exists = RadiusNas::where("shortname", $ip)->first();
+            if ($exists == null) {
+                $exists = new RadiusNas();
+                $exists->nasname = $ip;
+                $exists->shortname = $ip;
+                $exists->type = "other";
+                $exists->secret = Config::get('radius_secret');
+                $exists->description = $ip;
                 $exists->save();
             }
         }
@@ -125,15 +125,15 @@ class Radius
 
     public static function DelNas($ip)
     {
-        if (Config::get('enable_radius')=='true') {
+        if (Config::get('enable_radius') == 'true') {
             RadiusNas::where("shortname", $ip)->delete();
         }
     }
 
     public static function GetUserName($email)
     {
-        $emailt=str_replace("@", "", $email);
-        $emailt=str_replace(".", "", $emailt);
+        $emailt = str_replace("@", "", $email);
+        $emailt = str_replace(".", "", $emailt);
         return $emailt;
     }
 }
diff --git a/app/Utils/Telegram.php b/app/Utils/Telegram.php
index be62c64c..2bf83315 100644
--- a/app/Utils/Telegram.php
+++ b/app/Utils/Telegram.php
@@ -8,28 +8,28 @@ class Telegram
 {
 
     /**
-     * ·¢ËÍÏûϢ
+     * ������Ϣ
      */
     public static function Send($messageText)
     {
         if (Config::get('enable_telegram') == 'true') {
             $bot = new \TelegramBot\Api\BotApi(Config::get('telegram_token'));
-			try{
-				$bot->sendMessage(Config::get('telegram_chatid'), $messageText);
-			} catch (\Exception $e) {
+            try {
+                $bot->sendMessage(Config::get('telegram_chatid'), $messageText);
+            } catch (\Exception $e) {
                 echo $e->getMessage();
             }
         }
     }
-    
-    
+
+
     public static function SendMarkdown($messageText)
     {
         if (Config::get('enable_telegram') == 'true') {
             $bot = new \TelegramBot\Api\BotApi(Config::get('telegram_token'));
-			try{
-				$bot->sendMessage(Config::get('telegram_chatid'), $messageText, "Markdown");
-			} catch (\Exception $e) {
+            try {
+                $bot->sendMessage(Config::get('telegram_chatid'), $messageText, "Markdown");
+            } catch (\Exception $e) {
                 echo $e->getMessage();
             }
         }
diff --git a/app/Utils/TelegramProcess.php b/app/Utils/TelegramProcess.php
index 402c6a61..5f771535 100644
--- a/app/Utils/TelegramProcess.php
+++ b/app/Utils/TelegramProcess.php
@@ -9,103 +9,104 @@ use App\Controllers\LinkController;
 class TelegramProcess
 {
     private static $all_rss = [
-        "clean_link"=>"重置订阅",
-        "?mu=0" => "SSR普通订阅" ,
+        "clean_link" => "重置订阅",
+        "?mu=0" => "SSR普通订阅",
         "?mu=1" => "SSR单端口订阅",
-        "?mu=3"=> "SS/SSD订阅",
+        "?mu=3" => "SS/SSD订阅",
         "?mu=2" => "V2ray订阅",
-        "?mu=4"=> "Clash订阅"];
+        "?mu=4" => "Clash订阅"];
 
-    private static function callback_bind_method($bot,$message,$command)
-	{
+    private static function callback_bind_method($bot, $message, $command)
+    {
         $reply_to = $message->getMessageId();
         $user = User::where('telegram_id', $message->getFrom()->getId())->first();
-		$reply_message="???";
+        $reply_message = "???";
         if ($user != null) {
-            switch (true){
-                case (strpos($command,"mu")):
+            switch (true) {
+                case (strpos($command, "mu")):
                     $ssr_sub_token = LinkController::GenerateSSRSubCode($user->id, 0);
                     $subUrl = Config::get('subUrl');
-                    $reply_message = self::$all_rss[$command].": ".$subUrl.$ssr_sub_token.$command.PHP_EOL;
+                    $reply_message = self::$all_rss[$command] . ": " . $subUrl . $ssr_sub_token . $command . PHP_EOL;
                     break;
-                case ($command=="clean_link"):
+                case ($command == "clean_link"):
                     $user->clean_link();
-					$reply_message="链接重置成功";
+                    $reply_message = "链接重置成功";
                     break;
             }
             $bot->sendMessage($message->getChat()->getId(), $reply_message, $parseMode = null, $disablePreview = false, $replyToMessageId = $reply_to);
         }
-}
-    private static function needbind_method($bot, $message, $command, $user, $reply_to=null)
+    }
+
+    private static function needbind_method($bot, $message, $command, $user, $reply_to = null)
     {
-		$reply = [
-			"message" => "???",
-			"markup" => null,
-		];
+        $reply = [
+            "message" => "???",
+            "markup" => null,
+        ];
         if ($user != null) {
             switch ($command) {
                 case 'traffic':
-                    $reply['message']="您当前的流量状况:
+                    $reply['message'] = "您当前的流量状况:
 今日已使用 " . $user->TodayusedTraffic() . " " . number_format(($user->u + $user->d - $user->last_day_t) / $user->transfer_enable * 100, 2) . "%
 今日之前已使用 " . $user->LastusedTraffic() . " " . number_format($user->last_day_t / $user->transfer_enable * 100, 2) . "%
 未使用 " . $user->unusedTraffic() . " " . number_format(($user->transfer_enable - ($user->u + $user->d)) / $user->transfer_enable * 100, 2) . "%";
                     break;
                 case 'checkin':
                     if (!$user->isAbleToCheckin()) {
-                        $reply['message']= "您今天已经签过到了!";
+                        $reply['message'] = "您今天已经签过到了!";
                         break;
                     }
                     $traffic = rand(Config::get('checkinMin'), Config::get('checkinMax'));
                     $user->transfer_enable = $user->transfer_enable + Tools::toMB($traffic);
                     $user->last_check_in_time = time();
                     $user->save();
-                   $reply['message']= "签到成功!获得了 " . $traffic . " MB 流量!";
+                    $reply['message'] = "签到成功!获得了 " . $traffic . " MB 流量!";
                     break;
                 case 'prpr':
                     $prpr = array('⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄', '(≧ ﹏ ≦)', '(*/ω\*)', 'ヽ(*。>Д<)o゜', '(つ ﹏ ⊂)', '( >  < )');
-                    $reply['message']= $prpr[mt_rand(0, 5)];
+                    $reply['message'] = $prpr[mt_rand(0, 5)];
                     break;
                 case "rss":
                     $reply['message'] = "点击以下按钮获取对应订阅: ";
                     $keys = [];
-                    foreach (self::$all_rss as $key => $value){
+                    foreach (self::$all_rss as $key => $value) {
                         $keys[] = [["text" => $value, "callback_data" => $key]];
                     }
-                   $reply['mark'] = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
+                    $reply['mark'] = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
                         $keys
                     );
                     break;
 
             }
         } else {
-             $reply['message'] = "您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号";
+            $reply['message'] = "您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号";
         }
 
-		return $reply;
+        return $reply;
     }
 
 
     public static function telegram_process($bot, $message, $command)
     {
         $user = User::where('telegram_id', $message->getFrom()->getId())->first();
-		$reply_to = $message->getMessageId();
-		$reply = [
-			"message" => "???",
-			"markup" => null,
-		];
+        $reply_to = $message->getMessageId();
+        $reply = [
+            "message" => "???",
+            "markup" => null,
+        ];
         if ($message->getChat()->getId() > 0) {
             //个人
             $bot->sendChatAction($message->getChat()->getId(), 'typing');
 
             switch ($command) {
                 case 'ping':
-                    $reply['message']= 'Pong!您的 ID 是 ' . $message->getChat()->getId() . '!';
+                    $reply['message'] = 'Pong!您的 ID 是 ' . $message->getChat()->getId() . '!';
                     break;
                 case 'traffic':
                 case 'checkin':
                 case 'prpr':
                 case "rss":
-                    $reply=TelegramProcess::needbind_method($bot, $message, $command, $user, $reply_to);
+                    $reply = TelegramProcess::needbind_method($bot, $message, $command, $user, $reply_to);
                     break;
                 case 'help':
                     $reply['message'] = "命令列表:
@@ -114,50 +115,50 @@ class TelegramProcess
 						/checkin 签到
 						/help 获取帮助信息
 						/rss 获取节点订阅";
-					if($user==null){
-						$help_list.=PHP_EOL."您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号";
-					}
+                    if ($user == null) {
+                        $help_list .= PHP_EOL . "您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号";
+                    }
                     break;
                 default:
-					if ($message->getPhoto()==null){
-						if (is_numeric($message->getText()) || strlen($message->getText()) != 6) {
-							$reply['message']= Tuling::chat($message->getFrom()->getId(), $message->getText());
+                    if ($message->getPhoto() == null) {
+                        if (is_numeric($message->getText()) || strlen($message->getText()) != 6) {
+                            $reply['message'] = Tuling::chat($message->getFrom()->getId(), $message->getText());
+                            break;
+                        }
+
+                        if ($user == null) {
+                            $reply['message'] = "登录验证失败,您未绑定本站账号";
                             break;
                         }
-						
-						if($user==null){
-							$reply['message']= "登录验证失败,您未绑定本站账号";
-							break;
-						}
 
                         $uid = TelegramSessionManager::verify_login_number($message->getText(), $user->id);
                         if ($uid != 0) {
-                            $reply['message']= "登录验证成功,邮箱:" . $user->email;
+                            $reply['message'] = "登录验证成功,邮箱:" . $user->email;
                         } else {
-                            $reply['message']= "登录验证失败,数字无效";
+                            $reply['message'] = "登录验证失败,数字无效";
                         }
-						break;
-					}
+                        break;
+                    }
 
                     $bot->sendMessage($message->getChat()->getId(), "正在解码,请稍候。。。");
-					$bot->sendChatAction($message->getChat()->getId(), 'typing');
+                    $bot->sendChatAction($message->getChat()->getId(), 'typing');
                     $photos = $message->getPhoto();
 
                     $photo_size_array = array();
                     $photo_id_array = array();
                     $photo_id_list_array = array();
-					
+
                     foreach ($photos as $photo) {
                         $file = $bot->getFile($photo->getFileId());
                         $real_id = substr($file->getFileId(), 0, 36);
                         if (!isset($photo_size_array[$real_id])) {
                             $photo_size_array[$real_id] = 0;
                         }
-						
+
                         if ($photo_size_array[$real_id] >= $file->getFileSize()) {
-							continue;
+                            continue;
                         }
-						
+
                         $photo_size_array[$real_id] = $file->getFileSize();
                         $photo_id_array[$real_id] = $file->getFileId();
                         if (!isset($photo_id_list_array[$real_id])) {
@@ -184,31 +185,31 @@ class TelegramProcess
                         if (substr($qrcode_text, 0, 11) == 'mod://bind/' && strlen($qrcode_text) == 27) {
                             $uid = TelegramSessionManager::verify_bind_session(substr($qrcode_text, 11));
                             if ($uid == 0) {
-								$reply['message']= "绑定失败,二维码无效:" . substr($qrcode_text, 11)."二维码的有效期为10分钟,请尝试刷新网站的“资料编辑”页面以更新二维码";
-								continue;
-                            }							
+                                $reply['message'] = "绑定失败,二维码无效:" . substr($qrcode_text, 11) . "二维码的有效期为10分钟,请尝试刷新网站的“资料编辑”页面以更新二维码";
+                                continue;
+                            }
                             $user = User::where('id', $uid)->first();
                             $user->telegram_id = $message->getFrom()->getId();
                             $user->im_type = 4;
                             $user->im_value = $message->getFrom()->getUsername();
                             $user->save();
-                            $reply['message']= "绑定成功,邮箱:" . $user->email;
-							break;
+                            $reply['message'] = "绑定成功,邮箱:" . $user->email;
+                            break;
                         }
 
                         if (substr($qrcode_text, 0, 12) == 'mod://login/' && strlen($qrcode_text) == 28) {
                             if ($user == null) {
-								$reply['message']= "登录验证失败,您未绑定本站账号" . substr($qrcode_text, 12);
-								break;
+                                $reply['message'] = "登录验证失败,您未绑定本站账号" . substr($qrcode_text, 12);
+                                break;
                             }
-							
+
                             $uid = TelegramSessionManager::verify_login_session(substr($qrcode_text, 12), $user->id);
                             if ($uid != 0) {
-                                $reply['message']= "登录验证成功,邮箱:" . $user->email;
+                                $reply['message'] = "登录验证成功,邮箱:" . $user->email;
                             } else {
-                                $reply['message']= "登录验证失败,二维码无效" . substr($qrcode_text, 12);
+                                $reply['message'] = "登录验证失败,二维码无效" . substr($qrcode_text, 12);
                             }
-							break;
+                            break;
                         }
 
                         break;
@@ -223,12 +224,12 @@ class TelegramProcess
 
             switch ($command) {
                 case 'ping':
-                    $reply['message']= 'Pong!这个群组的 ID 是 ' . $message->getChat()->getId() . '!';
+                    $reply['message'] = 'Pong!这个群组的 ID 是 ' . $message->getChat()->getId() . '!';
                     break;
                 case 'traffic':
                 case 'checkin':
                 case 'prpr':
-                    $reply=TelegramProcess::needbind_method($bot, $message, $command, $user, $reply_to);
+                    $reply = TelegramProcess::needbind_method($bot, $message, $command, $user, $reply_to);
                     break;
                 case 'help':
                     $reply['message'] = "命令列表:
@@ -237,28 +238,27 @@ class TelegramProcess
 						/checkin 签到
 						/help 获取帮助信息
 						/rss 获取节点订阅	";
-					if($user==null){
-						$reply['message'].=PHP_EOL."您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号";
-					}
+                    if ($user == null) {
+                        $reply['message'] .= PHP_EOL . "您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号";
+                    }
                     break;
                 default:
                     if ($message->getText() != null) {
                         if ($message->getChat()->getId() == Config::get('telegram_chatid')) {
-                            $reply['message']= Tuling::chat($message->getFrom()->getId(), $message->getText());
+                            $reply['message'] = Tuling::chat($message->getFrom()->getId(), $message->getText());
                         } else {
-                            $reply['message']='不约,叔叔我们不约';
+                            $reply['message'] = '不约,叔叔我们不约';
                         }
                     }
                     if ($message->getNewChatMember() != null && Config::get('enable_welcome_message') == 'true') {
-                        $reply['message']="欢迎 " . $message->getNewChatMember()->getFirstName() . " " . $message->getNewChatMember()->getLastName();
+                        $reply['message'] = "欢迎 " . $message->getNewChatMember()->getFirstName() . " " . $message->getNewChatMember()->getLastName();
+                    } else {
+                        $reply['message'] = null;
                     }
-					else{
-						$reply['message']=null;
-					}
             }
         }
 
-		$bot->sendMessage($message->getChat()->getId(), $reply['message'] , $parseMode = null, $disablePreview = false, $replyToMessageId = $reply_to, $replyMarkup=$reply['mark']);
+        $bot->sendMessage($message->getChat()->getId(), $reply['message'], $parseMode = null, $disablePreview = false, $replyToMessageId = $reply_to, $replyMarkup = $reply['mark']);
         $bot->sendChatAction($message->getChat()->getId(), '');
     }
 
@@ -281,15 +281,17 @@ class TelegramProcess
             }), function () {
                 return true;
             });
-            $bot->on(function($update) use ($bot){
+            $bot->on(function ($update) use ($bot) {
                 $callback = $update->getCallbackQuery();
                 //Answer to Telegram, you make answer in the end, or in the beginning.
-                $message =  $callback->getMessage();
+                $message = $callback->getMessage();
                 $message->setFrom($callback->getFrom());
-                TelegramProcess::callback_bind_method($bot,$message,$callback->getData());
-            }, function($update){
+                TelegramProcess::callback_bind_method($bot, $message, $callback->getData());
+            }, function ($update) {
                 $callback = $update->getCallbackQuery();
-                if (is_null($callback) || !strlen($callback->getData())){return false; }
+                if (is_null($callback) || !strlen($callback->getData())) {
+                    return false;
+                }
                 return true;
             });
 
diff --git a/app/Utils/TelegramSessionManager.php b/app/Utils/TelegramSessionManager.php
index 391626a1..48714362 100644
--- a/app/Utils/TelegramSessionManager.php
+++ b/app/Utils/TelegramSessionManager.php
@@ -10,7 +10,7 @@ class TelegramSessionManager
 {
     public static function GenerateRandomLink()
     {
-        $i =0;
+        $i = 0;
         for ($i = 0; $i < 10; $i++) {
             $token = Tools::genRandomChar(16);
             $Elink = TelegramSession::where("session_content", "=", $token)->first();
@@ -18,25 +18,25 @@ class TelegramSessionManager
                 return $token;
             }
         }
-        
+
         return "couldn't alloc token";
     }
-    
+
     public static function GenerateLoginRandomLink()
     {
-        $i =0;
+        $i = 0;
         for ($i = 0; $i < 10; $i++) {
             $token = Tools::genRandomChar(16);
             $number = rand(100000, 999999);
-            $Elink = TelegramSession::where("session_content", "LIKE", $token."|%")->orWhere("session_content", "LIKE", "%|".$number)->first();
+            $Elink = TelegramSession::where("session_content", "LIKE", $token . "|%")->orWhere("session_content", "LIKE", "%|" . $number)->first();
             if ($Elink == null) {
-                return $token."|".$number;
+                return $token . "|" . $number;
             }
         }
-        
+
         return "couldn't alloc token";
     }
-    
+
     public static function add_bind_session($user)
     {
         $Elink = TelegramSession::where("type", "=", 0)->where("user_id", "=", $user->id)->first();
@@ -46,17 +46,17 @@ class TelegramSessionManager
             $Elink->save();
             return $Elink->session_content;
         }
-        
+
         $NLink = new TelegramSession();
         $NLink->type = 0;
         $NLink->user_id = $user->id;
         $NLink->datetime = time();
         $NLink->session_content = TelegramSessionManager::GenerateRandomLink();
         $NLink->save();
-        
+
         return $NLink->session_content;
     }
-    
+
     public static function verify_bind_session($token)
     {
         $Elink = TelegramSession::where("type", "=", 0)->where('session_content', $token)->where('datetime', '>', time() - 600)->orderBy('datetime', 'desc')->first();
@@ -67,7 +67,7 @@ class TelegramSessionManager
         }
         return 0;
     }
-    
+
     public static function add_login_session()
     {
         $NLink = new TelegramSession();
@@ -76,13 +76,13 @@ class TelegramSessionManager
         $NLink->datetime = time();
         $NLink->session_content = TelegramSessionManager::GenerateLoginRandomLink();
         $NLink->save();
-        
+
         return $NLink->session_content;
     }
-    
+
     public static function verify_login_session($token, $uid)
     {
-        $Elink = TelegramSession::where("type", "=", 1)->where('user_id', 0)->where('session_content', "LIKE", $token."|%")->where('datetime', '>', time() - 90)->orderBy('datetime', 'desc')->first();
+        $Elink = TelegramSession::where("type", "=", 1)->where('user_id', 0)->where('session_content', "LIKE", $token . "|%")->where('datetime', '>', time() - 90)->orderBy('datetime', 'desc')->first();
         if ($Elink != null) {
             $Elink->user_id = $uid;
             $Elink->save();
@@ -90,10 +90,10 @@ class TelegramSessionManager
         }
         return 0;
     }
-    
+
     public static function verify_login_number($token, $uid)
     {
-        $Elink = TelegramSession::where("type", "=", 1)->where('user_id', 0)->where('session_content', "LIKE", "%|".$token)->where('datetime', '>', time() - 90)->orderBy('datetime', 'desc')->first();
+        $Elink = TelegramSession::where("type", "=", 1)->where('user_id', 0)->where('session_content', "LIKE", "%|" . $token)->where('datetime', '>', time() - 90)->orderBy('datetime', 'desc')->first();
         if ($Elink != null) {
             $Elink->user_id = $uid;
             $Elink->save();
@@ -101,10 +101,10 @@ class TelegramSessionManager
         }
         return 0;
     }
-    
+
     public static function step2_verify_login_session($token, $number)
     {
-        $Elink = TelegramSession::where("type", "=", 1)->where('session_content', $token."|".$number)->where('datetime', '>', time() - 90)->orderBy('datetime', 'desc')->first();
+        $Elink = TelegramSession::where("type", "=", 1)->where('session_content', $token . "|" . $number)->where('datetime', '>', time() - 90)->orderBy('datetime', 'desc')->first();
         if ($Elink != null) {
             $uid = $Elink->user_id;
             $Elink->delete();
@@ -112,10 +112,10 @@ class TelegramSessionManager
         }
         return 0;
     }
-    
+
     public static function check_login_session($token, $number)
     {
-        $Elink = TelegramSession::where("type", "=", 1)->where('session_content', $token."|".$number)->orderBy('datetime', 'desc')->first();
+        $Elink = TelegramSession::where("type", "=", 1)->where('session_content', $token . "|" . $number)->orderBy('datetime', 'desc')->first();
         if ($Elink != null) {
             if ($Elink->datetime < time() - 90) {
                 return -1;
diff --git a/app/Utils/Tools.php b/app/Utils/Tools.php
index a28af155..a14c9d41 100644
--- a/app/Utils/Tools.php
+++ b/app/Utils/Tools.php
@@ -32,18 +32,18 @@ class Tools
         } elseif (abs($value) > $kb) {
             return round($value / $kb, 2) . "KB";
         } else {
-            return round($value, 2)."B";
+            return round($value, 2) . "B";
         }
     }
 
-	//虽然名字是toMB,但是实际上功能是from MB to B
+    //虽然名字是toMB,但是实际上功能是from MB to B
     public static function toMB($traffic)
     {
         $mb = 1048576;
         return $traffic * $mb;
     }
 
-	//虽然名字是toGB,但是实际上功能是from GB to B
+    //虽然名字是toGB,但是实际上功能是from GB to B
     public static function toGB($traffic)
     {
         $gb = 1048576 * 1024;
@@ -72,18 +72,18 @@ class Tools
     }
 
     //获取随机字符串
-		
-		public static function genRandomNum($length = 8)
-		{
-				// 来自Miku的 6位随机数 注册验证码 生成方案
-				$chars = '0123456789';
-				$char = '';
-				for ($i = 0; $i < $length; $i++) {
-						$char .= $chars[mt_rand(0, strlen($chars) - 1)];
-				}
-				return $char;
-		}
-		
+
+    public static function genRandomNum($length = 8)
+    {
+        // 来自Miku的 6位随机数 注册验证码 生成方案
+        $chars = '0123456789';
+        $char = '';
+        for ($i = 0; $i < $length; $i++) {
+            $char .= $chars[mt_rand(0, strlen($chars) - 1)];
+        }
+        return $char;
+    }
+
     public static function genRandomChar($length = 8)
     {
         // 密码字符集,可任意添加你需要的字符
@@ -128,7 +128,7 @@ class Tools
     public static function genUUID()
     {
         // @TODO
-      return self::genSID();
+        return self::genSID();
     }
 
     public static function getLastPort()
@@ -161,12 +161,12 @@ class Tools
 
     public static function getDir($dir)
     {
-        $dirArray[]=null;
+        $dirArray[] = null;
         if (false != ($handle = opendir($dir))) {
-            $i=0;
+            $i = 0;
             while (false !== ($file = readdir($handle))) {
-                if ($file != "." && $file != ".."&&!strpos($file, ".")) {
-                    $dirArray[$i]=$file;
+                if ($file != "." && $file != ".." && !strpos($file, ".")) {
+                    $dirArray[$i] = $file;
                     $i++;
                 }
             }
@@ -293,8 +293,8 @@ class Tools
                     return $rule->id;
                 }
 
-        //递归处理这个节点
-        $maybe_rule_id = Tools::has_conflict_rule($rule, $ruleset, $edit_rule_id, $origin_node_id, $rule->user_id);
+                //递归处理这个节点
+                $maybe_rule_id = Tools::has_conflict_rule($rule, $ruleset, $edit_rule_id, $origin_node_id, $rule->user_id);
                 if ($maybe_rule_id != 0) {
                     return $maybe_rule_id;
                 }
@@ -303,7 +303,7 @@ class Tools
 
         if (($input_rule->id == $edit_rule_id || $edit_rule_id == 0) && $input_rule->dist_node_id != -1) {
             $dist_node = Node::find($input_rule->dist_node_id);
-            if ($input_rule->source_node_id == 0 && ($dist_node->sort == 10 ||$dist_node->sort == 12)) {
+            if ($input_rule->source_node_id == 0 && ($dist_node->sort == 10 || $dist_node->sort == 12)) {
                 return -1;
             }
 
@@ -333,10 +333,10 @@ class Tools
                 if ($single_rule->dist_node_id == $path->begin_node->id) {
                     $path->begin_node = $single_rule->Source_Node();
                     if ($path->begin_node->isNodeAccessable() == false) {
-                        $path->path = ''.$single_rule->Source_Node()->name.''." → ".$path->path;
+                        $path->path = '' . $single_rule->Source_Node()->name . '' . " → " . $path->path;
                         $path->status = "阻断";
                     } else {
-                        $path->path = $single_rule->Source_Node()->name." → ".$path->path;
+                        $path->path = $single_rule->Source_Node()->name . " → " . $path->path;
                         $path->status = "通畅";
                     }
                     return $pathset;
@@ -345,10 +345,10 @@ class Tools
                 if ($path->end_node->id == $single_rule->source_node_id) {
                     $path->end_node = $single_rule->Dist_Node();
                     if ($path->end_node->isNodeAccessable() == false) {
-                        $path->path = $path->path." → ".''.$single_rule->Dist_Node()->name.'';
+                        $path->path = $path->path . " → " . '' . $single_rule->Dist_Node()->name . '';
                         $path->status = "阻断";
                     } else {
-                        $path->path = $path->path." → ".$single_rule->Dist_Node()->name;
+                        $path->path = $path->path . " → " . $single_rule->Dist_Node()->name;
                     }
                     return $pathset;
                 }
@@ -358,7 +358,7 @@ class Tools
         $new_path = new \stdClass();
         $new_path->begin_node = $single_rule->Source_Node();
         if ($new_path->begin_node->isNodeAccessable() == false) {
-            $new_path->path = ''.$single_rule->Source_Node()->name.'';
+            $new_path->path = '' . $single_rule->Source_Node()->name . '';
             $new_path->status = "阻断";
         } else {
             $new_path->path = $single_rule->Source_Node()->name;
@@ -367,10 +367,10 @@ class Tools
 
         $new_path->end_node = $single_rule->Dist_Node();
         if ($new_path->end_node->isNodeAccessable() == false) {
-            $new_path->path .= " -> ".''.$single_rule->Dist_Node()->name.'';
+            $new_path->path .= " -> " . '' . $single_rule->Dist_Node()->name . '';
             $new_path->status = "阻断";
         } else {
-            $new_path->path .= " -> ".$single_rule->Dist_Node()->name;
+            $new_path->path .= " -> " . $single_rule->Dist_Node()->name;
         }
 
         $new_path->port = $port;
@@ -425,9 +425,8 @@ class Tools
 
     public static function checkNoneProtocol($user)
     {
-        if($user->method == 'none' && !in_array($user->protocol, Config::getSupportParam('allow_none_protocol')))
-        {
-          return false;
+        if ($user->method == 'none' && !in_array($user->protocol, Config::getSupportParam('allow_none_protocol'))) {
+            return false;
         }
 
         return true;
@@ -438,22 +437,22 @@ class Tools
         return str_replace("::ffff:", "", $rawIp);
     }
 
-	public static function isInt($str)
-	{
-		if($str[0]=='-'){
-			$str=substr($str,1);
-		}
+    public static function isInt($str)
+    {
+        if ($str[0] == '-') {
+            $str = substr($str, 1);
+        }
 
-		return ctype_digit($str);
+        return ctype_digit($str);
     }
-    
+
     public static function v2Array($node)
     {
         $server = explode(';', $node);
         $item = [
-            'host'=>'',
-            'path'=>'',
-            'tls'=>''
+            'host' => '',
+            'path' => '',
+            'tls' => ''
         ];
         $item['add'] = $server[0];
         if ($server[1] == "0" or $server[1] == "") {
@@ -507,10 +506,10 @@ class Tools
     {
         $server = explode(';', $node);
         $item = [
-            'host'=>'',
-            'path'=>'',
-            'net'=>'ws',
-            'tls'=>''
+            'host' => '',
+            'path' => '',
+            'net' => 'ws',
+            'tls' => ''
         ];
         $item['add'] = $server[0];
         if ($server[1] == "0" or $server[1] == "") {
@@ -528,7 +527,7 @@ class Tools
         }
         if (count($server) >= 5 && $server[4] == 'ws') {
             $item['net'] = 'ws';
-        }elseif (count($server) >= 5 && $server[4] == 'tls'){
+        } elseif (count($server) >= 5 && $server[4] == 'tls') {
             $item['tls'] = 'tls';
         }
         if (count($server) >= 6) {
diff --git a/app/Utils/Tuling.php b/app/Utils/Tuling.php
index b61db44c..322d450d 100644
--- a/app/Utils/Tuling.php
+++ b/app/Utils/Tuling.php
@@ -14,16 +14,16 @@ class Tuling
             $data['key'] = Config::get('tuling_apikey');
             $data['userid'] = $user;
             $data['info'] = $text;
-            
+
             $param = json_encode($data);
-            
-            
+
+
             $sock = new HTTPSocket;
             $sock->connect("www.tuling123.com", 80);
             $sock->set_method('POST');
             $sock->add_header('Content-Type', 'application/json');
             $sock->query('/openapi/api', $param);
-            
+
             $result = $sock->fetch_body();
             $result_array = json_decode($result, true);
             return $result_array['text'];
diff --git a/app/Utils/URL.php b/app/Utils/URL.php
index d2df2e88..86f26d4e 100644
--- a/app/Utils/URL.php
+++ b/app/Utils/URL.php
@@ -1,5 +1,7 @@
  xxx, xxx => xxx)
         $args_explode = explode('|', $origin);
 
@@ -79,43 +87,46 @@ class URL
         return $return_array;
     }
 
-    public static function SSCanConnect($user, $mu_port = 0) {
-        if($mu_port != 0) {
+    public static function SSCanConnect($user, $mu_port = 0)
+    {
+        if ($mu_port != 0) {
             $mu_user = User::where('port', '=', $mu_port)->where("is_multi_user", "<>", 0)->first();
             if ($mu_user == null) {
                 return;
             }
             return URL::SSCanConnect($mu_user);
         }
-        if(URL::CanMethodConnect($user->method) >= 2 && URL::CanProtocolConnect($user->protocol) >= 2 && URL::CanObfsConnect($user->obfs) >= 2) {
+        if (URL::CanMethodConnect($user->method) >= 2 && URL::CanProtocolConnect($user->protocol) >= 2 && URL::CanObfsConnect($user->obfs) >= 2) {
             return true;
-        }else{
+        } else {
             return false;
         }
     }
 
-    public static function SSRCanConnect($user, $mu_port = 0) {
-        if($mu_port != 0) {
+    public static function SSRCanConnect($user, $mu_port = 0)
+    {
+        if ($mu_port != 0) {
             $mu_user = User::where('port', '=', $mu_port)->where("is_multi_user", "<>", 0)->first();
             if ($mu_user == null) {
                 return;
             }
             return URL::SSRCanConnect($mu_user);
         }
-        if(URL::CanMethodConnect($user->method) != 2 && URL::CanProtocolConnect($user->protocol) != 2 && URL::CanObfsConnect($user->obfs) != 2) {
+        if (URL::CanMethodConnect($user->method) != 2 && URL::CanProtocolConnect($user->protocol) != 2 && URL::CanObfsConnect($user->obfs) != 2) {
             return true;
-        }else{
+        } else {
             return false;
         }
     }
 
-    public static function getSSConnectInfo($user) {
+    public static function getSSConnectInfo($user)
+    {
         $new_user = clone $user;
-        if(URL::CanObfsConnect($new_user->obfs) == 5) {
+        if (URL::CanObfsConnect($new_user->obfs) == 5) {
             $new_user->obfs = 'plain';
             $new_user->obfs_param = '';
         }
-        if(URL::CanProtocolConnect($new_user->protocol) == 3) {
+        if (URL::CanProtocolConnect($new_user->protocol) == 3) {
             $new_user->protocol = 'origin';
             $new_user->protocol_param = '';
         }
@@ -124,9 +135,10 @@ class URL
         return $new_user;
     }
 
-    public static function getSSRConnectInfo($user) {
+    public static function getSSRConnectInfo($user)
+    {
         $new_user = clone $user;
-        if(URL::CanObfsConnect($new_user->obfs) == 4) {
+        if (URL::CanObfsConnect($new_user->obfs) == 4) {
             $new_user->obfs = 'plain';
             $new_user->obfs_param = '';
         }
@@ -135,10 +147,11 @@ class URL
         return $new_user;
     }
 
-    public static function getAllItems($user, $is_mu = 0, $is_ss = 0) {
+    public static function getAllItems($user, $is_mu = 0, $is_ss = 0)
+    {
         $return_array = array();
         if ($user->is_admin) {
-            $nodes=Node::where(
+            $nodes = Node::where(
                 function ($query) {
                     $query->where('sort', 0)
                         ->orwhere('sort', 10)
@@ -146,35 +159,35 @@ class URL
                 }
             )->where("type", "1")->orderBy("name")->get();
         } else {
-            $nodes=Node::where(
+            $nodes = Node::where(
                 function ($query) {
                     $query->where('sort', 0)
                         ->orwhere('sort', 10)
                         ->orwhere('sort', 13);
                 }
             )->where(
-                function ($query) use ($user){
+                function ($query) use ($user) {
                     $query->where("node_group", "=", $user->node_group)
                         ->orWhere("node_group", "=", 0);
                 }
             )->where("type", "1")->where("node_class", "<=", $user->class)->orderBy("name")->get();
         }
-        if($is_mu) {
+        if ($is_mu) {
             if ($user->is_admin) {
-            	if ($is_mu!=1){
-            		$mu_nodes = Node::where('sort', 9)->where('server', '=', $is_mu)->where("type", "1")->get();
-            	}else{
-                	$mu_nodes = Node::where('sort', 9)->where("type", "1")->get();
-            	}
+                if ($is_mu != 1) {
+                    $mu_nodes = Node::where('sort', 9)->where('server', '=', $is_mu)->where("type", "1")->get();
+                } else {
+                    $mu_nodes = Node::where('sort', 9)->where("type", "1")->get();
+                }
             } else {
-                if ($is_mu!=1){
+                if ($is_mu != 1) {
                     $mu_nodes = Node::where('sort', 9)->where('server', '=', $is_mu)->where('node_class', '<=', $user->class)->where("type", "1")->where(
                         function ($query) use ($user) {
                             $query->where("node_group", "=", $user->node_group)
                                 ->orWhere("node_group", "=", 0);
                         }
                     )->get();
-                }else{
+                } else {
                     $mu_nodes = Node::where('sort', 9)->where('node_class', '<=', $user->class)->where("type", "1")->where(
                         function ($query) use ($user) {
                             $query->where("node_group", "=", $user->node_group)
@@ -199,12 +212,12 @@ class URL
                         }
                     }
                     $item = URL::getItem($user, $node, 0, $relay_rule_id, $is_ss);
-                    if($item != null) {
+                    if ($item != null) {
                         array_push($return_array, $item);
                     }
-                }else{
+                } else {
                     $item = URL::getItem($user, $node, 0, 0, $is_ss);
-                    if($item != null) {
+                    if ($item != null) {
                         array_push($return_array, $item);
                     }
                 }
@@ -220,12 +233,12 @@ class URL
                             }
                         }
                         $item = URL::getItem($user, $node, $mu_node->server, $relay_rule_id, $is_ss);
-                        if($item != null) {
+                        if ($item != null) {
                             array_push($return_array, $item);
                         }
-                    }else{
+                    } else {
                         $item = URL::getItem($user, $node, $mu_node->server, 0, $is_ss);
-                        if($item != null) {
+                        if ($item != null) {
                             array_push($return_array, $item);
                         }
                     }
@@ -234,82 +247,88 @@ class URL
         }
         return $return_array;
     }
-    public static function getAllUrl($user, $is_mu, $is_ss = 0) {
+
+    public static function getAllUrl($user, $is_mu, $is_ss = 0)
+    {
         $return_url = '';
-		if(!$is_ss){
-			$return_url .= URL::getUserTraffic($user, $is_mu).PHP_EOL;
-			$return_url .= URL::getUserClassExpiration($user, $is_mu).PHP_EOL;
-		}
-        if(strtotime($user->expire_in)expire_in) < time()) {
+            return $return_url;
+        }
         $items = URL::getAllItems($user, $is_mu, $is_ss);
-        foreach($items as $item) {
-            $return_url .= URL::getItemUrl($item, $is_ss).PHP_EOL;
+        foreach ($items as $item) {
+            $return_url .= URL::getItemUrl($item, $is_ss) . PHP_EOL;
         }
-        if(Config::get('mergeSub')=='true' and in_array($is_mu, array(0, 1))){
-            $is_mu = $is_mu==0?1:0;
+        if (Config::get('mergeSub') == 'true' and in_array($is_mu, array(0, 1))) {
+            $is_mu = $is_mu == 0 ? 1 : 0;
             $items = URL::getAllItems($user, $is_mu, $is_ss);
-            foreach($items as $item) {
-                $return_url .= URL::getItemUrl($item, $is_ss).PHP_EOL;
+            foreach ($items as $item) {
+                $return_url .= URL::getItemUrl($item, $is_ss) . PHP_EOL;
             }
         }
         return $return_url;
     }
 
-    public static function getItemUrl($item, $is_ss) {
+    public static function getItemUrl($item, $is_ss)
+    {
         $ss_obfs_list = Config::getSupportParam('ss_obfs');
-        if(!$is_ss) {
-            $ssurl = $item['address'].":".$item['port'].":".$item['protocol'].":".$item['method'].":".$item['obfs'].":".Tools::base64_url_encode($item['passwd'])."/?obfsparam=".Tools::base64_url_encode($item['obfs_param'])."&protoparam=".Tools::base64_url_encode($item['protocol_param'])."&remarks=".Tools::base64_url_encode($item['remark'])."&group=".Tools::base64_url_encode($item['group']);
-            return "ssr://".Tools::base64_url_encode($ssurl);
+        if (!$is_ss) {
+            $ssurl = $item['address'] . ":" . $item['port'] . ":" . $item['protocol'] . ":" . $item['method'] . ":" . $item['obfs'] . ":" . Tools::base64_url_encode($item['passwd']) . "/?obfsparam=" . Tools::base64_url_encode($item['obfs_param']) . "&protoparam=" . Tools::base64_url_encode($item['protocol_param']) . "&remarks=" . Tools::base64_url_encode($item['remark']) . "&group=" . Tools::base64_url_encode($item['group']);
+            return "ssr://" . Tools::base64_url_encode($ssurl);
         } else {
-            if($is_ss == 2) {
-                $personal_info = $item['method'].':'.$item['passwd']."@".$item['address'].":".$item['port'];
-                $ssurl = "ss://".Tools::base64_url_encode($personal_info);
-                $ssurl .= "#".rawurlencode(Config::get('appName')." - ".$item['remark']);
-            }else{
-                $personal_info = $item['method'].':'.$item['passwd'];
-                $ssurl = "ss://".Tools::base64_url_encode($personal_info)."@".$item['address'].":".$item['port'];
+            if ($is_ss == 2) {
+                $personal_info = $item['method'] . ':' . $item['passwd'] . "@" . $item['address'] . ":" . $item['port'];
+                $ssurl = "ss://" . Tools::base64_url_encode($personal_info);
+                $ssurl .= "#" . rawurlencode(Config::get('appName') . " - " . $item['remark']);
+            } else {
+                $personal_info = $item['method'] . ':' . $item['passwd'];
+                $ssurl = "ss://" . Tools::base64_url_encode($personal_info) . "@" . $item['address'] . ":" . $item['port'];
                 $plugin = '';
-                if(in_array($item['obfs'], $ss_obfs_list) || $item['obfs'] == "v2ray") {
-                    if(strpos($item['obfs'], 'http') !== FALSE) {
+                if (in_array($item['obfs'], $ss_obfs_list) || $item['obfs'] == "v2ray") {
+                    if (strpos($item['obfs'], 'http') !== FALSE) {
                         $plugin .= "obfs-local;obfs=http";
                     } elseif (strpos($item['obfs'], 'tls') !== false) {
                         $plugin .= "obfs-local;obfs=tls";
                     } else {
-                        $plugin .= "v2ray;".$item['obfs_param'];
+                        $plugin .= "v2ray;" . $item['obfs_param'];
                     }
-                    if($item['obfs_param'] != '' && $item['obfs'] != "v2ray") {
-                        $plugin .= ";obfs-host=".$item['obfs_param'];
+                    if ($item['obfs_param'] != '' && $item['obfs'] != "v2ray") {
+                        $plugin .= ";obfs-host=" . $item['obfs_param'];
                     }
-                    $ssurl .= "?plugin=".rawurlencode($plugin);
+                    $ssurl .= "?plugin=" . rawurlencode($plugin);
                 }
-                $ssurl .= "#".rawurlencode(Config::get('appName')." - ".$item['remark']);
+                $ssurl .= "#" . rawurlencode(Config::get('appName') . " - " . $item['remark']);
             }
             return $ssurl;
         }
     }
-    public static function getV2Url($user, $node, $arrout = 0){
+
+    public static function getV2Url($user, $node, $arrout = 0)
+    {
         $item = Tools::v2Array($node->server);
         $item['v'] = "2";
         $item['ps'] = $node->name;
         $item['id'] = $user->getUuid();
-        
+
         if ($arrout == 0) {
-            return "vmess://".base64_encode((json_encode($item, JSON_UNESCAPED_UNICODE)));
+            return "vmess://" . base64_encode((json_encode($item, JSON_UNESCAPED_UNICODE)));
         } else {
             return $item;
         }
     }
 
-    public static function getAllVMessUrl($user, $arrout = 0) {
+    public static function getAllVMessUrl($user, $arrout = 0)
+    {
         $nodes = Node::where(
             function ($query) {
                 $query->where('sort', 11)
                     ->orwhere('sort', 12);
             }
-            )->where(
-            function ($query) use ($user){
+        )->where(
+            function ($query) use ($user) {
                 $query->where("node_group", "=", $user->node_group)
                     ->orWhere("node_group", "=", 0);
             }
@@ -329,171 +348,174 @@ class URL
         return $result;
     }
 
-	public static function getAllSSDUrl($user){
-		if (!URL::SSCanConnect($user)){
-			return null;
-		}
-		$array_all=array();
-		$array_all['airport']=Config::get("appName");
-		$array_all['port']=$user->port;
-		$array_all['encryption']=$user->method;
-		$array_all['password']=$user->passwd;
-		$array_all['traffic_used']=Tools::flowToGB($user->u+$user->d);
-		$array_all['traffic_total']=Tools::flowToGB($user->transfer_enable);
-		$array_all['expiry']=$user->class_expire;
-		$array_all['url']=Config::get('subUrl').LinkController::GenerateSSRSubCode($user->id, 0).'?mu=3';
-		$plugin_options='';
-		if(strpos($user->obfs,'http')!=FALSE){
-			$plugin_options='obfs=http';
-		}
-		if(strpos($user->obfs,'tls')!=FALSE){
-			$plugin_options='obfs=tls';
-		}
-		if($plugin_options!=''){
-			$array_all['plugin']='simple-obfs';//目前只支持这个
-			$array_all['plugin_options']=$plugin_options;
-			if($user->obfs_param!=''){
-				$array_all['plugin_options'].=';obfs-host='.$user->obfs_param;
-			}
-		}
-
-		$nodes_muport=Node::where('type',1)->where('sort', '=', 9)->orderBy('name')->get();
-		$array_server=array();
-		$nodes = Node::where('type',1)->where('node_class','<=',$user->class)
-			->where(function ($func){
-				$func->where('sort', '=', 0)
+    public static function getAllSSDUrl($user)
+    {
+        if (!URL::SSCanConnect($user)) {
+            return null;
+        }
+        $array_all = array();
+        $array_all['airport'] = Config::get("appName");
+        $array_all['port'] = $user->port;
+        $array_all['encryption'] = $user->method;
+        $array_all['password'] = $user->passwd;
+        $array_all['traffic_used'] = Tools::flowToGB($user->u + $user->d);
+        $array_all['traffic_total'] = Tools::flowToGB($user->transfer_enable);
+        $array_all['expiry'] = $user->class_expire;
+        $array_all['url'] = Config::get('subUrl') . LinkController::GenerateSSRSubCode($user->id, 0) . '?mu=3';
+        $plugin_options = '';
+        if (strpos($user->obfs, 'http') != FALSE) {
+            $plugin_options = 'obfs=http';
+        }
+        if (strpos($user->obfs, 'tls') != FALSE) {
+            $plugin_options = 'obfs=tls';
+        }
+        if ($plugin_options != '') {
+            $array_all['plugin'] = 'simple-obfs';//目前只支持这个
+            $array_all['plugin_options'] = $plugin_options;
+            if ($user->obfs_param != '') {
+                $array_all['plugin_options'] .= ';obfs-host=' . $user->obfs_param;
+            }
+        }
+
+        $nodes_muport = Node::where('type', 1)->where('sort', '=', 9)->orderBy('name')->get();
+        $array_server = array();
+        $nodes = Node::where('type', 1)->where('node_class', '<=', $user->class)
+            ->where(function ($func) {
+                $func->where('sort', '=', 0)
                     ->orwhere('sort', '=', 10)
                     ->orwhere('sort', '=', 13);
-			})
-			->where(function ($func) use ($user){
-				$func->where('node_group', '=', $user->node_group)
-					->orwhere('node_group', '=', 0);
-			})->orderBy('name')->get();
-		$server_index=1;
-		foreach($nodes as $node){
-            $server=array();
-            if ($node->sort==13) {
-                if (URL::CanMethodConnect($user->method)!=2) {
+            })
+            ->where(function ($func) use ($user) {
+                $func->where('node_group', '=', $user->node_group)
+                    ->orwhere('node_group', '=', 0);
+            })->orderBy('name')->get();
+        $server_index = 1;
+        foreach ($nodes as $node) {
+            $server = array();
+            if ($node->sort == 13) {
+                if (URL::CanMethodConnect($user->method) != 2) {
                     continue;
                 }
                 $ssv2Array = Tools::ssv2Array($node->server);
-                $server['server']=$ssv2Array['add'];
-                $server['id']=$server_index;
-                $server['remarks']=$node->name.' - 单多'.$ssv2Array['port'].'端口';
-                $server['port']=$ssv2Array['port'];
-                $server['encryption']=$user->method;
-                $server['password']=$user->passwd;
-                $server['plugin']='v2ray';
+                $server['server'] = $ssv2Array['add'];
+                $server['id'] = $server_index;
+                $server['remarks'] = $node->name . ' - 单多' . $ssv2Array['port'] . '端口';
+                $server['port'] = $ssv2Array['port'];
+                $server['encryption'] = $user->method;
+                $server['password'] = $user->passwd;
+                $server['plugin'] = 'v2ray';
                 if ($ssv2Array['tls'] == "tls" && $ssv2Array['net'] == "ws") {
-                    $server['plugin_options']="mode=ws;security=tls;path=".$ssv2Array['path'].";host=".$user->getMuMd5();
+                    $server['plugin_options'] = "mode=ws;security=tls;path=" . $ssv2Array['path'] . ";host=" . $user->getMuMd5();
                 } else {
-                    $server['plugin_options']="mode=ws;security=none;path=".$ssv2Array['path'].";host=".$user->getMuMd5();
+                    $server['plugin_options'] = "mode=ws;security=none;path=" . $ssv2Array['path'] . ";host=" . $user->getMuMd5();
                 }
                 array_push($array_server, $server);
                 $server_index++;
                 continue;
             }
-			$server['id']=$server_index;
-			$server['server']=$node->server;
-			//判断是否是中转起源节点
-			$relay_rule = Relay::where('source_node_id', $node->id)->where(
-				function ($query) use ($user) {
-					$query->Where('user_id', '=', $user->id)
-						->orWhere('user_id', '=', 0);
-				}
-			)->orderBy('priority','DESC')->orderBy('id')->first();
-			if ($relay_rule != null) {
-				//是中转起源节点
-				$server['remarks']=$node->name.' => '.$relay_rule->dist_node()->name;
-				$server['ratio']=$node->traffic_rate+$relay_rule->dist_node()->traffic_rate;
-				array_push($array_server,$server);
-				$server_index++;
-				continue;
-			}
-
-			//不是中转起源节点
-
-			$server['ratio']=$node->traffic_rate;
-			//包含普通
-			if($node->mu_only==0||$node->mu_only==-1){
-			$server['remarks']=$node->name;
-				array_push($array_server,$server);
-				$server_index++;
-			}
-			//包含单多
-			if($node->mu_only==0||$node->mu_only==1){
-				$nodes_muport=Node::where('type','1')->where('sort', '=', 9)
-					->where(function ($query) use ($user) {
-						$query->Where('node_group', '=', $user->group)
-							->orWhere('node_group', '=', 0);
-					})
-					->where('node_class', '<=', $user->class)
-					->orderBy('server')->get();
-				foreach($nodes_muport as $node_muport){
-					$muport_user=User::where('port','=',$node_muport->server)->first();
-					if(!URL::SSCanConnect($muport_user)){
-						continue;
-					}
-					$server['id']=$server_index;
-					$server['remarks']=$node->name.' - 单多'.$node_muport->server.'端口';
-					$server['port']=$node_muport->server;
-					$server['encryption']=$muport_user->method;
-					$server['password']=$muport_user->passwd;
-					$server['plugin']='simple-obfs';//目前只支持这个
-					$plugin_options='';
-					if(strpos($muport_user->obfs,'http')!=FALSE){
-						$plugin_options='obfs=http';
-					}
-					if(strpos($muport_user->obfs,'tls')!=FALSE){
-						$plugin_options='obfs=tls';
-					}
-					$server['plugin_options']=$plugin_options.';obfs-host='.$user->getMuMd5();
-					array_push($array_server,$server);
-					$server_index++;
-				}
-			}
-		}
-
-		$array_all['servers']=$array_server;
-		$json_all=json_encode($array_all);
-
-		return 'ssd://'.Tools::base64_url_encode($json_all);
-	}
-
-    public static function getJsonObfs($item) {
+            $server['id'] = $server_index;
+            $server['server'] = $node->server;
+            //判断是否是中转起源节点
+            $relay_rule = Relay::where('source_node_id', $node->id)->where(
+                function ($query) use ($user) {
+                    $query->Where('user_id', '=', $user->id)
+                        ->orWhere('user_id', '=', 0);
+                }
+            )->orderBy('priority', 'DESC')->orderBy('id')->first();
+            if ($relay_rule != null) {
+                //是中转起源节点
+                $server['remarks'] = $node->name . ' => ' . $relay_rule->dist_node()->name;
+                $server['ratio'] = $node->traffic_rate + $relay_rule->dist_node()->traffic_rate;
+                array_push($array_server, $server);
+                $server_index++;
+                continue;
+            }
+
+            //不是中转起源节点
+
+            $server['ratio'] = $node->traffic_rate;
+            //包含普通
+            if ($node->mu_only == 0 || $node->mu_only == -1) {
+                $server['remarks'] = $node->name;
+                array_push($array_server, $server);
+                $server_index++;
+            }
+            //包含单多
+            if ($node->mu_only == 0 || $node->mu_only == 1) {
+                $nodes_muport = Node::where('type', '1')->where('sort', '=', 9)
+                    ->where(function ($query) use ($user) {
+                        $query->Where('node_group', '=', $user->group)
+                            ->orWhere('node_group', '=', 0);
+                    })
+                    ->where('node_class', '<=', $user->class)
+                    ->orderBy('server')->get();
+                foreach ($nodes_muport as $node_muport) {
+                    $muport_user = User::where('port', '=', $node_muport->server)->first();
+                    if (!URL::SSCanConnect($muport_user)) {
+                        continue;
+                    }
+                    $server['id'] = $server_index;
+                    $server['remarks'] = $node->name . ' - 单多' . $node_muport->server . '端口';
+                    $server['port'] = $node_muport->server;
+                    $server['encryption'] = $muport_user->method;
+                    $server['password'] = $muport_user->passwd;
+                    $server['plugin'] = 'simple-obfs';//目前只支持这个
+                    $plugin_options = '';
+                    if (strpos($muport_user->obfs, 'http') != FALSE) {
+                        $plugin_options = 'obfs=http';
+                    }
+                    if (strpos($muport_user->obfs, 'tls') != FALSE) {
+                        $plugin_options = 'obfs=tls';
+                    }
+                    $server['plugin_options'] = $plugin_options . ';obfs-host=' . $user->getMuMd5();
+                    array_push($array_server, $server);
+                    $server_index++;
+                }
+            }
+        }
+
+        $array_all['servers'] = $array_server;
+        $json_all = json_encode($array_all);
+
+        return 'ssd://' . Tools::base64_url_encode($json_all);
+    }
+
+    public static function getJsonObfs($item)
+    {
         $ss_obfs_list = Config::getSupportParam('ss_obfs');
         $plugin = "";
-        if(in_array($item['obfs'], $ss_obfs_list)) {
-            if(strpos($item['obfs'], 'http') !== FALSE) {
+        if (in_array($item['obfs'], $ss_obfs_list)) {
+            if (strpos($item['obfs'], 'http') !== FALSE) {
                 $plugin .= "obfs-local --obfs http";
             } else {
                 $plugin .= "obfs-local --obfs tls";
             }
-            if($item['obfs_param'] != '') {
-                $plugin .= "--obfs-host ".$item['obfs_param'];
+            if ($item['obfs_param'] != '') {
+                $plugin .= "--obfs-host " . $item['obfs_param'];
             }
         }
         return $plugin;
     }
-    public static function getSurgeObfs($item) {
+
+    public static function getSurgeObfs($item)
+    {
         $ss_obfs_list = Config::getSupportParam('ss_obfs');
         $plugin = "";
-        if(in_array($item['obfs'], $ss_obfs_list)) {
-            if(strpos($item['obfs'], 'http') !== FALSE) {
+        if (in_array($item['obfs'], $ss_obfs_list)) {
+            if (strpos($item['obfs'], 'http') !== FALSE) {
                 $plugin .= ",obfs=http";
-            }
-			else {
+            } else {
                 $plugin .= ",obfs=tls";
             }
-            if($item['obfs_param'] != '') {
-                $plugin .= ",obfs-host=".$item['obfs_param'];
+            if ($item['obfs_param'] != '') {
+                $plugin .= ",obfs-host=" . $item['obfs_param'];
+            } else {
+                $plugin .= ",obfs-host=wns.windows.com";
             }
-			else {
-				$plugin .= ",obfs-host=wns.windows.com";
-			}
         }
         return $plugin;
     }
+
     /*
     * Conn info
     * address
@@ -506,36 +528,37 @@ class URL
     * obfs
     * obfs_param
     */
-    public static function getItem($user, $node, $mu_port = 0, $relay_rule_id = 0, $is_ss = 0) {
+    public static function getItem($user, $node, $mu_port = 0, $relay_rule_id = 0, $is_ss = 0)
+    {
         $relay_rule = Relay::where('id', $relay_rule_id)->where(
             function ($query) use ($user) {
                 $query->Where("user_id", "=", $user->id)
                     ->orWhere("user_id", "=", 0);
             }
-        )->orderBy('priority','DESC')->orderBy('id')->first();
+        )->orderBy('priority', 'DESC')->orderBy('id')->first();
         $node_name = $node->name;
         if ($relay_rule != null) {
-            $node_name .= " - ".$relay_rule->dist_node()->name;
+            $node_name .= " - " . $relay_rule->dist_node()->name;
         }
-        if($mu_port != 0) {
+        if ($mu_port != 0) {
             $mu_user = User::where('port', '=', $mu_port)->where("is_multi_user", "<>", 0)->first();
             if ($mu_user == null) {
                 return;
             }
             $mu_user->obfs_param = $user->getMuMd5();
-            $mu_user->protocol_param = $user->id.":".$user->passwd;
+            $mu_user->protocol_param = $user->id . ":" . $user->passwd;
             $user = $mu_user;
-            if(Config::get('mergeSub')!='true'){
-                $node_name .= " - ".$mu_port." 单端口";
+            if (Config::get('mergeSub') != 'true') {
+                $node_name .= " - " . $mu_port . " 单端口";
             }
         }
-        if($is_ss) {
-            if(!URL::SSCanConnect($user)) {
+        if ($is_ss) {
+            if (!URL::SSCanConnect($user)) {
                 return;
             }
             $user = URL::getSSConnectInfo($user);
-        }else{
-            if(!URL::SSRCanConnect($user)) {
+        } else {
+            if (!URL::SSRCanConnect($user)) {
                 return;
             }
             $user = URL::getSSRConnectInfo($user);
@@ -549,9 +572,9 @@ class URL
             $return_array['path'] = $server['path'];
             $return_array['obfs'] = "v2ray";
             if ($server['tls'] == "tls" && $server['net'] == "ws") {
-                $return_array['obfs_param'] = "mode=ws;security=tls;path=".$server['path'].";host=".$user->getMuMd5();        
+                $return_array['obfs_param'] = "mode=ws;security=tls;path=" . $server['path'] . ";host=" . $user->getMuMd5();
             } else {
-                $return_array['obfs_param'] = "mode=ws;security=none;path=".$server['path'].";host=".$user->getMuMd5();        
+                $return_array['obfs_param'] = "mode=ws;security=none;path=" . $server['path'] . ";host=" . $user->getMuMd5();
             }
         } else {
             $return_array['address'] = $node->server;
@@ -565,45 +588,48 @@ class URL
         $return_array['method'] = $user->method;
         $return_array['remark'] = $node_name;
         $return_array['group'] = Config::get('appName');
-        if($mu_port != 0 && Config::get('mergeSub')!='true') {
+        if ($mu_port != 0 && Config::get('mergeSub') != 'true') {
             $return_array['group'] .= ' - 单端口';
         }
         return $return_array;
     }
-    public static function cloneUser($user) {
+
+    public static function cloneUser($user)
+    {
         $new_user = clone $user;
         return $new_user;
     }
 
-	public static function getUserTraffic($user, $is_mu = 0){
+    public static function getUserTraffic($user, $is_mu = 0)
+    {
         $group_name = Config::get('appName');
-		if(Config::get('mergeSub')!='true' and $is_mu == 1){
-			$group_name .= ' - 单端口';
-		}
-		if(strtotime($user->expire_in)>time()){
-			if($user->transfer_enable==0){
-				$percent='0.00%';
-			}
-			else{
-				$percent=number_format(($user->transfer_enable-$user->u-$user->d)/$user->transfer_enable*100,2).'%';
-			}
-			$ssurl = "www.google.com:1:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=".Tools::base64_url_encode('剩余流量:'.$percent.' '.$user->unusedTraffic())."&group=".Tools::base64_url_encode($group_name);
-		}else{
-			$ssurl = "www.google.com:1:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=".Tools::base64_url_encode("账户已过期,请续费后使用")."&group=".Tools::base64_url_encode($group_name);
-		}
-      	return "ssr://".Tools::base64_url_encode($ssurl);
-	}
-
-    public static function getUserClassExpiration($user, $is_mu = 0){
+        if (Config::get('mergeSub') != 'true' and $is_mu == 1) {
+            $group_name .= ' - 单端口';
+        }
+        if (strtotime($user->expire_in) > time()) {
+            if ($user->transfer_enable == 0) {
+                $percent = '0.00%';
+            } else {
+                $percent = number_format(($user->transfer_enable - $user->u - $user->d) / $user->transfer_enable * 100, 2) . '%';
+            }
+            $ssurl = "www.google.com:1:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=" . Tools::base64_url_encode('剩余流量:' . $percent . ' ' . $user->unusedTraffic()) . "&group=" . Tools::base64_url_encode($group_name);
+        } else {
+            $ssurl = "www.google.com:1:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=" . Tools::base64_url_encode("账户已过期,请续费后使用") . "&group=" . Tools::base64_url_encode($group_name);
+        }
+        return "ssr://" . Tools::base64_url_encode($ssurl);
+    }
+
+    public static function getUserClassExpiration($user, $is_mu = 0)
+    {
         $group_name = Config::get('appName');
-		if(Config::get('mergeSub')!='true' and $is_mu == 1){
-			$group_name .= ' - 单端口';
-		}
-		if(strtotime($user->expire_in)>time()){
-			$ssurl = "www.google.com:2:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=".Tools::base64_url_encode("过期时间:".$user->class_expire)."&group=".Tools::base64_url_encode($group_name);
-		}else{
-			$ssurl = "www.google.com:2:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=".Tools::base64_url_encode("账户已过期,请续费后使用")."&group=".Tools::base64_url_encode($group_name);
-		}
-	return "ssr://".Tools::base64_url_encode($ssurl);
-  }
+        if (Config::get('mergeSub') != 'true' and $is_mu == 1) {
+            $group_name .= ' - 单端口';
+        }
+        if (strtotime($user->expire_in) > time()) {
+            $ssurl = "www.google.com:2:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=" . Tools::base64_url_encode("过期时间:" . $user->class_expire) . "&group=" . Tools::base64_url_encode($group_name);
+        } else {
+            $ssurl = "www.google.com:2:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=" . Tools::base64_url_encode("账户已过期,请续费后使用") . "&group=" . Tools::base64_url_encode($group_name);
+        }
+        return "ssr://" . Tools::base64_url_encode($ssurl);
+    }
 }