张保健 пре 4 година
родитељ
комит
97d25c38f3
100 измењених фајлова са 13047 додато и 1 уклоњено
  1. 54 0
      .env
  2. 20 1
      README.md
  3. 0 0
      app/Console/Commands/.gitkeep
  4. 29 0
      app/Console/Kernel.php
  5. 10 0
      app/Events/Event.php
  6. 16 0
      app/Events/ExampleEvent.php
  7. 50 0
      app/Exceptions/Handler.php
  8. 272 0
      app/Http/Controllers/ApiController.php
  9. 646 0
      app/Http/Controllers/ApiGuestController.php
  10. 330 0
      app/Http/Controllers/ApiTopController.php
  11. 75 0
      app/Http/Controllers/AppController.php
  12. 15 0
      app/Http/Controllers/BaseController.php
  13. 41 0
      app/Http/Controllers/CaseController.php
  14. 72 0
      app/Http/Controllers/Console/CacheController.php
  15. 153 0
      app/Http/Controllers/Console/PkProcessController.php
  16. 54 0
      app/Http/Controllers/Controller.php
  17. 160 0
      app/Http/Controllers/CorpController.php
  18. 31 0
      app/Http/Controllers/DingtalkController.php
  19. 41 0
      app/Http/Controllers/ExampleController.php
  20. 135 0
      app/Http/Controllers/PersonDingtalkController.php
  21. 292 0
      app/Http/Controllers/PkApiController.php
  22. 295 0
      app/Http/Controllers/WebController.php
  23. 44 0
      app/Http/Middleware/Authenticate.php
  24. 21 0
      app/Http/Middleware/ExampleMiddleware.php
  25. 26 0
      app/Jobs/ExampleJob.php
  26. 24 0
      app/Jobs/Job.php
  27. 76 0
      app/Libs/Aliyun/Api/Sms/Request/V20170525/QueryInterSmsIsoInfoRequest.php
  28. 103 0
      app/Libs/Aliyun/Api/Sms/Request/V20170525/QuerySendDetailsRequest.php
  29. 121 0
      app/Libs/Aliyun/Api/Sms/Request/V20170525/SendBatchSmsRequest.php
  30. 131 0
      app/Libs/Aliyun/Api/Sms/Request/V20170525/SendInterSmsRequest.php
  31. 113 0
      app/Libs/Aliyun/Api/Sms/Request/V20170525/SendSmsRequest.php
  32. 125 0
      app/Libs/Aliyun/Core/AcsRequest.php
  33. 29 0
      app/Libs/Aliyun/Core/AcsResponse.php
  34. 72 0
      app/Libs/Aliyun/Core/Auth/Credential.php
  35. 12 0
      app/Libs/Aliyun/Core/Auth/ISigner.php
  36. 20 0
      app/Libs/Aliyun/Core/Auth/ShaHmac1Signer.php
  37. 20 0
      app/Libs/Aliyun/Core/Auth/ShaHmac256Signer.php
  38. 23 0
      app/Libs/Aliyun/Core/Config.php
  39. 124 0
      app/Libs/Aliyun/Core/DefaultAcsClient.php
  40. 50 0
      app/Libs/Aliyun/Core/Exception/ClientException.php
  41. 31 0
      app/Libs/Aliyun/Core/Exception/ServerException.php
  42. 69 0
      app/Libs/Aliyun/Core/Http/HttpHelper.php
  43. 38 0
      app/Libs/Aliyun/Core/Http/HttpResponse.php
  44. 7 0
      app/Libs/Aliyun/Core/IAcsClient.php
  45. 137 0
      app/Libs/Aliyun/Core/Profile/DefaultProfile.php
  46. 14 0
      app/Libs/Aliyun/Core/Profile/IClientProfile.php
  47. 47 0
      app/Libs/Aliyun/Core/Regions/Endpoint.php
  48. 63 0
      app/Libs/Aliyun/Core/Regions/EndpointConfig.php
  49. 53 0
      app/Libs/Aliyun/Core/Regions/EndpointProvider.php
  50. 28 0
      app/Libs/Aliyun/Core/Regions/ProductDomain.php
  51. 1349 0
      app/Libs/Aliyun/Core/Regions/endpoints.xml
  52. 207 0
      app/Libs/Aliyun/Core/RoaAcsRequest.php
  53. 105 0
      app/Libs/Aliyun/Core/RpcAcsRequest.php
  54. 91 0
      app/Libs/AppClient.php
  55. 162 0
      app/Libs/Curl.php
  56. 31 0
      app/Listeners/ExampleListener.php
  57. 24 0
      app/Models/Blockade.php
  58. 20 0
      app/Models/BlockadeUserAnswer.php
  59. 33 0
      app/Models/Corp.php
  60. 23 0
      app/Models/Department.php
  61. 22 0
      app/Models/KnowledgeMoneyRecord.php
  62. 25 0
      app/Models/Lottery.php
  63. 20 0
      app/Models/LotteryBoxs.php
  64. 23 0
      app/Models/PkRoom.php
  65. 21 0
      app/Models/PkUserAnswer.php
  66. 21 0
      app/Models/Prize.php
  67. 24 0
      app/Models/Question.php
  68. 23 0
      app/Models/QuestionCategory.php
  69. 21 0
      app/Models/User.php
  70. 18 0
      app/Providers/AppServiceProvider.php
  71. 39 0
      app/Providers/AuthServiceProvider.php
  72. 19 0
      app/Providers/EventServiceProvider.php
  73. 47 0
      app/Services/AccessToken.php
  74. 66 0
      app/Services/BrainstormingService.php
  75. 121 0
      app/Services/CookieService.php
  76. 68 0
      app/Services/DepartmentService.php
  77. 33 0
      app/Services/ErrorMessageService.php
  78. 69 0
      app/Services/GameTimeService.php
  79. 30 0
      app/Services/LogEventService.php
  80. 67 0
      app/Services/OnlineLimitService.php
  81. 280 0
      app/Services/PkService.php
  82. 54 0
      app/Services/PushMessageService.php
  83. 112 0
      app/Services/QuestionService.php
  84. 93 0
      app/Services/SmsService.php
  85. 457 0
      app/Services/TopService.php
  86. 350 0
      app/Services/UserService.php
  87. 23 0
      app/Traits/Singleton.php
  88. 35 0
      artisan
  89. 115 0
      bootstrap/app.php
  90. 46 0
      composer.json
  91. 4073 0
      composer.lock
  92. 15 0
      config/errCode.php
  93. 17 0
      config/errMsg.php
  94. 19 0
      database/factories/ModelFactory.php
  95. 0 0
      database/migrations/.gitkeep
  96. 16 0
      database/seeds/DatabaseSeeder.php
  97. 53 0
      example.env
  98. 27 0
      phpunit.xml
  99. 28 0
      public/index.php
  100. 0 0
      public/static/index - 副本.html

+ 54 - 0
.env Прегледај датотеку

@@ -0,0 +1,54 @@
1
+APP_ENV=local
2
+APP_DEBUG=true
3
+APP_KEY=
4
+APP_TIMEZONE=PRC
5
+APP_LOCALE=zh-CN
6
+
7
+LOG_CHANNEL=stack
8
+LOG_SLACK_WEBHOOK_URL=
9
+
10
+DB_CONNECTION=mysql
11
+DB_HOST=rdswssh45zep1dpvgvsjvpo.mysql.rds.aliyuncs.com
12
+DB_PORT=3306
13
+DB_DATABASE=game
14
+DB_USERNAME=jtp
15
+DB_PASSWORD=crgGodH8WaYAXgtu
16
+
17
+REDIS_HOST=127.0.0.1
18
+REDIS_PORT=6379
19
+REDIS_DATABASE=0
20
+REDIS_PASSWORD=hnredis123456
21
+
22
+REDIS_HOST_LOG=127.0.0.1
23
+REDIS_PORT_LOG=6379
24
+REDIS_PASSWORD_LOG=hnredis123456
25
+
26
+CACHE_DRIVER=redis
27
+QUEUE_DRIVER=redis
28
+
29
+ALIYUN_ACCESS_KEY_ID="LTAIRwTwDdeclRzu"
30
+ALIYUN_ACCESS_KEY_SECRET="Iz68nzAgp1LD8Relicz0Z8stdH2RHR"
31
+SMS_TEMPLATE_CODE="SMS_135031096"
32
+SMS_SIGN_NAME="爱关怀"
33
+
34
+NO_PRIZE_IMG=""
35
+
36
+WX_APP_ID="wx525bff6a4717631a"
37
+WX_APP_SECRET="eb4868781d7da8972c75104748c7af93"
38
+
39
+SSO_URL="https://dt.sgjyun.com/common/sso"
40
+
41
+COOKIE_DOMAIN="sgjyun.com"
42
+
43
+WEB_URL="https://dt.sgjyun.com/brainstorming"
44
+
45
+NOT_FOUND_URL="https://s1-hn.aghcdn.com/activity/common/page/crowd/index.html?"
46
+ERROR_MESSAGE_URL="https://s1-hn.aghcdn.com/activity/common/page/crowd/errEvir.html"
47
+
48
+QINIU_ACCESS_KEY="4zxzx2L8XVodROkDhK-p8Vcr7Dn-fqN9feC5Zghx"
49
+QINIU_SECRET_KEY="CXJp6zx-Z2-Y-9ITPmwJgmjc6vUNI0s9emhEVMSZ"
50
+QINIU_BUCKET=game
51
+
52
+APP_NAME="叮当答题"
53
+
54
+APP_SUPPORT="叮当科技"

+ 20 - 1
README.md Прегледај датотеку

@@ -1,2 +1,21 @@
1
-# web
1
+# Lumen PHP Framework
2 2
 
3
+[![Build Status](https://travis-ci.org/laravel/lumen-framework.svg)](https://travis-ci.org/laravel/lumen-framework)
4
+[![Total Downloads](https://poser.pugx.org/laravel/lumen-framework/d/total.svg)](https://packagist.org/packages/laravel/lumen-framework)
5
+[![Latest Stable Version](https://poser.pugx.org/laravel/lumen-framework/v/stable.svg)](https://packagist.org/packages/laravel/lumen-framework)
6
+[![Latest Unstable Version](https://poser.pugx.org/laravel/lumen-framework/v/unstable.svg)](https://packagist.org/packages/laravel/lumen-framework)
7
+[![License](https://poser.pugx.org/laravel/lumen-framework/license.svg)](https://packagist.org/packages/laravel/lumen-framework)
8
+
9
+Laravel Lumen is a stunningly fast PHP micro-framework for building web applications with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Lumen attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as routing, database abstraction, queueing, and caching.
10
+
11
+## Official Documentation
12
+
13
+Documentation for the framework can be found on the [Lumen website](http://lumen.laravel.com/docs).
14
+
15
+## Security Vulnerabilities
16
+
17
+If you discover a security vulnerability within Lumen, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
18
+
19
+## License
20
+
21
+The Lumen framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)

+ 0 - 0
app/Console/Commands/.gitkeep Прегледај датотеку


+ 29 - 0
app/Console/Kernel.php Прегледај датотеку

@@ -0,0 +1,29 @@
1
+<?php
2
+
3
+namespace App\Console;
4
+
5
+use Illuminate\Console\Scheduling\Schedule;
6
+use Laravel\Lumen\Console\Kernel as ConsoleKernel;
7
+
8
+class Kernel extends ConsoleKernel
9
+{
10
+    /**
11
+     * The Artisan commands provided by your application.
12
+     *
13
+     * @var array
14
+     */
15
+    protected $commands = [
16
+        //
17
+    ];
18
+
19
+    /**
20
+     * Define the application's command schedule.
21
+     *
22
+     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
23
+     * @return void
24
+     */
25
+    protected function schedule(Schedule $schedule)
26
+    {
27
+        //
28
+    }
29
+}

+ 10 - 0
app/Events/Event.php Прегледај датотеку

@@ -0,0 +1,10 @@
1
+<?php
2
+
3
+namespace App\Events;
4
+
5
+use Illuminate\Queue\SerializesModels;
6
+
7
+abstract class Event
8
+{
9
+    use SerializesModels;
10
+}

+ 16 - 0
app/Events/ExampleEvent.php Прегледај датотеку

@@ -0,0 +1,16 @@
1
+<?php
2
+
3
+namespace App\Events;
4
+
5
+class ExampleEvent extends Event
6
+{
7
+    /**
8
+     * Create a new event instance.
9
+     *
10
+     * @return void
11
+     */
12
+    public function __construct()
13
+    {
14
+        //
15
+    }
16
+}

+ 50 - 0
app/Exceptions/Handler.php Прегледај датотеку

@@ -0,0 +1,50 @@
1
+<?php
2
+
3
+namespace App\Exceptions;
4
+
5
+use Exception;
6
+use Illuminate\Validation\ValidationException;
7
+use Illuminate\Auth\Access\AuthorizationException;
8
+use Illuminate\Database\Eloquent\ModelNotFoundException;
9
+use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
10
+use Symfony\Component\HttpKernel\Exception\HttpException;
11
+
12
+class Handler extends ExceptionHandler
13
+{
14
+    /**
15
+     * A list of the exception types that should not be reported.
16
+     *
17
+     * @var array
18
+     */
19
+    protected $dontReport = [
20
+        AuthorizationException::class,
21
+        HttpException::class,
22
+        ModelNotFoundException::class,
23
+        ValidationException::class,
24
+    ];
25
+
26
+    /**
27
+     * Report or log an exception.
28
+     *
29
+     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
30
+     *
31
+     * @param  \Exception  $e
32
+     * @return void
33
+     */
34
+    public function report(Exception $e)
35
+    {
36
+        parent::report($e);
37
+    }
38
+
39
+    /**
40
+     * Render an exception into an HTTP response.
41
+     *
42
+     * @param  \Illuminate\Http\Request  $request
43
+     * @param  \Exception  $e
44
+     * @return \Illuminate\Http\Response
45
+     */
46
+    public function render($request, Exception $e)
47
+    {
48
+        return parent::render($request, $e);
49
+    }
50
+}

+ 272 - 0
app/Http/Controllers/ApiController.php Прегледај датотеку

@@ -0,0 +1,272 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/25
6
+ * Time: 15:30
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use DB;
12
+use App\Models\Lottery;
13
+use App\Models\LotteryBoxs;
14
+use App\Models\Prize;
15
+use App\Services\BrainstormingService;
16
+use App\Services\GameTimeService;
17
+use App\Services\UserService;
18
+use Illuminate\Http\Request;
19
+use Illuminate\Support\Facades\Log;
20
+use Illuminate\Support\Facades\Redis;
21
+use Qiniu\Auth;
22
+use Qiniu\Storage\UploadManager;
23
+
24
+class ApiController extends Controller
25
+{
26
+
27
+    public function lottery($id)
28
+    {
29
+        $userInfo = UserService::getInstance()->getUser($this->userId);
30
+        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
31
+
32
+        if($brainstorming["is_temp_stop"]==1){
33
+            return response()->json([
34
+                "error" => 1000,
35
+                "message" => "活动已暂停!"
36
+            ]);
37
+        }
38
+
39
+        if($brainstorming["is_open_prize"]==0){
40
+            return response()->json([
41
+                "error" => 1002,
42
+                "message" => "本次活动未设置抽奖!"
43
+            ]);
44
+        }
45
+
46
+        $lottery_level = intval($id);
47
+
48
+        if(GameTimeService::getInstance()->isReachEndTime($this->activityId)){
49
+            return response()->json([
50
+                "error" => 1000,
51
+                "message" => "活动已经结束!"
52
+            ]);
53
+        }
54
+
55
+        if (empty($userInfo)) {
56
+            return response()->json([
57
+                "error" => 1000,
58
+                "message" => config("errMsg.permission_denied")
59
+            ]);
60
+        }
61
+
62
+        $knowledge_money = $userInfo["knowledge_money"];
63
+        $boxs = LotteryBoxs::where("activity_id",$this->activityId)->where("status",1)->orderBy("lottery_level")->get();
64
+        $lottery = [];
65
+        $curHasChance = false;
66
+        foreach ($boxs as $box){
67
+            $has_chance = $knowledge_money>=$box["open_rule"]? true:false;
68
+            if($box["lottery_level"]==$lottery_level&&$has_chance){
69
+                $curHasChance = true;
70
+            }
71
+            array_push($lottery,[
72
+                "lottery_level" => $box["lottery_level"],
73
+                "lottery_name" => $box["lottery_name"],
74
+                "lottery_icon" => $box["lottery_icon"],
75
+                "has_chance" => $has_chance,
76
+                'is_lottery' => false,
77
+                "need_km" => $box["open_rule"]
78
+            ]);
79
+        }
80
+        if (!$curHasChance) {
81
+            return response()->json([
82
+                "error" => 1000,
83
+                "message" => "没有本等级开箱的权限"
84
+            ]);
85
+        }
86
+        /*$lottery_level_1 = $brainstorming["copper_box_km"]==0? 100:$brainstorming["copper_box_km"];
87
+        $lottery_level_2 = $brainstorming["silver_box_km"]==0? 500:$brainstorming["silver_box_km"];
88
+        $lottery_level_3 = $brainstorming["gold_box_km"]==0? 1000:$brainstorming["gold_box_km"];
89
+
90
+        $has_chance_1 = $knowledge_money >= $lottery_level_1 ? true : false;
91
+        $has_chance_2 = $knowledge_money >= $lottery_level_2 ? true : false;
92
+        $has_chance_3 = $knowledge_money >= $lottery_level_3 ? true : false;*/
93
+
94
+        $lotterys = Lottery::where('user_id', $this->userId)
95
+            ->orderBy('lottery_time', 'desc')
96
+            ->get();
97
+
98
+        if ($lotterys) {
99
+            foreach ($lotterys as $lot) {
100
+                if ($lot->lottery_level == $lottery_level) {
101
+                    return response()->json([
102
+                        "error" => 1000,
103
+                        "message" => "该等级宝箱你已经开启过"
104
+                    ]);
105
+                }
106
+            }
107
+        }
108
+
109
+        $prize = Prize::where("status", 1) ->where("activity_id",$this->activityId)-> where("lottery_level",$lottery_level)->get();
110
+        if (empty($prize)) {
111
+            return response()->json([
112
+                "error" => 1000,
113
+                "message" => "该级别没有设置任何奖项"
114
+            ]);
115
+        }
116
+
117
+        $date = date("Ymd");
118
+        $lottery_data = new Lottery;
119
+        $lottery_data->user_id = $this->userId;
120
+        $lottery_data->lottery_level = $lottery_level;
121
+        $lottery_data->prize_id = 0;
122
+        $lottery_data->prize_name = "谢谢参与";
123
+        $lottery_data->prize_image_url = env("NO_PRIZE_IMG");
124
+        $lottery_data->corp_id = $this->corpId;
125
+        $lottery_data->activity_id = $this->activityId;
126
+        $lottery_data->lottery_time = date("Y-m-d H:i:s");
127
+
128
+        $data['prize_id'] = 0;
129
+        $data['prize_name'] = "谢谢参与";
130
+        $data['prize_image_url'] = env("NO_PRIZE_IMG");
131
+        $min = 0;
132
+        $probability = array();
133
+        foreach ($prize as $p){
134
+            $max = $p->prize_weights;
135
+            $value = array( 'min' => $min,
136
+                            'max' => $max,
137
+                            'prize_id' => $p->prize_id,
138
+                            'prize_name' => $p->prize_name,
139
+                            'prize_image_url' => $p->prize_image_url,
140
+                            'prize_day_rule' => $p->prize_day_rule,
141
+                            'prize_count' => $p->prize_count,
142
+                            'prize_grant_count' => $p->prize_grant_count);
143
+            $probability[] = $value;
144
+        }
145
+        shuffle($probability);
146
+
147
+        $rand = rand(1, 1000);
148
+        foreach ($probability as $pr){
149
+            $redisKey = 'bs_prize_count:'.$pr['prize_id'].':'.$date;
150
+            if(!Redis::exists($redisKey)){
151
+                $count = $pr["prize_day_rule"];
152
+                Redis::set($redisKey,$count);
153
+            }else{
154
+                $count =  Redis::get($redisKey);
155
+            }
156
+
157
+            if ($rand > $pr['min'] && $rand <= $pr['max'] && $pr['prize_grant_count'] < $pr['prize_count'] && $count > 0){
158
+                Redis::incrby($redisKey,-1);
159
+                Prize::where('prize_id',$pr['prize_id'])->update(["prize_grant_count" => $pr['prize_grant_count']+1]);
160
+                $lottery_data->prize_id = $pr['prize_id'];
161
+                $lottery_data->prize_name = $pr['prize_name'];
162
+                $lottery_data->prize_image_url = $pr['prize_image_url'];
163
+                $data['prize_id'] = $pr['prize_id'];
164
+                $data['prize_name'] = $pr['prize_name'];
165
+                $data['prize_image_url'] = $pr['prize_image_url'];
166
+                break;
167
+            }
168
+        }
169
+
170
+        $lottery_data->save();
171
+        return response()->json([
172
+            "error" => "0",
173
+            "data" => $data
174
+        ]);
175
+
176
+    }
177
+
178
+    public function lotteryResult(Request $request)
179
+    {
180
+        $userInfo = UserService::getInstance()->getUser($this->userId);
181
+        //$brainstorming = BrainstormingService::getInstance()->get($this->activityId);
182
+
183
+        if ($userInfo) {
184
+            $knowledge_money = $userInfo["knowledge_money"];
185
+            //获取宝箱参数
186
+            $boxs = LotteryBoxs::where("activity_id",$this->activityId)->where("status",1)->orderBy("lottery_level")->get();
187
+
188
+            /*$lottery_level_1 = $brainstorming["copper_box_km"]==0? 100:$brainstorming["copper_box_km"];
189
+            $lottery_level_2 = $brainstorming["silver_box_km"]==0? 500:$brainstorming["silver_box_km"];
190
+            $lottery_level_3 = $brainstorming["gold_box_km"]==0? 1000:$brainstorming["gold_box_km"];
191
+
192
+            $has_chance_1 = $knowledge_money >= $lottery_level_1 ? true:false;
193
+            $has_chance_2 = $knowledge_money >= $lottery_level_2 ? true:false;
194
+            $has_chance_3 = $knowledge_money >= $lottery_level_3 ? true:false;*/
195
+            $lottery = [];
196
+            foreach ($boxs as $box){
197
+                $has_chance = $knowledge_money>=$box["open_rule"]? true:false;
198
+                array_push($lottery,[
199
+                                            "lottery_level" => $box["lottery_level"],
200
+                                            "lottery_name" => $box["lottery_name"],
201
+                                            "lottery_icon" => $box["lottery_icon"],
202
+                                            "has_chance" => $has_chance,
203
+                                            'is_lottery' => false,
204
+                                            "need_km" => $box["open_rule"]
205
+                ]);
206
+            }
207
+
208
+            $guid = $userInfo["guid"];
209
+
210
+            $lotterys = DB::table("bs_user_lotterys")
211
+                            -> leftJoin("bs_users","bs_user_lotterys.user_id","=","bs_users.user_id")
212
+                            -> where("bs_users.guid","=",$guid)
213
+                            -> where("bs_user_lotterys.activity_id",">","28")
214
+                            -> orderBy("bs_user_lotterys.lottery_time","desc")
215
+                            -> get();
216
+
217
+            $cur_lotterys = Lottery::where('user_id',$this->userId)
218
+                       ->orderBy('lottery_time','desc')
219
+                       ->get();
220
+            if ($lotterys){
221
+                /*$lottery = array(
222
+                                array("lottery_level" => '1',"has_chance" => $has_chance_1,'is_lottery' => false,"need_km" => $lottery_level_1),
223
+                                 array("lottery_level" => '2',"has_chance" => $has_chance_2,'is_lottery' => false,"need_km" => $lottery_level_2),
224
+                                 array("lottery_level" => '3',"has_chance" => $has_chance_3,'is_lottery' => false,"need_km" => $lottery_level_3)
225
+                );*/
226
+                $prize = array();
227
+                foreach ($lotterys as $lot){
228
+                    $lotteryName = "";
229
+                    foreach ($lottery as $lot_array){
230
+                        if($lot->lottery_level == $lot_array['lottery_level'])
231
+                        {
232
+                            $lotteryName = $lot_array["lottery_name"];
233
+                        }
234
+                    }
235
+                    $prize[] = [
236
+                        'prize_id'=>$lot->prize_id,
237
+                        'prize_name' => $lot->prize_name,
238
+                        'prize_image_url' => $lot->prize_image_url,
239
+                        'lottery_level' => $lot->lottery_level,
240
+                        'lottery_name' => $lotteryName];
241
+                }
242
+                foreach ($cur_lotterys as $clot) {
243
+                    foreach ($lottery as &$clot_array){
244
+                        if($clot->lottery_level == $clot_array['lottery_level'])
245
+                        {
246
+                            $clot_array['has_chance'] = false;
247
+                            $clot_array['is_lottery'] = true;
248
+                        }
249
+                    }
250
+                }
251
+                $resule = array('error' => 0, 'data' =>array( 'lottery' => $lottery,'prize' => $prize));
252
+                return \response()->json($resule);
253
+            }else{
254
+                return \response()->json([
255
+                    "error" => 0,
256
+                    "data" => [
257
+                        "lottery" => $lottery,
258
+                        "prize" => [
259
+                            "status" => 0
260
+                        ]
261
+                    ]
262
+                ]);
263
+            }
264
+        } else {
265
+            return response()->json([
266
+                "error" => 401,
267
+                "message" => config("errMsg.permission_denied")
268
+            ]);
269
+        }
270
+
271
+    }
272
+}

+ 646 - 0
app/Http/Controllers/ApiGuestController.php Прегледај датотеку

@@ -0,0 +1,646 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/5/16
6
+ * Time: 11:22
7
+ * 访客可以访问的API接口
8
+ */
9
+
10
+namespace App\Http\Controllers;
11
+
12
+use App\Libs\AppClient;
13
+use App\Models\Activity;
14
+use App\Models\User;
15
+use App\Services\AccessToken;
16
+use App\Services\BrainstormingService;
17
+use App\Services\CookieService;
18
+use App\Services\DepartmentService;
19
+use App\Services\ErrorMessageService;
20
+use App\Services\OnlineLimitService;
21
+use App\Services\PkService;
22
+use App\Services\PushMessageService;
23
+use App\Services\QuestionService;
24
+use App\Services\SmsService;
25
+use App\Services\TopService;
26
+use App\Services\UserService;
27
+use Illuminate\Http\Request;
28
+use Illuminate\Support\Facades\Config;
29
+use Illuminate\Support\Facades\Cookie;
30
+use Illuminate\Support\Facades\DB;
31
+use Illuminate\Support\Facades\Log;
32
+use Illuminate\Support\Facades\Redis;
33
+
34
+use Laravel\Lumen\Routing\Controller as BaseController;
35
+
36
+class ApiGuestController extends BaseController
37
+{
38
+
39
+    protected $userId;
40
+    protected $activityId;
41
+    protected $oauth;
42
+    protected $corpId;
43
+    protected $user;
44
+    protected $browser;
45
+
46
+    public function __construct(Request $request)
47
+    {
48
+        $this->oauth = CookieService::getOauth();
49
+
50
+        try {
51
+            $this->activityId = $request->get("activity_id");
52
+            //判断是否已经登录
53
+            $userData = CookieService::getBsAuthUser();
54
+            if ($userData) {
55
+                $user = UserService::getInstance()->getUser($userData["user_id"]);
56
+                if ($user) {
57
+                    if ($this->activityId == $userData["activity_id"]) {
58
+                        if (AccessToken::getInstance()->getAccessToken($user["user_id"]) != CookieService::getBsAccessToken()) {
59
+                            CookieService::unsetBsAuth();
60
+                        }
61
+                    }
62
+                }
63
+            }
64
+            $activity = BrainstormingService::getInstance()->get($this->activityId);
65
+            if (empty($activity)) {
66
+                Log::info("api not found activity {$this->activityId}");
67
+                die(json_encode(["error" => 302, "message" => config("errormsg.not_found_activity"), "redirect" => env("NOT_FOUND_URL")]));
68
+            }
69
+
70
+            $openId = $request->cookie("oauth_open_id");
71
+            if (empty($openId)) {
72
+                Log::info(config("errormsg.not_oauth"));
73
+                die(json_encode(["error" => 302, "message" => config("errormsg.not_oauth"), "redirect" => env("WEB_URL") . "/frontend?activity_id=" . $this->activityId]));
74
+            }
75
+
76
+
77
+            $browser = AppClient::browserType();
78
+
79
+            $this->browser = $browser;
80
+
81
+            switch ($activity["client_type"]) {
82
+
83
+                case "wechat":
84
+                    if ($browser != AppClient::BROWSER_TYPE_WECHAT) {
85
+                        ErrorMessageService::forward("请在微信客户端打开链接!");
86
+                        die;
87
+                    }
88
+                    break;
89
+                case "wesuit":
90
+                    if ($browser != AppClient::BROWSER_TYPE_WESUITAPP) {
91
+                        ErrorMessageService::forward("请在企业微信客户端打开链接!");
92
+                        die;
93
+                    }
94
+                    break;
95
+                case "cmb_mobile_oa":
96
+                    /* if ($browser != AppClient::BROWSER_TYPE_CMB_MOBILE_OA) {
97
+                         ErrorMessageService::forward("请在招行移事通打开链接!");
98
+                         die;
99
+                     }*/
100
+                    break;
101
+                case "pingan":
102
+
103
+                    break;
104
+                case "pingan_zhiniao":
105
+                    if ($browser != AppClient::BROWSER_TYPE_PINGAN_ZHINIAO) {
106
+                        $url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.pingan.xueyuan";
107
+                        die(json_encode(["error" => 302, "message" => "", "redirect" => $url]));
108
+                    }
109
+                    break;
110
+                case "yunzhijia":
111
+                    if ($browser != AppClient::BROWSER_TYPE_YUNZHIJIA || !AppClient::isMobile()) {
112
+                        ErrorMessageService::forward("请在云之家移动端打开链接!");
113
+                    }
114
+                    break;
115
+                case "dingtalk":
116
+                    if ($browser != AppClient::BROWSER_TYPE_DINGTALK || !AppClient::isMobile()) {
117
+                        ErrorMessageService::forward("请在钉钉移动端打开链接!");
118
+                    }
119
+                    break;
120
+                case "kara":
121
+                   /* if ($browser != AppClient::BROWSER_TYPE_KARA || !AppClient::isMobile()) {
122
+                        ErrorMessageService::forward("请在信部落移动端打开链接!");
123
+                    }*/
124
+                    break;
125
+               /* default:
126
+                    if (!AppClient::isWxBrowser()) {
127
+                        ErrorMessageService::forward("请在企业微信或微信客户端打开链接!");
128
+                        die;
129
+                    }
130
+                    break;*/
131
+            }
132
+
133
+            $userData = CookieService::getBsAuthUser();
134
+            if ($userData) {
135
+                Log::info($userData);
136
+                $user = UserService::getInstance()->getUser($userData["user_id"]);
137
+                if ($user) {
138
+                    if ($this->activityId == $userData["activity_id"]) {
139
+                        $this->userId = $userData["user_id"];
140
+                        $this->user = $user;
141
+                        $this->corpId = $user["corp_id"];
142
+                    } else {
143
+                        CookieService::unsetBsAuth();
144
+                    }
145
+                }
146
+            } else {
147
+                //用openId身份去登录
148
+                $openId = $this->oauth["oauth_open_id"];
149
+                $avatar = $this->oauth["oauth_avatar"];
150
+                $nickname = $this->oauth["oauth_nickname"];
151
+                $platform = $this->oauth["oauth_platform"];
152
+                $guid = $this->oauth["oauth_guid"];
153
+                $department = $this->oauth["oauth_department"];
154
+                $gCorpId = $this->oauth["oauth_gcorp_id"];
155
+
156
+                if (!empty($this->oauth["oauth_open_id"])) {
157
+                    Log::info("oauth_open_id:" . $openId);
158
+                    //校验活动进行方式  wechat 纯微信(导入人员名单)  agh_import 微信+企业微信(导人员入名单)  agh 微信+企业微信(不导入人员名单) agh_corps 多企业使用
159
+
160
+                    //根据认证方式去处理是否需要新增人员或者单位信息。
161
+                    switch ($activity['auth_type']) {
162
+                        case "wechat_auto_add":
163
+                            UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
164
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
165
+                            break;
166
+                        case "cmb_mobile_oa_add":
167
+                            UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
168
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
169
+                            break;
170
+                        case "cmb_mobile_oa":
171
+                            $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
172
+                            break;
173
+                        case "yunzhijia_add":
174
+                            UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
175
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
176
+                            break;
177
+                        case "yunzhijia":
178
+                            $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
179
+                            break;
180
+                        case "dingtalk_add":
181
+                            UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
182
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
183
+                            break;
184
+                        case "dingtalk":
185
+                            $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
186
+                            break;
187
+                        case "kara_sbu_add":
188
+                            UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform,$department);
189
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
190
+                            break;
191
+                        case "kara_add":
192
+                            UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
193
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
194
+                            break;
195
+                        case "kara":
196
+                            $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
197
+                            break;
198
+                        case "pingan_zhiniao_add":
199
+                            UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
200
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
201
+                            break;
202
+                        case "pingan_zhiniao":
203
+                            $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
204
+                            break;
205
+                        case "agh":
206
+                            $ret = UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId);
207
+                            if($ret["error"]>0){
208
+                                CookieService::unsetOauth();
209
+                                ErrorMessageService::forward("抱歉,你不在(".$ret["corp_short_name"].")活动名单中");
210
+                            }
211
+                            $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
212
+                            break;
213
+                        case "agh_corps":
214
+                            UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId, true);
215
+                            $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
216
+                            break;
217
+                        default:
218
+                            $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
219
+                            break;
220
+                    }
221
+
222
+                    //如果认证为纯微信认证
223
+                    if ($activity['auth_type'] == "agh") {
224
+                        //若$user为空,则清除原有cookie信息,重新设置cookie
225
+                        if (empty($user)) {
226
+                            if (CookieService::getLoginTrialNum() < 3) {
227
+                                //清除Oauth的cookie
228
+                                CookieService::unsetOauth();
229
+                                CookieService::incrLoginTrialNum();
230
+                                $this->oauth["oauth_open_id"] = null;
231
+                            } else {
232
+                                CookieService::unsetLoginTrialNum();
233
+                                ErrorMessageService::forward("登录认证失败!");
234
+                            }
235
+                        }
236
+                    }
237
+
238
+                    if ($user) {
239
+                        $this->user = $user;
240
+                        $accessToken = AccessToken::getInstance()->create($user);
241
+                        //生成认证后的登录cookie
242
+                        CookieService::setBsAuth($user, $accessToken);
243
+                        Log::info($user);
244
+                    }
245
+                }
246
+
247
+                $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
248
+                if ($user) {
249
+                    $this->user = $user;
250
+                    $accessToken = AccessToken::getInstance()->create($user);
251
+                    CookieService::setBsAuth($user, $accessToken);
252
+                }
253
+            }
254
+        } catch (\Exception $exception) {
255
+            Log::info("api not found activity {$this->activityId} exception:" . $exception->getMessage());
256
+            Log::info($exception->getTraceAsString());
257
+            die(json_encode(["error" => 302, "message" => config("errormsg.not_found_activity"), "redirect" => env("NOT_FOUND_URL")]));
258
+        }
259
+    }
260
+
261
+    /**
262
+     * 获取活动基本信息
263
+     * @param Request $request
264
+     * @return \Illuminate\Http\JsonResponse
265
+     */
266
+    public function baseInfo(Request $request)
267
+    {
268
+        $data = BrainstormingService::getInstance()->get($this->activityId);
269
+        if ($data) {
270
+            $time = time();
271
+            $data["is_activity_start"] = 0;
272
+            $data["is_activity_end"] = 0;
273
+            $data["is_job_time"] = 0;
274
+            if ($data["start_time"] < $time || $data["start_time"] == 0) {
275
+                $data["is_activity_start"] = 1;
276
+            }
277
+            if ($data["end_time"] < $time) {
278
+                $data["is_activity_end"] = 1;
279
+            }
280
+            $data["limit_time"] = "";
281
+            if ($data["is_jobtime_limit"] == 1) {
282
+                $isWeekendLimit = true;
283
+                if(isset($data["is_weekend_limit"])){
284
+                    $isWeekendLimit = $data["is_weekend_limit"]? true:false;
285
+                }
286
+                $w = date("w");
287
+                if (($w > 0 && $w < 6)||$isWeekendLimit) {
288
+                    $jobTimes = json_decode($data["jobtimes"], true);
289
+                    if (is_array($jobTimes)) {
290
+                        foreach ($jobTimes as $jobTime) {
291
+                            $startTime = strtotime($jobTime["start_time"]);
292
+                            $endTime = strtotime($jobTime["end_time"]);
293
+                            if ($time >= $startTime && $time <= $endTime) {
294
+                                $data["is_job_time"] = 1;
295
+                            }
296
+                            $data["limit_time"] .= " " . $jobTime["start_time"] . "-" . $jobTime["end_time"];
297
+                        }
298
+                    }
299
+                }
300
+            }
301
+
302
+            $data["level_star_config"] = json_decode($data["level_star_config"],true);
303
+
304
+            $name = empty($this->user) ? "" : $this->user["name"];
305
+            $data["share_home_title"] = $this->ubb($data["share_home_title"], $data, $name);
306
+            $data["share_home_desc"] = $this->ubb($data["share_home_desc"], $data, $name);
307
+            $data["share_pk_title"] = $this->ubb($data["share_pk_title"], $data, $name);
308
+            $data["share_pk_desc"] = $this->ubb($data["share_pk_desc"], $data, $name);
309
+
310
+            $data["app_name"] = env("APP_NAME");
311
+            $data["app_support"] = env("APP_SUPPORT");
312
+
313
+
314
+            switch ($data["client_type"]){
315
+                case "yunzhijia":
316
+                    $authExtend = json_decode($data["auth_extend"],true);
317
+                    $data["yzj_app_id"] = $authExtend["yzj_app_id"];
318
+                    break;
319
+                case "cmb_mobile_oa":
320
+                    $authExtend = json_decode($data["auth_extend"],true);
321
+                    $data["cmb_app_code"] = $authExtend["cmb_app_code"];
322
+                    break;
323
+            }
324
+
325
+            $data["activity_time"] = date("Y年m月d日 H:i", $data["start_time"]) . "至" . date("Y年m月d日 H:i", $data["end_time"]);
326
+
327
+
328
+            $ws = substr(env("WEB_URL"),0,5)=="https"? "wss":"ws";
329
+            $data["ws_server"] = $ws."://" . $_SERVER["HTTP_HOST"] . "/brainstorming/ws?userdata=".urlencode(Cookie::get("bs_access_user_data"))."&bs_access_token=".urlencode(Cookie::get("bs_access_token"));
330
+
331
+            unset($data["is_jobtime_limit"]);
332
+            unset($data["is_complete_set"]);
333
+            unset($data["key"]);
334
+            unset($data["app_id"]);
335
+            unset($data["status"]);
336
+            unset($data["auth_extend"]);
337
+            $data["sponsor_corp"] = explode("/",$data["sponsor_corp"]);
338
+
339
+            return response()->json([
340
+                "error" => 0,
341
+                "data" => $data
342
+            ]);
343
+        }
344
+
345
+    }
346
+
347
+    /**
348
+     * 获得用户信息
349
+     * @param Request $request
350
+     * @return \Illuminate\Http\JsonResponse
351
+     */
352
+    public function userInfo(Request $request)
353
+    {
354
+        $userId = intval($request->get("user_id"));
355
+        $userId = $userId > 0 ? $userId : $this->userId;
356
+        if ($userId > 0) {
357
+            $user = UserService::getInstance()->getUser($userId);
358
+            if ($user) {
359
+                //判断用户是否可用
360
+                if ($user["status"] == 1) {
361
+                    $data = [
362
+                        "user_id" => $userId,
363
+                        "name" => $user["name"],
364
+                        "headpic_url" => $user["avatar"],
365
+                        "nickname" => $user["nickname"],
366
+                        "short_name" => mb_substr($user["name"], -2, 2, "utf-8"),
367
+                        "department_id" => $user["department_id"],
368
+                        "department_name" => DepartmentService::getInstance()->getDepartmentName($user["department_id"]),
369
+                        "knowledge_money" => $user["knowledge_money"],
370
+                        "is_blockade_success" => $user["is_blockade_success"],
371
+                        "platform" => $user["platform"],
372
+                        "is_white_list" => $user["is_white_list"],
373
+                        "is_over_online" => false,
374
+                        "online_limit_count" => 0
375
+                    ];
376
+
377
+                    if (OnlineLimitService::getInstance()->isOverOnline($this->activityId)) {
378
+                        $data["is_over_online"] = true;
379
+
380
+                    }
381
+                    $data["online_limit_count"] = OnlineLimitService::getInstance()->onlineLimitCount($this->activityId);
382
+
383
+                    TopService::getInstance()->updateUserTop($userId);
384
+
385
+                    return response()->json([
386
+                        "error" => 0,
387
+                        "data" => $data
388
+                    ]);
389
+                }
390
+
391
+            }
392
+        }
393
+
394
+        $data = [
395
+            "user_id" => 0,
396
+            "headpic_url" => $this->oauth["oauth_avatar"],
397
+            "nickname" => $this->oauth["oauth_nickname"],
398
+            "is_not_in_list" => 0,
399
+            "platform" => $this->oauth["oauth_platform"]
400
+        ];
401
+
402
+        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
403
+        if ($brainstorming["client_type"] != "wechat") {
404
+            $data["is_not_in_list"] = 1;
405
+            $data["message"] = "抱歉,你不在本次活动名单中!";
406
+        }
407
+
408
+        return response()->json([
409
+            "error" => 0,
410
+            "data" => $data
411
+        ]);
412
+    }
413
+
414
+    public function otherActivitys()
415
+    {
416
+        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
417
+        if ($brainstorming) {
418
+            $activitys = DB::table("agh_activitys")->where("app_id", 1)
419
+                ->where("corp_id", $brainstorming["corp_id"])
420
+                ->where("status", 1)->get();
421
+            $data = [];
422
+            $time = time();
423
+            foreach ($activitys as $activity) {
424
+                $bs = BrainstormingService::getInstance()->get($activity->activity_id);
425
+                $isActivityStart = 0;
426
+                $sActivityEnd = 0;
427
+                if ($bs["start_time"] < $time || $bs["start_time"] == 0) {
428
+                    $isActivityStart = 1;
429
+                }
430
+                if ($bs["end_time"] < $time) {
431
+                    $sActivityEnd = 1;
432
+                }
433
+                $topBanner = isset($bs["top_banner"]) ? $bs["top_banner"] : "";
434
+                $sponsorCorp = isset($bs["sponsor_corp"]) ? $bs["sponsor_corp"] : "";
435
+                $data[] = [
436
+                    "activity_id" => $bs["activity_id"],
437
+                    "title" => $bs["title"],
438
+                    "top_banner" => $topBanner,
439
+                    "sponsor_corp" => $sponsorCorp,
440
+                    "is_activity_start" => $isActivityStart,
441
+                    "is_activity_end" => $sActivityEnd,
442
+                    "activtiy_tims" => date("Y年m月d日 H:i", $bs["start_time"]) . "至" . date("Y年m月d日 H:i", $bs["end_time"])
443
+                ];
444
+            }
445
+
446
+            return response()->json([
447
+                "error" => 0,
448
+                "data" => $data
449
+            ]);
450
+        } else {
451
+            return response()->json([
452
+                "error" => 404,
453
+                "message" => "找不到活动信息"
454
+            ]);
455
+        }
456
+    }
457
+
458
+    /**
459
+     * 获取题库分类
460
+     */
461
+    public function getClass(Request $request){
462
+        $activity_id = $this -> activityId;
463
+        try {
464
+            $class_direct = QuestionService::getInstance() ->getClassDirect($activity_id);
465
+            $class_not_direct = QuestionService::getInstance() ->getClassNotDirect($activity_id);
466
+            if ($class_direct || $class_not_direct){
467
+                $direct = array();
468
+                $not_direct = array();
469
+                $tmp_direct = array();
470
+                $tmp_not_direct = array();
471
+                foreach ($class_direct as $key => $c) {
472
+                    $tmp = json_decode($c,256);
473
+                    array_push($direct,$tmp);
474
+                    $tmp_direct[$key] = $tmp["category_id"];
475
+                }
476
+                array_multisort($tmp_direct,SORT_ASC ,SORT_REGULAR ,$direct);
477
+                foreach ($class_not_direct as $key => $c) {
478
+                    $tmp = json_decode($c,256);
479
+                    array_push($not_direct,$tmp);
480
+                    $tmp_not_direct[$key] = $tmp["category_id"];
481
+                }
482
+                array_multisort($tmp_not_direct,SORT_ASC ,SORT_REGULAR ,$not_direct);
483
+                return response()->json([
484
+                    "error" => 0,
485
+                    "direct" => $direct,
486
+                    "not_direct" => $not_direct
487
+                ]);
488
+            }return response()->json([
489
+                "error" => 1000,
490
+                "message" => "暂无题库!"
491
+            ]);
492
+        }catch (\Exception $exception) {
493
+            Log::info($exception->getTraceAsString());
494
+            return response()->json([
495
+                "error" => 500,
496
+                "message" => "服务器内部错误"
497
+            ]);
498
+        }
499
+    }
500
+
501
+    /**
502
+     * 获取PK房间信息
503
+     */
504
+    public function room(Request $request)
505
+    {
506
+        $roomId = intval($request->get("room_id"));
507
+        if ($roomId > 0) {
508
+            try {
509
+                $room = PkService::getInstance()->getRoomInfo($roomId);
510
+                if ($room) {
511
+                    if ($this->userId > 0) {
512
+                        Redis::sadd("bs_pk_room_joins:" . $roomId, $this->userId);
513
+                    }
514
+                    $pkUserInfo = PkService::getInstance()->getPkUserInfo($room["sponsor_user_id"], $room["challenger_user_id"]);
515
+                    $data = [
516
+                        "room_id" => $roomId,
517
+                        "knowledge_money" => $room["knowledge_money"],
518
+                        "sponsor_score" => $room["sponsor_score"],
519
+                        "challenger_score" => $room["challenger_score"],
520
+                        "win_user_id" => $room["win_user_id"],
521
+                        "status" => $room["status"],
522
+                        "create_time" => $room["create_time"]
523
+                    ];
524
+                    $data = array_merge($data, $pkUserInfo);
525
+
526
+                    return response()->json([
527
+                        "error" => 0,
528
+                        "data" => $data
529
+                    ]);
530
+                } else {
531
+                    return response()->json([
532
+                        "error" => 17000,
533
+                        "message" => "PK已经结束"
534
+                    ]);
535
+                }
536
+            } catch (\Exception $exception) {
537
+                Log::info("get Room Info {$roomId} exception:" . $exception->getMessage());
538
+                Log::info($exception->getTraceAsString());
539
+                return response()->json([
540
+                    "error" => 500,
541
+                    "message" => "服务器内部错误"
542
+                ]);
543
+            }
544
+        } else {
545
+            return response()->json([
546
+                "error" => 404,
547
+                "message" => "PK房间不存在"
548
+            ]);
549
+        }
550
+    }
551
+
552
+    /**
553
+     * @param Request $request
554
+     * @return \Illuminate\Http\JsonResponse
555
+     * @throws \Exception
556
+     */
557
+    public function sendsms(Request $request)
558
+    {
559
+        try {
560
+            $phone = $request->json("phone");
561
+            $user = User::where("activity_id", $this->activityId)->where("phone", $phone)->where("status", 1)->first();
562
+            if ($user) {
563
+                if (empty($user->open_id)) {
564
+
565
+                    \Aliyun\Core\Config::load();
566
+                    $verifyCode = random_int(100000, 999999);
567
+                    $ret = SmsService::sendSms($phone, $verifyCode);
568
+                    //Log::info($ret);
569
+                    Log::info(CookieService::getOauth());
570
+                    Log::info($phone);
571
+
572
+                    //todo send sms
573
+                    Redis::set("bs_sms_verify_code:" . $phone, $verifyCode);
574
+                    Redis::expire("bs_sms_verify_code:" . $phone, 900);
575
+
576
+                    return response()->json([
577
+                        "name" => $user['name'],
578
+                        "error" => 0,
579
+                        "message" => "OK"
580
+                    ]);
581
+                } else {
582
+                    return response()->json([
583
+                        "error" => 1000,
584
+                        "message" => "工号:{$phone}已经被绑定!"
585
+                    ]);
586
+                }
587
+            } else {
588
+                return response()->json([
589
+                    "error" => 1000,
590
+                    "message" => "工号:{$phone}不在此次活动名单内!"
591
+                ]);
592
+            }
593
+        } catch (\Exception $exception) {
594
+            Log::info("Send sms exception:" . $exception->getMessage());
595
+            Log::info("Trace message:" . $exception->getTraceAsString());
596
+            return response()->json([
597
+                "error" => 500,
598
+                "message" => config("errMsg.server_error")
599
+            ]);
600
+        }
601
+
602
+    }
603
+
604
+    public function userbind(Request $request)
605
+    {
606
+
607
+        $phone = $request->json("phone");
608
+        $openId = $request->cookie("oauth_open_id");
609
+
610
+//        $verifycode = $request->json("verifycode");
611
+        $user = User::where("activity_id", $this->activityId)->where("phone", $phone)->where("status", 1)->first();
612
+        if ($user) {
613
+            if (empty($user->open_id)) {
614
+                        $user->open_id = $openId;
615
+                        $user->save();
616
+
617
+                        //添加到agh_wechats
618
+                        DB::select("replace into agh_wechats set open_id='{$openId}',phone='{$phone}'");
619
+
620
+                        return response()->json([
621
+                            "error" => 0,
622
+                            "message" => "OK"
623
+                        ]);
624
+
625
+            } else {
626
+                return response()->json([
627
+                    "error" => 1000,
628
+                    "message" => "工号:{$phone}已经被绑定!"
629
+                ]);
630
+            }
631
+        } else {
632
+            return response()->json([
633
+                "error" => 1000,
634
+                "message" => "工号:{$phone}不在此次活动名单内!"
635
+            ]);
636
+        }
637
+
638
+    }
639
+
640
+    protected function ubb($str, $brainstorming, $name)
641
+    {
642
+        $str = str_replace("[活动标题]", $brainstorming["title"], $str);
643
+        $str = str_replace("[姓名]", $name, $str);
644
+        return $str;
645
+    }
646
+}

+ 330 - 0
app/Http/Controllers/ApiTopController.php Прегледај датотеку

@@ -0,0 +1,330 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/31
6
+ * Time: 15:56
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Models\User;
12
+use App\Services\BrainstormingService;
13
+use App\Services\CmbcService;
14
+use App\Services\DepartmentService;
15
+use App\Services\TopService;
16
+use App\Services\UserService;
17
+use Illuminate\Support\Facades\Log;
18
+use Illuminate\Support\Facades\Redis;
19
+
20
+class ApiTopController extends Controller
21
+{
22
+    public function joinRate()
23
+    {
24
+        try{
25
+            $myDepartmentId = $this->user["department_id"];
26
+
27
+            $data = TopService::getInstance()->departmentJoinRateTop($this->activityId);
28
+            $myRateRank = TopService::getInstance()->departmentJoinRateRank($this->activityId,$myDepartmentId);
29
+            $myAvgRank = TopService::getInstance()->departmentKmAvgRank($this->activityId,$myDepartmentId);
30
+            $joinCounts = TopService::getInstance()->departmentJoinTop($this->activityId);
31
+            $top = [];
32
+            foreach ($data as $key => $value) {
33
+                $joinCount = isset($joinCounts[$key]) ? $joinCounts[$key] : 0;
34
+                $top[] = [
35
+                    "department_id" => $key,
36
+                    "department_name" => DepartmentService::getInstance()->getDepartmentName($key),
37
+                    "join_count" => $joinCount,
38
+                    "join_rate" => $this->roundRate($value)
39
+                ];
40
+            }
41
+
42
+            if(count($top)>1){
43
+                foreach ($top as $value){
44
+                    $arrJoinRate[] = $value["join_rate"];
45
+                    $arrJoinCount[] = $value["join_count"];
46
+                }
47
+                array_multisort($arrJoinRate,SORT_DESC,$arrJoinCount,SORT_DESC,$top);
48
+            }
49
+
50
+            $joinCount = isset($joinCounts[$myDepartmentId]) ? $joinCounts[$myDepartmentId] : 0;
51
+            $my = [
52
+                "index_rate" => $myRateRank["index"],
53
+                "index_avg" => $myAvgRank["index"],
54
+                "department_id" => $myDepartmentId,
55
+                "department_name" => DepartmentService::getInstance()->getDepartmentName($myDepartmentId),
56
+                "join_count" => $joinCount,
57
+                "join_rate" => $this->roundRate($myRateRank["rate"]),
58
+                "avg_knowledge_money" => round($myAvgRank["avg_knowledge_money"], 1)
59
+            ];
60
+
61
+            return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my]]);
62
+        }catch (\Exception $exception){
63
+            Log::info("joinRate:exception ".$exception->getMessage());
64
+            return response()->json(["error"=>config("errorcode.server_error"),"message"=>config("errmsg.")]);
65
+        }
66
+
67
+    }
68
+
69
+    public function departmentKmAvg()
70
+    {
71
+        $myDepartmentId = $this->user["department_id"];
72
+        $data = TopService::getInstance()->departmentKmAvgTop($this->activityId);
73
+        $myRateRank = TopService::getInstance()->departmentJoinRateRank($this->activityId,$myDepartmentId);
74
+        $myAvgRank = TopService::getInstance()->departmentKmAvgRank($this->activityId,$myDepartmentId);
75
+        $joinCounts = TopService::getInstance()->departmentJoinTop($this->activityId);
76
+        $top = [];
77
+        foreach ($data as $key => $value) {
78
+            $joinCount = isset($joinCounts[$key]) ? $joinCounts[$key] : 0;
79
+            $top[] = [
80
+                "department_id" => $key,
81
+                "department_name" => DepartmentService::getInstance()->getDepartmentName($key),
82
+                "join_count" => $joinCount,
83
+                "avg_knowledge_money" => round($value, 1)
84
+            ];
85
+        }
86
+
87
+        if(count($top)>1){
88
+            foreach ($top as $value){
89
+                $arrAvgKm[] = $value["avg_knowledge_money"];
90
+                $arrJoinCount[] = $value["join_count"];
91
+            }
92
+            array_multisort($arrAvgKm,SORT_DESC,$arrJoinCount,SORT_DESC,$top);
93
+        }
94
+
95
+        $joinCount = isset($joinCounts[$myDepartmentId]) ? $joinCounts[$myDepartmentId] : 0;
96
+        $my = [
97
+            "index_rate" => $myRateRank["index"],
98
+            "index_avg" => $myAvgRank["index"],
99
+            "department_id" => $myDepartmentId,
100
+            "department_name" => DepartmentService::getInstance()->getDepartmentName($myDepartmentId),
101
+            "join_count" => $joinCount,
102
+            "join_rate" => $this->roundRate($myRateRank["rate"]),
103
+            "avg_knowledge_money" => round($myAvgRank["avg_knowledge_money"], 1)
104
+        ];
105
+
106
+        return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my]]);
107
+    }
108
+
109
+    public function personKm()
110
+    {
111
+
112
+        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
113
+        $data = TopService::getInstance()->personKmTop($this->activityId,100);
114
+        $myRank = TopService::getInstance()->personKmRank($this->activityId,$this->userId);
115
+        $top = [];
116
+        foreach ($data as $key => $value) {
117
+            $top[] = [
118
+                "user_id" => $key,
119
+                "name" => self::getName($brainstorming,$value["name"]),
120
+                "headpic_url" => $value["avatar"],
121
+                "department_id" => $value["department_id"],
122
+                "department_name" => DepartmentService::getInstance()->getDepartmentName($value["department_id"]),
123
+                "knowledge_money" => $value["knowledge_money"]
124
+            ];
125
+        }
126
+        $my = [
127
+            "index" => $myRank,
128
+            "user_id" => $this->user["user_id"],
129
+            "name" => $this->user["name"],
130
+            "headpic_url" => $this->user["avatar"],
131
+            "department_id" => $this->user["department_id"],
132
+            "department_name" => $this->user["department_name"],
133
+            "knowledge_money" => $this->user["knowledge_money"]
134
+        ];
135
+
136
+        $requirementIndex = isset($brainstorming["top_prize_num"])? intval($brainstorming["top_prize_num"]):1000;
137
+
138
+        $prizeKnowledgeMoney = TopService::getInstance()->prizeKmRank($this->activityId,$requirementIndex);
139
+        $prizeRequirement = [
140
+            "index" => $requirementIndex,
141
+            "knowledge_money" => $prizeKnowledgeMoney
142
+        ];
143
+
144
+        return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my,"prize_requirement" => $prizeRequirement]]);
145
+    }
146
+
147
+    public function personDepartmentKm()
148
+    {
149
+        $brainstorming = BrainstormingService::getInstance()->get($this->activityId);
150
+        $myDepartmentId = $this->user["department_id"];
151
+        $data = TopService::getInstance()->personKmDepartmentTop($this->activityId,$myDepartmentId, 100);
152
+        $myRank = TopService::getInstance()->personKmDepartmentRank($this->activityId,$this->userId, $myDepartmentId);
153
+        $departmentName = DepartmentService::getInstance()->getDepartmentName($myDepartmentId);
154
+        $top = [];
155
+        foreach ($data as $key => $value) {
156
+            $top[] = [
157
+                "user_id" => $key,
158
+                "name" => self::getName($brainstorming,$value["name"]),
159
+                "headpic_url" => $value["avatar"],
160
+                "department_id" => $value["department_id"],
161
+                "department_name" => $departmentName,
162
+                "knowledge_money" => $value["knowledge_money"]
163
+            ];
164
+        }
165
+        $my = [
166
+            "index" => $myRank,
167
+            "user_id" => $this->user["user_id"],
168
+            "name" => $this->user["name"],
169
+            "headpic_url" => $this->user["avatar"],
170
+            "department_id" => $this->user["department_id"],
171
+            "department_name" => $this->user["department_name"],
172
+            "knowledge_money" => $this->user["knowledge_money"]
173
+        ];
174
+
175
+        return response()->json(["error" => 0, "data" => ["top" => $top, "my" => $my]]);
176
+    }
177
+
178
+    /**
179
+     * 炫耀
180
+     * @return \Illuminate\Http\JsonResponse
181
+     */
182
+    public function mark()
183
+    {
184
+        $myDepartmentId = $this->user["department_id"];
185
+        $myRank = TopService::getInstance()->personKmRank($this->activityId,$this->userId);
186
+        $myDepartmentRank = TopService::getInstance()->personKmDepartmentRank($this->activityId,$this->userId, $myDepartmentId);
187
+        $userCount = User::where("activity_id",$this->activityId)
188
+                            ->where("status",1)->count();
189
+        $departmentCount = User::where("activity_id",$this->activityId)
190
+                                ->where("department_id",$myDepartmentId)
191
+                                ->where("status",1)->count();
192
+
193
+        $pkWin = intval($this->user["pk_win_count"]);
194
+        $pkLost = intval($this->user["pk_lost_count"]);
195
+        $pkDraw = intval($this->user["pk_draw_count"]);
196
+        $pkCount = $pkWin + $pkLost + $pkDraw;
197
+        $pkWinRate = 0;
198
+        if ($pkWin > 0 && $pkCount > 0) {
199
+            $pkWinRate = round(($pkWin/$pkCount)*100,2);
200
+        }
201
+        $topWinRate=0;
202
+        $topWinDepartmentRate = 0;
203
+        if($userCount>0){
204
+            $topWinRate = $myRank==1? 100:$this->roundRate((1-$myRank/$userCount)*100);
205
+        }
206
+        if($departmentCount>0){
207
+            $topWinDepartmentRate = $myDepartmentRank==1? 100:$this->roundRate((1-$myDepartmentRank/$departmentCount)*100);
208
+        }
209
+
210
+        $activityInfo = BrainstormingService::getInstance()->get($this->activityId);
211
+        $levelStarConfig = json_decode($activityInfo['level_star_config'], true);
212
+
213
+        $data = [
214
+            "index_all" => $myRank,
215
+            "user_id" => $this->user["user_id"],
216
+            "name" => $this->user["name"],
217
+            "headpic_url" => $this->user["name"],
218
+            "department_id" => $this->user["department_id"],
219
+            "department_name" => DepartmentService::getInstance()->getDepartmentName($myDepartmentId),
220
+            "knowledge_money" => $this->user["knowledge_money"],
221
+            "index_department" => $myDepartmentRank,
222
+            "top_win_rate" => $topWinRate,
223
+            "top_win_department_rate" => $topWinDepartmentRate,
224
+            "pk_count" => $pkCount,
225
+            "pk_win" => $pkWin,
226
+            "pk_lost" => $pkLost,
227
+            "pk_draw" => $pkDraw,
228
+            "pk_win_rate" => $pkWinRate,
229
+            "user_level" => intval($this->user['user_level']),
230
+            "user_star" => intval($this->user['user_star']),
231
+            "win_continuity" => intval($this->user['win_continuity']),
232
+            "user_level_name" => $levelStarConfig[$this->user['user_level']]['name'],
233
+            "level_need_star" => intval($levelStarConfig[$this->user['user_level']]['star']),
234
+            "index" => intval(TopService::getInstance()->personPkRank($this->activityId, $this->userId)),
235
+        ];
236
+        return response()->json(["error" => 0, "data" => $data]);
237
+    }
238
+
239
+    protected function roundRate($rate)
240
+    {
241
+        if(is_int($rate)){
242
+            return $rate;
243
+        }else{
244
+            if ($rate > 10) {
245
+                return substr(sprintf("%.3f",$rate),0,-1);
246
+            } else {
247
+                return substr(sprintf("%.2f",$rate),0,-1);
248
+            }
249
+        }
250
+
251
+    }
252
+
253
+    /**
254
+     * @param $activity
255
+     * @param $name
256
+     * @return string
257
+     */
258
+    function getName($activity,$name){
259
+        if($activity["client_type"]=="yunzhijia"){
260
+            return self::hidestr($name,1,1,1);
261
+        }else{
262
+            return $name;
263
+        }
264
+
265
+    }
266
+
267
+    /**
268
+    +----------------------------------------------------------
269
+     * 将一个字符串部分字符用*替代隐藏
270
+    +----------------------------------------------------------
271
+     * @param string    $string   待转换的字符串
272
+     * @param int       $bengin   起始位置,从0开始计数,当$type=4时,表示左侧保留长度
273
+     * @param int       $len      需要转换成*的字符个数,当$type=4时,表示右侧保留长度
274
+     * @param int       $type     转换类型:0,从左向右隐藏;1,从右向左隐藏;2,从指定字符位置分割前由右向左隐藏;3,从指定字符位置分割后由左向右隐藏;4,保留首末指定字符串
275
+     * @param string    $glue     分割符
276
+    +----------------------------------------------------------
277
+     * @return string   处理后的字符串
278
+    +----------------------------------------------------------
279
+     */
280
+    function hideStr($string, $bengin=0, $len = 4, $type = 0, $glue = "@") {
281
+        if (empty($string))
282
+            return false;
283
+        $array = array();
284
+        if ($type == 0 || $type == 1 || $type == 4) {
285
+            $strlen = $length = mb_strlen($string);
286
+            while ($strlen) {
287
+                $array[] = mb_substr($string, 0, 1, "utf8");
288
+                $string = mb_substr($string, 1, $strlen, "utf8");
289
+                $strlen = mb_strlen($string);
290
+            }
291
+        }
292
+        if ($type == 0) {
293
+            for ($i = $bengin; $i < ($bengin + $len); $i++) {
294
+                if (isset($array[$i]))
295
+                    $array[$i] = "*";
296
+            }
297
+            $string = implode("", $array);
298
+        }else if ($type == 1) {
299
+            $array = array_reverse($array);
300
+            for ($i = $bengin; $i < ($bengin + $len); $i++) {
301
+                if (isset($array[$i]))
302
+                    $array[$i] = "*";
303
+            }
304
+            $string = implode("", array_reverse($array));
305
+        }else if ($type == 2) {
306
+            $array = explode($glue, $string);
307
+            $array[0] = self::hideStr($array[0], $bengin, $len, 1);
308
+            $string = implode($glue, $array);
309
+        } else if ($type == 3) {
310
+            $array = explode($glue, $string);
311
+            $array[1] = self::hideStr($array[1], $bengin, $len, 0);
312
+            $string = implode($glue, $array);
313
+        } else if ($type == 4) {
314
+            $left = $bengin;
315
+            $right = $len;
316
+            $tem = array();
317
+            for ($i = 0; $i < ($length - $right); $i++) {
318
+                if (isset($array[$i]))
319
+                    $tem[] = $i >= $left ? "*" : $array[$i];
320
+            }
321
+            $array = array_chunk(array_reverse($array), $right);
322
+            $array = array_reverse($array[0]);
323
+            for ($i = 0; $i < $right; $i++) {
324
+                $tem[] = $array[$i];
325
+            }
326
+            $string = implode("", $tem);
327
+        }
328
+        return $string;
329
+    }
330
+}

+ 75 - 0
app/Http/Controllers/AppController.php Прегледај датотеку

@@ -0,0 +1,75 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/9/7
6
+ * Time: 14:07
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Services\CookieService;
12
+use Illuminate\Http\Request;
13
+use Illuminate\Support\Facades\Log;
14
+use Illuminate\Support\Facades\Redis;
15
+use App\Libs\Curl;
16
+
17
+class AppController
18
+{
19
+    public function index(Request $request){
20
+        Log::info('1232');
21
+        $token = $request->get("token");
22
+        $data = Redis::hGetAll("oauth:".$token);
23
+        if($data){
24
+            CookieService::setOauth($data);
25
+            header("location:http://activity.test.care001.cn/brainstorming?activity_id=709");
26
+        }
27
+    }
28
+
29
+    /**
30
+     * 根据code获取网页授权access_token
31
+     */
32
+    public function getAccessTokenByCode($code) {
33
+        $uri = sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", env("WX_APP_ID"), env("WX_APP_SECRET"), $code);
34
+        Log::info($uri);
35
+        $curl = new Curl($uri);
36
+        $curl->httpHeader('Content-Type', 'application/json');
37
+        $res = $curl -> httpGet();
38
+        $resData = json_decode($res, true);
39
+
40
+        if(isset($resData['access_token'])){
41
+            return $resData;
42
+        }
43
+        return null;
44
+    }
45
+
46
+    /**
47
+     * 根据openid和access_token获取用户信息,前提是scope = snsapi_userinfo
48
+     */
49
+    public function getUserInfo(Request $request) {
50
+        $code = $request -> get("code");
51
+        $activity_id = $request -> get("activity_id");
52
+        $access = $this->getAccessTokenByCode($code);
53
+
54
+        if(empty($access)) {
55
+            return null;
56
+        }
57
+
58
+        $uri = sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", $access['access_token'], $access['openid']);
59
+
60
+        $curl = new Curl($uri);
61
+        $curl->httpHeader('Content-Type', 'application/json');
62
+        $res = $curl -> httpGet();
63
+        $resData = json_decode($res, true);
64
+
65
+        if(isset($resData['openid'])){
66
+            $data["oauth_open_id"] = $resData['openid'];
67
+            $data["oauth_avatar"] = $resData['headimgurl'];
68
+            $data["oauth_nickname"] = $resData['nickname'];
69
+            $data["oauth_platform"] = "wechat";
70
+            $data["oauth_guid"] = $resData['openid'];
71
+            CookieService::setOauth($data);
72
+        }
73
+        header("location:" .  env("WEB_URL") . "?activity_id=$activity_id");
74
+    }
75
+}

+ 15 - 0
app/Http/Controllers/BaseController.php Прегледај датотеку

@@ -0,0 +1,15 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/5/18
6
+ * Time: 11:31
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+
12
+class BaseController
13
+{
14
+
15
+}

+ 41 - 0
app/Http/Controllers/CaseController.php Прегледај датотеку

@@ -0,0 +1,41 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/8/4
6
+ * Time: 10:58
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+use App\Services\CookieService;
11
+use Illuminate\Http\Request;
12
+use Illuminate\Support\Facades\Log;
13
+use Laravel\Lumen\Routing\Controller as BaseController;
14
+
15
+class CaseController extends BaseController{
16
+
17
+
18
+    public function e18Kingdee(Request $request){
19
+
20
+        $getData = $_GET;
21
+        unset($getData["_url_"]);
22
+        //CookieService::unsetBsAuth();
23
+        //CookieService::unsetOauth();
24
+        $url = env("WEB_URL")."?activity_id=1232&".http_build_query($getData);
25
+
26
+        Log::info($url);
27
+        header("location:".$url);
28
+
29
+    }
30
+
31
+    public function e18Essence(Request $request){
32
+        $getData = $_GET;
33
+        unset($getData["_url_"]);
34
+        CookieService::unsetBsAuth();
35
+        CookieService::unsetOauth();
36
+        $url = env("WEB_URL")."?activity_id=1559&".http_build_query($getData);
37
+
38
+        Log::info($url);
39
+        header("location:".$url);
40
+    }
41
+}

+ 72 - 0
app/Http/Controllers/Console/CacheController.php Прегледај датотеку

@@ -0,0 +1,72 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/5/14
6
+ * Time: 16:04
7
+ */
8
+
9
+namespace App\Http\Controllers\Console;
10
+use App\Models\Config;
11
+use App\Services\BrainstormingService;
12
+use App\Services\QuestionService;
13
+use Illuminate\Http\Request;
14
+use Illuminate\Support\Facades\Log;
15
+use Laravel\Lumen\Routing\Controller as BaseController;
16
+
17
+class CacheController extends BaseController
18
+{
19
+    public function question(Request $request){
20
+        $activityId = intval($request->get("activity_id"));
21
+        if($activityId>0){
22
+
23
+            try{
24
+                QuestionService::getInstance()->cache($activityId);
25
+                Log::info("更新题库成功!");
26
+                return response()->json([
27
+                    "error" => "0",
28
+                    "message" => "OK"
29
+                ]);
30
+            }catch (\Exception $exception){
31
+                Log::info("cache question:activity=".$activityId." Exception:".$exception->getTrace());
32
+                return response()->json([
33
+                    "error" => "500",
34
+                    "message" => "服务器内部错误!"
35
+                ]);
36
+            }
37
+        }else{
38
+            Log::info("无activityId,参数不正确!");
39
+            return response()->json([
40
+                "error" => "1",
41
+                "message" => "无activityId,参数不正确!"
42
+            ]);
43
+        }
44
+    }
45
+
46
+    public function config(Request $request){
47
+
48
+        $activityId = intval($request->get("activity_id"));
49
+        if($activityId>0){
50
+            try{
51
+                BrainstormingService::getInstance()->cache($activityId);
52
+                Log::info("更新配置成功!");
53
+                return response()->json([
54
+                    "error" => "0",
55
+                    "message" => "OK"
56
+                ]);
57
+            }catch(\Exception $exception){
58
+                Log::info("cahce config:activity=".$activityId." Exception:".$exception->getMessage());
59
+                return response()->json([
60
+                    "error" => "500",
61
+                    "message" => "服务器内部错误!".$exception->getTraceAsString()
62
+                ]);
63
+            }
64
+        }else{
65
+            Log::info("无activityId,参数不正确!");
66
+            return response()->json([
67
+                "error" => "1",
68
+                "message" => "无activityId,参数不正确!"
69
+            ]);
70
+        }
71
+    }
72
+}

+ 153 - 0
app/Http/Controllers/Console/PkProcessController.php Прегледај датотеку

@@ -0,0 +1,153 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/25
6
+ * Time: 15:30
7
+ */
8
+
9
+namespace App\Http\Controllers\Console;
10
+use App\Services\BrainstormingService;
11
+use App\Services\TopService;
12
+use App\Services\UserService;
13
+use Laravel\Lumen\Routing\Controller as BaseController;
14
+
15
+use Illuminate\Http\Request;
16
+use App\Models\PkRoom;
17
+use App\Models\User;
18
+use Illuminate\Support\Facades\Redis;
19
+
20
+class PkProcessController extends BaseController
21
+{
22
+
23
+    /**
24
+     * PK结果处理接口
25
+     * @param Request $request
26
+     * @return \Illuminate\Http\JsonResponse
27
+     */
28
+    public function getResultProcess(Request $request){
29
+        $params = $request->all();
30
+
31
+        if(empty($params['room_id'])){
32
+            return response()->json([
33
+                "error" => 1,
34
+                "message" => "无房间号码,无法获取PK结果"
35
+            ]);
36
+        }
37
+
38
+        $roomId = $params['room_id'];
39
+
40
+        //获取PK房间信息
41
+        $roomInfo = PkRoom::where('room_id', $roomId)->where('status', 0)->first();
42
+
43
+        if(!$roomInfo || empty($roomInfo)){
44
+            return response()->json([
45
+                "error" => 1,
46
+                "message" => "无法获取PK结果"
47
+            ]);
48
+        }
49
+
50
+        if($roomInfo['is_dispose'] == 1){
51
+            return response()->json([
52
+                "error" => 1,
53
+                "message" => "结果已处理,请勿重复操作"
54
+            ]);
55
+        }
56
+
57
+        $sponsorUserId    = $roomInfo['sponsor_user_id'];
58
+        $challengerUserId = $roomInfo['challenger_user_id'];
59
+        $sponsorUserInfo    = UserService::getInstance()->getUser($sponsorUserId);
60
+        $challengerUserInfo = UserService::getInstance()->getUser($challengerUserId);
61
+        $activityInfo       = BrainstormingService::getInstance()->get($roomInfo['activity_id']);
62
+        $levelStarConfig    = json_decode($activityInfo['level_star_config'], true);
63
+
64
+        $data = [];
65
+        $data['sponsor_user_level_ago']         = intval($sponsorUserInfo['user_level']);
66
+        $data['sponsor_user_star_ago']          = intval($sponsorUserInfo['user_star']);
67
+        $data['sponsor_user_level_name_ago']    = $levelStarConfig[$sponsorUserInfo['user_level']]['name'];
68
+        $data['challenger_user_level_ago']         = intval($challengerUserInfo['user_level']);
69
+        $data['challenger_user_star_ago']          = intval($challengerUserInfo['user_star']);
70
+        $data['challenger_user_level_name_ago']    = $levelStarConfig[$challengerUserInfo['user_level']]['name'];
71
+        if($roomInfo['win_user_id'] == 0) {                                                                             //平局
72
+            $data['sponsor_user_level_now']         = intval($sponsorUserInfo['user_level']);
73
+            $data['sponsor_user_star_now']          = intval($sponsorUserInfo['user_star']);
74
+            $data['sponsor_user_level_name_now']    = $levelStarConfig[$sponsorUserInfo['user_level']]['name'];
75
+
76
+            $data['challenger_user_level_now']         = intval($challengerUserInfo['user_level']);
77
+            $data['challenger_user_star_now']          = intval($challengerUserInfo['user_star']);
78
+            $data['challenger_user_level_name_now']    = $levelStarConfig[$challengerUserInfo['user_level']]['name'];
79
+
80
+            $data['sponsor_level_need_star']           = intval($levelStarConfig[$sponsorUserInfo['user_level']]['star']);
81
+            $data['challenger_level_need_star']        = intval($levelStarConfig[$challengerUserInfo['user_level']]['star']);
82
+
83
+            User::where('user_id', $sponsorUserId)->update(['win_continuity'=>0]);
84
+            User::where('user_id', $challengerUserId)->update(['win_continuity'=>0]);
85
+
86
+            $data['sponsor_win_continuity']     = 0;
87
+            $data['challenger_win_continuity']  = 0;
88
+        } else {                                                                                                        //有胜负
89
+            $winUserId      = $roomInfo['win_user_id'];
90
+            $failUserId     = $roomInfo['win_user_id'] == $roomInfo['sponsor_user_id'] ? $roomInfo['challenger_user_id'] : $roomInfo['sponsor_user_id'];
91
+            $winUserInfo    = $roomInfo['win_user_id'] == $roomInfo['sponsor_user_id'] ? $sponsorUserInfo : $challengerUserInfo;
92
+            $failUserInfo   = $roomInfo['win_user_id'] == $roomInfo['sponsor_user_id'] ? $challengerUserInfo : $sponsorUserInfo;
93
+
94
+            $winUserQuery = [];
95
+            if ($winUserInfo['user_star'] >= $levelStarConfig[$winUserInfo['user_level']]['star']) {                    //需要提升PK段位
96
+                //小于最高段位则增加段位,重置星级
97
+                if($winUserInfo['user_level'] < count($levelStarConfig)){
98
+                    $winUserQuery['user_level'] = $winUserInfo['user_level'] + 1;
99
+                    $winUserQuery['user_star']  = 1;
100
+                } else {
101
+                    $winUserQuery['user_star']  = $winUserInfo['user_star'] + 1;
102
+                }
103
+                $winUserQuery['win_continuity'] = $winUserInfo['win_continuity'] + 1;
104
+            } else {                                                                                                    //只需要提升星级
105
+                $winUserQuery['user_star']      = $winUserInfo['user_star'] + 1;
106
+                $winUserQuery['win_continuity'] = $winUserInfo['win_continuity'] + 1;
107
+            }
108
+
109
+            $failUserQuery = [];
110
+            if ($failUserInfo['user_star'] <= 0) {                                                                      //星级为0时,不扣减段位,不扣减星级
111
+                $failUserQuery['user_star'] = 0;
112
+            } else {
113
+                $failUserQuery['user_star'] = $failUserInfo['user_star'] - 1;
114
+            }
115
+            $failUserQuery['win_continuity'] = 0;
116
+
117
+            //修改PK双方的星段
118
+            User::where('user_id', $winUserId)->update($winUserQuery);
119
+            User::where('user_id', $failUserId)->update($failUserQuery);
120
+            Redis::del(UserService::REDIS_USERS.':'.$sponsorUserId);
121
+            Redis::del(UserService::REDIS_USERS.':'.$challengerUserId);
122
+
123
+            $sponsorUserInfo_new    = UserService::getInstance()->getUser($sponsorUserId);
124
+            $challengerUserInfo_new = UserService::getInstance()->getUser($challengerUserId);
125
+            $data['sponsor_user_level_now']         = intval($sponsorUserInfo_new['user_level']);
126
+            $data['sponsor_user_star_now']          = intval($sponsorUserInfo_new['user_star']);
127
+            $data['sponsor_user_level_name_now']    = $levelStarConfig[$sponsorUserInfo_new['user_level']]['name'];
128
+
129
+            $data['challenger_user_level_now']         = intval($challengerUserInfo_new['user_level']);
130
+            $data['challenger_user_star_now']          = intval($challengerUserInfo_new['user_star']);
131
+            $data['challenger_user_level_name_now']    = $levelStarConfig[$challengerUserInfo_new['user_level']]['name'];
132
+
133
+            $data['sponsor_level_need_star']        = intval($levelStarConfig[$sponsorUserInfo_new['user_level']]['star']);
134
+            $data['challenger_level_need_star']     = intval($levelStarConfig[$challengerUserInfo_new['user_level']]['star']);
135
+
136
+            $data['sponsor_win_continuity']     = $sponsorUserInfo_new['win_continuity'];
137
+            $data['challenger_win_continuity']  = $challengerUserInfo_new['win_continuity'];
138
+        }
139
+
140
+        PkRoom::where('room_id', $roomId)->update(['is_dispose'=>1]);
141
+
142
+        //更新redis
143
+        TopService::getInstance()->updateUserTop($challengerUserId);
144
+        TopService::getInstance()->updateUserTop($sponsorUserId);
145
+
146
+        return response()->json([
147
+            'error'=>0,
148
+            'message'=>"OK",
149
+            'data'=>$data
150
+        ]);
151
+    }
152
+}
153
+?>

+ 54 - 0
app/Http/Controllers/Controller.php Прегледај датотеку

@@ -0,0 +1,54 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Services\AccessToken;
6
+use App\Services\CookieService;
7
+use App\Services\UserService;
8
+use Illuminate\Http\Request;
9
+use Illuminate\Support\Facades\Log;
10
+use Laravel\Lumen\Routing\Controller as BaseController;
11
+
12
+class Controller extends BaseController
13
+{
14
+    protected $userId;
15
+    protected $activityId;
16
+    protected $corpId;
17
+    protected $user;
18
+    public function __construct(Request $request)
19
+    {
20
+        try{
21
+            $this->activityId = $request->get("activity_id");
22
+            $userData = CookieService::getBsAuthUser();
23
+            Log::info($userData);
24
+            if ($userData){
25
+                $user = UserService::getInstance()->getUser($userData["user_id"]);
26
+                if($user){
27
+                    if($this->activityId==$userData["activity_id"]){
28
+                        if(AccessToken::getInstance()->getAccessToken($user["user_id"])!=CookieService::getBsAccessToken()){
29
+                            $accessToken = AccessToken::getInstance()->create($user);
30
+                            setcookie("bs_access_token", $accessToken,null,"/",env("COOKIE_DOMAIN"));
31
+                        }
32
+                        $this->userId = $userData["user_id"];
33
+                        $this->user = $user;
34
+                        $this->corpId = $user["corp_id"];
35
+
36
+                    }else{
37
+
38
+                        Log::info("activity_id not correct");
39
+                        die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
40
+                    }
41
+                }else{
42
+                    Log::info("user not found");
43
+                    die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
44
+                }
45
+            }else{
46
+                Log::info("not auth");
47
+                die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
48
+            }
49
+        }catch (\Exception $exception){
50
+            Log::info($exception->getTraceAsString());
51
+            die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
52
+        }
53
+    }
54
+}

+ 160 - 0
app/Http/Controllers/CorpController.php Прегледај датотеку

@@ -0,0 +1,160 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/9/28
6
+ * Time: 11:41
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Models\Corp;
12
+use App\Services\BrainstormingService;
13
+use App\Services\UserService;
14
+use Illuminate\Support\Facades\Cookie;
15
+use Illuminate\Support\Facades\DB;
16
+use Illuminate\Http\Request;
17
+use App\Models\User;
18
+use Illuminate\Support\Facades\Log;
19
+use Illuminate\Support\Facades\Redis;
20
+
21
+class CorpController extends BaseController
22
+{
23
+    /**
24
+     * 企业活动列表
25
+     * @param Request $request
26
+     * @return \Illuminate\Http\JsonResponse
27
+     */
28
+    public function activityList(Request $request)
29
+    {
30
+
31
+        try{
32
+            $ddCorpId = $request->get("dd_corp_id");
33
+            $corpId = 0;
34
+            if(!empty($ddCorpId)){
35
+                $corp = Corp::where("dd_corp_id",$ddCorpId)->first();
36
+                if($corp){
37
+                    $corpId = $corp->corp_id;
38
+                }
39
+            }else{
40
+                $corpId = $request->get("corp_id");
41
+            }
42
+
43
+            if(empty($corpId)){
44
+                $corpId = empty(Cookie::get("oauth_corp_id"))? 0:Cookie::get("oauth_corp_id");
45
+            }
46
+            $status = $request->get("status","running");
47
+            $redisKey = "bs_corp:".$status.":".$corpId;
48
+            //$redisValue = Redis::get($redisKey);
49
+            $redisValue = "";
50
+            if(empty($redisValue)){
51
+                $curTime = time();
52
+                $where = " and A.corp_id={$corpId} and A.status=1 and is_complete_set=1";
53
+                switch ($status) {
54
+                    case "upcoming":
55
+                        $where .= " and A.start_time>".$curTime;
56
+                        break;
57
+                    case "finish":
58
+                        $where .= " and A.end_time<".$curTime;
59
+                        break;
60
+                    default:
61
+                        $where .= " and (A.start_time<$curTime and A.end_time>$curTime)";
62
+                        break;
63
+                }
64
+                $data = [];
65
+                $activitys = DB::select("select A.activity_id,A.title,B.share_home_desc,A.start_time,A.end_time,B.top_banner from agh_activitys as A,bs_configs as B where A.activity_id=B.activity_id ".$where." limit 0,100");
66
+                foreach ($activitys as $activity){
67
+                    $userCount = User::where("activity_id",$activity->activity_id)->where("status",1)->count();
68
+                    $data[] = [
69
+                        "activity_id" => $activity->activity_id,
70
+                        "title" => $activity->title,
71
+                        "desc" => $activity->share_home_desc,
72
+                        "start_time" => $activity->start_time*1000,
73
+                        "end_time" => $activity->end_time*1000,
74
+                        "top_banner" => $activity->top_banner,
75
+                        "url" => env("WEB_URL")."?activity_id=".$activity->activity_id,
76
+                        "user_count" => $userCount
77
+                    ];
78
+                }
79
+
80
+                Redis::setex($redisKey,300,json_encode($data));
81
+
82
+            }else{
83
+                $data = json_decode($redisValue,true);
84
+            }
85
+            return response()->json([
86
+                "error" => 0,
87
+                "message" => "OK",
88
+                "data" => $data
89
+            ]);
90
+        }catch (\Exception $exception){
91
+            Log::info($exception->getTraceAsString());
92
+            return response()->json([
93
+                "error" => 0,
94
+                "message" => "OK",
95
+                "data" => []
96
+            ]);
97
+        }
98
+    }
99
+
100
+    /**
101
+     * 我加入的活动
102
+     * @param Request $request
103
+     * @return \Illuminate\Http\JsonResponse
104
+     */
105
+    public function joinActivity(Request $request){
106
+        try{
107
+            $openId = $request->get("openid");
108
+            $ddCorpId = $request->get("dd_corp_id");
109
+            $corpId = 0;
110
+            if(!empty($ddCorpId)){
111
+                $corp = Corp::where("dd_corp_id",$ddCorpId)->first();
112
+                if($corp){
113
+                    $corpId = $corp->corp_id;
114
+                }
115
+            }else{
116
+                $corpId = $request->get("corp_id");
117
+            }
118
+            $data = [];
119
+            if($openId){
120
+                $redisKey = "bs_corp:activitys:".$openId;
121
+                //$redisValue = Redis::get($redisKey);
122
+                $redisValue = "";
123
+                if(empty($redisValue)){
124
+                    $where = " and B.open_id='$openId' and A.corp_id='$corpId' and A.status=1";
125
+                    $activitys = DB::select("select A.activity_id,A.title,C.share_home_desc,A.start_time,A.end_time from agh_activitys as A,bs_users as B,bs_configs as C where A.activity_id=C.activity_id and A.activity_id=B.activity_id ".$where." limit 0,100");
126
+                    foreach ($activitys as $activity){
127
+                        $activityRedis = BrainstormingService::getInstance()->get($activity->activity_id);
128
+                        $userCount = User::where("activity_id",$activity->activity_id)->where("status",1)->count();
129
+                        $data[] = [
130
+                            "activity_id" => $activity->activity_id,
131
+                            "title" => $activity->title,
132
+                            "desc" => $activity->share_home_desc,
133
+                            "start_time" => $activity->start_time*1000,
134
+                            "end_time" => $activity->end_time*1000,
135
+                            "top_banner" => $activityRedis["top_banner"],
136
+                            "url" => env("WEB_URL")."?activity_id=".$activity->activity_id,
137
+                            "user_count" => $userCount
138
+                        ];
139
+                    }
140
+
141
+                    Redis::setex($redisKey,300,json_encode($data));
142
+                }else{
143
+                    $data = json_decode($redisValue,true);
144
+                }
145
+            }
146
+            return response()->json([
147
+                "error" => 0,
148
+                "message" => "OK",
149
+                "data" => $data
150
+            ]);
151
+        }catch (\Exception $exception){
152
+            Log::info($exception->getTraceAsString());
153
+            return response()->json([
154
+            "error" => 0,
155
+            "message" => "OK",
156
+                "data" => []
157
+            ]);
158
+        }
159
+    }
160
+}

+ 31 - 0
app/Http/Controllers/DingtalkController.php Прегледај датотеку

@@ -0,0 +1,31 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/9/28
6
+ * Time: 11:41
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Models\Corp;
12
+use App\Services\BrainstormingService;
13
+use App\Services\UserService;
14
+use Illuminate\Support\Facades\Cookie;
15
+use Illuminate\Support\Facades\DB;
16
+use Illuminate\Http\Request;
17
+use App\Models\User;
18
+use Illuminate\Support\Facades\Log;
19
+use Illuminate\Support\Facades\Redis;
20
+
21
+class DingtalkController extends BaseController
22
+{
23
+    /**
24
+     * 钉钉E应用活动入口链接
25
+     * @param Request $request
26
+     */
27
+    public function index(Request $request){
28
+        $url = "dingtalk://dingtalkclient/action/open_mini_app?miniAppId=2018112862350270&page=page%2Factivity%2Fview%2Fview%3Fpageurl%3Dhttps%3A%2F%2Factivity.dingteam.com%2Fbrainstorming%3Factivity_id%3D".$request->get("activity_id")."%26pagetitle%3D%E5%8F%AE%E5%BD%93%E7%AD%94%E9%A2%98%E5%88%9D%E4%BD%93%E9%AA%8C%EF%BC%88%E7%A4%BA%E4%BE%8B%E6%B4%BB%E5%8A%A8%EF%BC%89%26pagedesc%3D%E5%8F%82%E4%B8%8E%E6%B4%BB%E5%8A%A8%E8%B5%A2%E5%8F%96%E4%B8%B0%E5%8E%9A%E5%A5%96%E5%93%81~%26sharepage%3D1";
29
+        header("location:".$url);
30
+    }
31
+}

+ 41 - 0
app/Http/Controllers/ExampleController.php Прегледај датотеку

@@ -0,0 +1,41 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use Aliyun\Core\Config;
6
+use App\Models\Department;
7
+use App\Models\PkRoom;
8
+use App\Models\Question;
9
+use App\Models\User;
10
+use App\Services\BrainstormingService;
11
+use App\Services\AccessToken;
12
+use App\Services\CmbcService;
13
+use App\Services\DepartmentService;
14
+use App\Services\OnlineLimitService;
15
+use App\Services\PkService;
16
+use App\Services\PushMessageService;
17
+use App\Services\RandChinaName;
18
+use App\Services\SmsService;
19
+use App\Services\TopService;
20
+use App\Services\UserService;
21
+use Illuminate\Http\Request;
22
+use Illuminate\Support\Facades\DB;
23
+use Illuminate\Support\Facades\Redis;
24
+use App\Services\GameTimeService;
25
+
26
+class ExampleController extends Controller
27
+{
28
+    /**
29
+     * Create a new controller instance.
30
+     *
31
+     * @return void
32
+     */
33
+    public function __construct()
34
+    {
35
+        //
36
+    } 
37
+
38
+    public function baseIndex(Request $request){
39
+        return json_encode(BrainstormingService::getInstance()->get($request->get("activity_id")));
40
+    }     
41
+}

+ 135 - 0
app/Http/Controllers/PersonDingtalkController.php Прегледај датотеку

@@ -0,0 +1,135 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/9/28
6
+ * Time: 11:41
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Models\Corp;
12
+use App\Services\BrainstormingService;
13
+use App\Services\UserService;
14
+use Illuminate\Support\Facades\Cookie;
15
+use Illuminate\Support\Facades\DB;
16
+use Illuminate\Http\Request;
17
+use App\Models\User;
18
+use Illuminate\Support\Facades\Log;
19
+use Illuminate\Support\Facades\Redis;
20
+
21
+class PersonDingtalkController extends BaseController
22
+{
23
+    /**
24
+     * 活动列表
25
+     * @param Request $request
26
+     * @return \Illuminate\Http\JsonResponse
27
+     */
28
+    public function activityList(Request $request)
29
+    {
30
+        try{
31
+            $status = $request->get("status","running");
32
+            $redisKey = "bs_person_dingtalk:".$status;
33
+            //$redisValue = Redis::get($redisKey);
34
+            $redisValue = "";
35
+            if(empty($redisValue)){
36
+                $curTime = time();
37
+                $where = " and A.status=1 and is_complete_set=1 and activity_type=3";
38
+                switch ($status) {
39
+                    case "upcoming":
40
+                        $where .= " and A.start_time>".$curTime;
41
+                        break;
42
+                    case "finish":
43
+                        $where .= " and A.end_time<".$curTime;
44
+                        break;
45
+                    default:
46
+                        $where .= " and (A.start_time<$curTime and A.end_time>$curTime)";
47
+                        break;
48
+                }
49
+                $data = [];
50
+                $activitys = DB::select("select A.activity_id,A.title,B.share_home_desc,A.start_time,A.end_time,B.top_banner from agh_activitys as A,bs_configs as B where A.activity_id=B.activity_id ".$where." limit 0,100");
51
+                foreach ($activitys as $activity){
52
+                    $userCount = User::where("activity_id",$activity->activity_id)->where("status",1)->count();
53
+                    $data[] = [
54
+                        "activity_id" => $activity->activity_id,
55
+                        "title" => $activity->title,
56
+                        "desc" => $activity->share_home_desc,
57
+                        "start_time" => $activity->start_time*1000,
58
+                        "end_time" => $activity->end_time*1000,
59
+                        "top_banner" => $activity->top_banner,
60
+                        "url" => env("WEB_URL")."?activity_id=".$activity->activity_id,
61
+                        "user_count" => $userCount
62
+                    ];
63
+                }
64
+
65
+                Redis::setex($redisKey,300,json_encode($data));
66
+
67
+            }else{
68
+                $data = json_decode($redisValue,true);
69
+            }
70
+            return response()->json([
71
+                "error" => 0,
72
+                "message" => "OK",
73
+                "data" => $data
74
+            ]);
75
+        }catch (\Exception $exception){
76
+            Log::info($exception->getTraceAsString());
77
+            return response()->json([
78
+                "error" => 0,
79
+                "message" => "OK",
80
+                "data" => []
81
+            ]);
82
+        }
83
+    }
84
+
85
+    /**
86
+     * 我加入的活动
87
+     * @param Request $request
88
+     * @return \Illuminate\Http\JsonResponse
89
+     */
90
+    public function joinActivity(Request $request){
91
+        try{
92
+            $openId = $request->get("openid");
93
+            $data = [];
94
+            if($openId){
95
+                $redisKey = "bs_person_dingtalk:activitys:".$openId;
96
+                //$redisValue = Redis::get($redisKey);
97
+                $redisValue = "";
98
+                if(empty($redisValue)){
99
+                    $where = " and B.open_id='$openId' and A.status=1 and activity_type=3";
100
+                    $activitys = DB::select("select A.activity_id,A.title,C.share_home_desc,A.start_time,A.end_time from agh_activitys as A,bs_users as B,bs_configs as C where A.activity_id=C.activity_id and A.activity_id=B.activity_id ".$where." limit 0,100");
101
+                    foreach ($activitys as $activity){
102
+                        $activityRedis = BrainstormingService::getInstance()->get($activity->activity_id);
103
+                        $userCount = User::where("activity_id",$activity->activity_id)->where("status",1)->count();
104
+                        $data[] = [
105
+                            "activity_id" => $activity->activity_id,
106
+                            "title" => $activity->title,
107
+                            "desc" => $activity->share_home_desc,
108
+                            "start_time" => $activity->start_time*1000,
109
+                            "end_time" => $activity->end_time*1000,
110
+                            "top_banner" => $activityRedis["top_banner"],
111
+                            "url" => env("WEB_URL")."?activity_id=".$activity->activity_id,
112
+                            "user_count" => $userCount
113
+                        ];
114
+                    }
115
+
116
+                    Redis::setex($redisKey,300,json_encode($data));
117
+                }else{
118
+                    $data = json_decode($redisValue,true);
119
+                }
120
+            }
121
+            return response()->json([
122
+                "error" => 0,
123
+                "message" => "OK",
124
+                "data" => $data
125
+            ]);
126
+        }catch (\Exception $exception){
127
+            Log::info($exception->getTraceAsString());
128
+            return response()->json([
129
+            "error" => 0,
130
+            "message" => "OK",
131
+                "data" => []
132
+            ]);
133
+        }
134
+    }
135
+}

+ 292 - 0
app/Http/Controllers/PkApiController.php Прегледај датотеку

@@ -0,0 +1,292 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: hanle
5
+ * Date: 2018/8/16
6
+ * Time: 16:30
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+use App\Models\Department;
11
+use App\Services\BrainstormingService;
12
+use App\Services\DepartmentService;
13
+use App\Services\PkService;
14
+use App\Services\PushMessageService;
15
+use App\Services\TopService;
16
+use App\Services\UserService;
17
+use Laravel\Lumen\Routing\Controller as BaseController;
18
+
19
+use Illuminate\Http\Request;
20
+use App\Models\PkRoom;
21
+use App\Models\User;
22
+use Illuminate\Support\Facades\Redis;
23
+use Illuminate\Support\Facades\DB;
24
+
25
+//class PkApiController extends BaseController
26
+class PkApiController extends Controller
27
+{
28
+    const ONLINE_KEY        = 'bs_online_list:';
29
+    const USER_STATUS_KEY   = 'bs_user_current_work:';
30
+    const PK_READY          = 'bs_pk_ready:';
31
+
32
+//    protected $userId;
33
+//    protected $activityId;
34
+//    protected $user;
35
+//
36
+//    public function __construct()
37
+//    {
38
+//        $this->userId       = 723613;
39
+//        $this->activityId   = 521;
40
+//        $this->user         = UserService::getInstance()->getUser($this->userId);
41
+//    }
42
+
43
+    /**
44
+     * 获取活动在线人员信息及状态
45
+     * @param Request $request
46
+     * @return \Illuminate\Http\JsonResponse
47
+     */
48
+    public function getOnlineUsers(Request $request){
49
+        $params = $request->all();
50
+
51
+        $activityId = $this->activityId;
52
+        $keyword    = empty($params['keyword'])?'':$params['keyword'];
53
+        $user_id    = $this->userId;
54
+        $onlineUsers= Redis::hgetAll(self::ONLINE_KEY.$activityId);                                                    //获取活动在线人员
55
+
56
+        //获取段位配置
57
+        $activityInfo = BrainstormingService::getInstance()->get($activityId);
58
+        $level_start_config = json_decode($activityInfo['level_star_config'], true);
59
+
60
+        if(!empty($onlineUsers)) {
61
+            $userIds = array_keys($onlineUsers);
62
+            $onlineUsersInfo = TopService::getInstance()->getUsers($activityId, $userIds);
63
+
64
+            //数据组装
65
+            $data = [];
66
+            foreach ($onlineUsersInfo as $k => $v) {
67
+                //模糊搜索判断
68
+                if (!empty($keyword)) {
69
+                    $is_search_word = strstr($v['name'], $keyword);
70
+                    if (!$is_search_word) {
71
+                        continue;
72
+                    }
73
+                }
74
+                //如果为null则跳过
75
+                if(empty($v)){
76
+                    continue;
77
+                }
78
+
79
+                //剔除自己并获取自己的排名信息
80
+                if ($user_id == $v['user_id']) {
81
+                    continue;
82
+                }
83
+
84
+                $user = $v;
85
+                $curWork = Redis::hGetAll(self::USER_STATUS_KEY . $v['user_id']);                                                        //获取用户状态 存在则为正忙,不存在则为正闲
86
+
87
+                if ($curWork) {
88
+                    switch ($curWork["channel"]) {
89
+                        case "pk":
90
+                            $user["is_busy"] = 1;
91
+                            $user["busy_message"] = "正在PK";
92
+                            break;
93
+                        case "blockade":
94
+                            $user["is_busy"] = 1;
95
+                            $user["busy_message"] = "正在答题";
96
+                            break;
97
+                    }
98
+                } else {
99
+                    //用户的被邀请状态
100
+                    $invite_status = Redis::get(self::PK_READY . $this->userId . ":" . $v['user_id']);
101
+                    if ($invite_status) {
102
+                        $user['is_invite'] = 1;
103
+                    }
104
+
105
+                    $user["is_busy"] = 0;
106
+                }
107
+
108
+                $user['user_level_name'] = $level_start_config[$v['user_level']]['name'];
109
+                $user['user_name'] = $user['name'];
110
+
111
+                $data[] = $user;
112
+            }
113
+
114
+            //只返回一百条
115
+            $result_status = collect($data)->sortBy('is_busy')->values()->all();
116
+        } else {
117
+            //只返回一百条
118
+            $result_status = [];
119
+        }
120
+
121
+        //获取当前用户的排名
122
+        $user_self['user_level_name']   = isset($level_start_config[$this->user['user_level']]['name']) ? $level_start_config[$this->user['user_level']]['name'] : '无';
123
+        $user_self['level_need_star']   = intval($level_start_config[$this->user['user_level']]['star']);
124
+        $user_self['user_level']        = intval($this->user['user_level']);
125
+        $user_self['user_star']         = intval($this->user['user_star']);
126
+        $user_self['avatar']            = $this->user['avatar'];
127
+        $user_self['name']              = $this->user['name'];
128
+        $user_self['department_name']   = $this->user['department_name'];
129
+        $user_self['index']             = intval(TopService::getInstance()->getPkRank($this->activityId, $this->userId));
130
+
131
+        return response()->json([
132
+            "error"     =>0,
133
+            "message"   =>"OK",
134
+            "data"      =>[
135
+                'online_users'  =>collect($result_status)->take(100),
136
+                'user_self'     =>$user_self
137
+            ]
138
+        ]);
139
+    }
140
+
141
+    /**
142
+     * 获取排行榜信息与当前用户信息
143
+     * @param Request $request
144
+     * @return \Illuminate\Http\JsonResponse
145
+     */
146
+    public function getTop(Request $request){
147
+        $activity_id = $this->activityId;
148
+
149
+        //获取排行信息
150
+        $topUsers = TopService::getInstance()->getPkTop($activity_id);
151
+
152
+        //获取段位配置信息
153
+        $activityInfo = BrainstormingService::getInstance()->get($activity_id);
154
+        $levelStartConfig = json_decode($activityInfo['level_star_config'], true);
155
+
156
+        //获取当前用户的排行等信息
157
+        $userSelfInfoAll = UserService::getInstance()->getUser($this->userId);
158
+        $userSelfInfo['index'] = TopService::getInstance()->getPkRank($activity_id, $this->userId);
159
+        $userSelfInfo['user_level_name'] = isset($levelStartConfig[$userSelfInfoAll['user_level']]['name'])?$levelStartConfig[$userSelfInfoAll['user_level']]['name']:'无';
160
+        $userSelfInfo['level_need_star'] = intval($levelStartConfig[$userSelfInfoAll['user_level']]['star']);
161
+
162
+        //排行榜用户信息组装
163
+        foreach ($topUsers as $k=>$v) {
164
+            $topUsers[$k]['user_level_name'] = isset($levelStartConfig[$v['user_level']]['name'])?$levelStartConfig[$v['user_level']]['name']:'无';
165
+        }
166
+
167
+        return response()->json([
168
+            "error"     =>0,
169
+            "message"   =>"OK",
170
+            "data"      =>[
171
+                'top'=>collect($topUsers)->take(100),
172
+                'user_self'=>$userSelfInfo
173
+            ]
174
+        ]);
175
+    }
176
+
177
+    /**
178
+     * 发起PK
179
+     * @param Request $request
180
+     * @return \Illuminate\Http\JsonResponse
181
+     */
182
+    public function postChallenge(Request $request){
183
+        $params = $request->all();
184
+
185
+        //参数过滤
186
+        if(empty($params['invite_user_id'])){
187
+            return response()->json([
188
+                "error"     =>1,
189
+                "message"   =>"参数不全,无法发起PK"
190
+            ]);
191
+        }
192
+
193
+        $sponsor_user_id  = $this->userId;                   //挑战者ID
194
+        $invite_user_id  = $params['invite_user_id'];       //被挑战者ID
195
+
196
+        Redis::del(self::USER_STATUS_KEY.$sponsor_user_id);                                                              //清除用户状态缓存(默认可操作邀请,则状态为空闲状态)
197
+        $invite_status      = Redis::hGetAll(self::USER_STATUS_KEY.$invite_user_id);
198
+        $sponsor_user_info  = UserService::getInstance()->getUser($sponsor_user_id);
199
+        $invite_user_info   = UserService::getInstance()->getUser($invite_user_id);
200
+
201
+        if($invite_status){
202
+            return response()->json([
203
+                "error"     =>1,
204
+                "message"   =>"对方正忙,无法发起PK"
205
+            ]);
206
+        }
207
+        if($sponsor_user_info['status'] == 0 || $invite_user_info['status'] == 0){
208
+            return response()->json([
209
+                "error"     =>1,
210
+                "message"   =>"用户不存在,无法发起PK"
211
+            ]);
212
+        }
213
+
214
+        $data = [
215
+            'sponsor_user_id'   =>$sponsor_user_id,          //发起挑战者
216
+            'invite_user_id'    =>$invite_user_id,           //被挑战者
217
+            'name'              =>$sponsor_user_info['name']
218
+        ];
219
+        //挑战消息推送
220
+        PushMessageService::getInstance()->pushByUserId('pk','inviteNotify',$data, $invite_user_id);
221
+        //建立被邀请关系
222
+        Redis::setex(self::PK_READY.$sponsor_user_id.":".$invite_user_id, 10, $invite_user_id);
223
+        return response()->json([
224
+            "error"     =>0,
225
+            "message"   =>"OK",
226
+        ]);
227
+    }
228
+
229
+    /**
230
+     * PK响应接口
231
+     * @param Request $request
232
+     * @return \Illuminate\Http\JsonResponse
233
+     */
234
+    public function postPkResponse(Request $request){
235
+        $params = $request->all();
236
+
237
+        //参数过滤
238
+        if(empty($params['sponsor_user_id'])){
239
+            return response()->json([
240
+                "error"     =>1,
241
+                "message"   =>"参数不全,无法接受PK"
242
+            ]);
243
+        }
244
+
245
+        $answer = empty($params['answer'])?0:$params['answer'];
246
+
247
+        if($answer == 1){                    //同意进行PK
248
+            $res = PkService::getInstance()->startPk($this->activityId, $params['sponsor_user_id'], $this->userId);
249
+            if(!empty($res)){
250
+                return response()->json([
251
+                    'error'=>0,
252
+                    'message'=>'OK',
253
+                    "data"=>[
254
+                        'roomId'=>$res
255
+                    ]
256
+                ]);
257
+            } else {
258
+                return response()->json([
259
+                    'error'=>1,
260
+                    'message'=>'PK开启失败'
261
+                ]);
262
+            }
263
+        } elseif($answer == 2) {            //响应超时
264
+            $data = [
265
+                'sponsor_user_id'   =>$params['sponsor_user_id'],          //发起挑战者
266
+                'name'              =>$this->user['name'],
267
+                'message'           =>'对方无应答'
268
+            ];
269
+            //挑战消息推送
270
+            PushMessageService::getInstance()->pushByUserId('pk','timeoutNotify',$data, $params['sponsor_user_id']);
271
+            return response()->json([
272
+                'error'=>1,
273
+                'message'=>'对方无应答,请稍后邀请!!'
274
+            ]);
275
+        } else {                            //拒绝PK
276
+            $sponsor_info = $this->user;
277
+            $data = [
278
+                'sponsor_user_id'   =>$params['sponsor_user_id'],          //发起挑战者
279
+                'name'              =>$sponsor_info['name'],
280
+                'message'           =>'邀请被拒绝'
281
+            ];
282
+            //挑战消息推送
283
+            PushMessageService::getInstance()->pushByUserId('pk','refuseNotify',$data, $params['sponsor_user_id']);
284
+
285
+            return response()->json([
286
+                'error'=>1,
287
+                'message'=>'邀请已拒绝!!'
288
+            ]);
289
+        }
290
+    }
291
+}
292
+?>

+ 295 - 0
app/Http/Controllers/WebController.php Прегледај датотеку

@@ -0,0 +1,295 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/18
6
+ * Time: 23:25
7
+ */
8
+
9
+namespace App\Http\Controllers;
10
+
11
+use App\Libs\AppClient;
12
+use App\Services\AccessToken;
13
+use App\Services\BrainstormingService;
14
+use App\Services\CookieService;
15
+use App\Services\ErrorMessageService;
16
+use App\Services\TopService;
17
+use App\Services\UserService;
18
+use Laravel\Lumen\Routing\Controller as BaseController;
19
+use Illuminate\Http\Request;
20
+use Illuminate\Support\Facades\Log;
21
+
22
+use Illuminate\Support\Facades\Cookie;
23
+
24
+class WebController extends BaseController
25
+{
26
+    protected $user;
27
+    protected $activityId;
28
+    protected $oauth;
29
+
30
+    public function __construct(Request $request)
31
+    {
32
+        Log::info("1");
33
+        $this->activityId = $request->get("activity_id");
34
+        $this->oauth = CookieService::getOauth();
35
+        Log::info($this -> oauth);
36
+        //判断是否已经登录
37
+        $userData = CookieService::getBsAuthUser();
38
+        Log::info($userData);
39
+        if ($userData) {
40
+            $user = UserService::getInstance()->getUser($userData["user_id"]);
41
+            if ($user) {
42
+                if ($this->activityId == $userData["activity_id"]) {
43
+                    if (AccessToken::getInstance()->getAccessToken($user["user_id"]) != CookieService::getBsAccessToken()) {
44
+                       CookieService::unsetBsAuth();
45
+                    }
46
+                }
47
+            }
48
+        }
49
+
50
+        try {
51
+            //获取活动信息
52
+            $activity = BrainstormingService::getInstance()->get($this->activityId);
53
+            if(isset($activity["qy_corp_id"])){
54
+                CookieService::setQyCorpId($activity["qy_corp_id"]);
55
+            }
56
+
57
+            if (empty($activity)) {
58
+                ErrorMessageService::redirect("您要参加的活动不存在!");
59
+                die;
60
+            }
61
+
62
+
63
+            $browser = AppClient::browserType();
64
+            switch ($activity["client_type"]) {
65
+
66
+                case "wechat":
67
+                    if ($browser != AppClient::BROWSER_TYPE_WECHAT) {
68
+                        ErrorMessageService::redirect("请在微信客户端打开链接!");
69
+                        die;
70
+                    }
71
+                    break;
72
+                case "wesuit":
73
+                    if ($browser != AppClient::BROWSER_TYPE_WESUITAPP) {
74
+                        ErrorMessageService::redirect("请在企业微信客户端打开链接!");
75
+                        die;
76
+                    }
77
+                    break;
78
+                case "cmb_mobile_oa":
79
+                    /*if($browser!=AppClient::BROWSER_TYPE_CMB_MOBILE_OA){
80
+                        ErrorMessageService::redirect("请在招行移事通打开链接!");
81
+                        die;
82
+                    }*/
83
+                    break;
84
+                case "pingan":
85
+
86
+                    break;
87
+                case "pingan_zhiniao":
88
+                    if ($browser != AppClient::BROWSER_TYPE_PINGAN_ZHINIAO) {
89
+                        header("location:http://a.app.qq.com/o/simple.jsp?pkgname=com.pingan.xueyuan");
90
+                        die;
91
+                    }
92
+                    break;
93
+                case "yunzhijia":
94
+                    if ($browser != AppClient::BROWSER_TYPE_YUNZHIJIA || !AppClient::isMobile()) {
95
+                        ErrorMessageService::redirect("请在云之家移动端打开链接!");
96
+                    }
97
+                    break;
98
+                case "kara":
99
+                    /*if ($browser != AppClient::BROWSER_TYPE_KARA || !AppClient::isMobile()) {
100
+                        ErrorMessageService::redirect("请在信部落移动端打开链接!");
101
+                    }*/
102
+                    break;
103
+                case "dingtalk":
104
+                    if ($browser != AppClient::BROWSER_TYPE_DINGTALK || !AppClient::isMobile()) {
105
+                        ErrorMessageService::redirect("请在钉钉移动端打开链接!");
106
+                    }
107
+                    break;
108
+                /*default:
109
+                    if (!AppClient::isWxBrowser()) {
110
+                        ErrorMessageService::redirect("请在企业微信或微信客户端打开链接!");
111
+                        die;
112
+                    }
113
+                    break;*/
114
+            }
115
+
116
+            $openId = $this->oauth["oauth_open_id"];
117
+            $avatar = $this->oauth["oauth_avatar"];
118
+            $nickname = $this->oauth["oauth_nickname"];
119
+            $platform = $this->oauth["oauth_platform"];
120
+            $department = $this->oauth["oauth_department"];
121
+            $guid = $this->oauth["oauth_guid"];
122
+            $gCorpId = $this->oauth["oauth_gcorp_id"];
123
+
124
+            $userData = CookieService::getBsAuthUser();
125
+            if ($userData) {
126
+                if ($this->activityId != $userData["activity_id"]) {
127
+                    CookieService::unsetBsAuth();
128
+                }
129
+            }
130
+
131
+            if (!empty($this->oauth["oauth_open_id"])) {
132
+                Log::info("oauth_open_id:" . $openId);
133
+                //校验活动进行方式  wechat 纯微信(导入人员名单)  agh_import 微信+企业微信(导人员入名单)  agh 微信+企业微信(不导入人员名单) agh_corps 多企业使用
134
+
135
+
136
+                //根据认证方式去处理是否需要新增人员或者单位信息。
137
+                switch ($activity['auth_type']) {
138
+                    case "wechat_auto_add":
139
+                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
140
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
141
+                        break;
142
+                    case "cmb_mobile_oa_add":
143
+                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
144
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
145
+                        break;
146
+                    case "cmb_mobile_oa":
147
+                        //UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId);
148
+                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
149
+                        break;
150
+                    case "yunzhijia_add":
151
+                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
152
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
153
+                        break;
154
+                    case "yunzhijia":
155
+                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
156
+                        break;
157
+                    case "dingtalk_add":
158
+                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
159
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
160
+                        break;
161
+                    case "dingtalk":
162
+                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
163
+                        break;
164
+                    case "kara_sbu_add":
165
+                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform,$department);
166
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
167
+                        break;
168
+                    case "kara_add":
169
+                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
170
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
171
+                        break;
172
+                    case "kara":
173
+                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
174
+                        break;
175
+                    case "pingan_zhiniao_add":
176
+                        UserService::getInstance()->addUserByOpenId($this->activityId, $openId, $avatar, $nickname, $platform);
177
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
178
+                        break;
179
+                    case "pingan_zhiniao":
180
+                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
181
+                        break;
182
+                    case "agh":
183
+                        $ret = UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId);
184
+                        if($ret["error"]>0){
185
+                            CookieService::unsetOauth();
186
+                            Log::info($_COOKIE);
187
+                            ErrorMessageService::redirect("抱歉,你不在(".$ret["corp_short_name"].")活动名单中");
188
+                        }
189
+                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
190
+                        break;
191
+                    case "agh_corps":
192
+                        UserService::getInstance()->addUserByGuid($this->activityId, $guid, $gCorpId, true);
193
+                        $user = UserService::getInstance()->authByGuid($this->activityId, $openId, $avatar, $nickname, $platform, $guid);
194
+                        break;
195
+                    default:
196
+                        $user = UserService::getInstance()->auth2($this->activityId, $openId, $avatar, $nickname, $platform);
197
+                        break;
198
+                }
199
+                //如果认证为纯微信认证
200
+                if ($activity['auth_type'] == "agh"||$activity["client_type"]=="yunzhijia") {
201
+                    //若$user为空,则清除原有cookie信息,重新设置cookie
202
+                    if (empty($user)) {
203
+                        if (CookieService::getLoginTrialNum() < 3) {
204
+                            //清除Oauth的cookie
205
+                            CookieService::unsetOauth();
206
+                            CookieService::incrLoginTrialNum();
207
+                            $this->oauth["oauth_open_id"] = null;
208
+                        } else {
209
+                            CookieService::unsetLoginTrialNum();
210
+                            ErrorMessageService::redirect("抱歉,你不在活动名单中!");
211
+                        }
212
+                    }
213
+                }
214
+
215
+                if ($user) {
216
+                    $this->user = $user;
217
+                    $accessToken = AccessToken::getInstance()->create($user);
218
+                    //生成认证后的登录cookie
219
+                    CookieService::setBsAuth($user, $accessToken);
220
+                    Log::info($user);
221
+                }
222
+            }
223
+        } catch (\Exception $exception) {
224
+            Log::info("NOT found activity_id" . $exception->getMessage());
225
+            Log::error($exception->getTraceAsString());
226
+            ErrorMessageService::redirect("您要参加的活动不存在!");
227
+            exit;
228
+        }
229
+    }
230
+
231
+    public function room($id)
232
+    {
233
+        $getData = $_GET;
234
+        unset($getData["_url_"]);
235
+        $redirectUrl = env("WEB_URL") . "/pk/room/{$id}?".http_build_query($getData);
236
+        $frontendRedirectUrl = env("WEB_URL") . "/static/v1/#/beatdown?room_id=" . $id . "&activity_id={$this->activityId}&time=" . time();
237
+        $this->sso($redirectUrl, $frontendRedirectUrl);
238
+    }
239
+
240
+    public function index(Request $request)
241
+    {
242
+        if(!empty($request->get("token"))){
243
+            //return $request->get("token");
244
+        }
245
+
246
+        $getData = $_GET;
247
+        unset($getData["_url_"]);
248
+        $redirectUrl = env("WEB_URL") . "?".http_build_query($getData);
249
+
250
+        $frontendRedirectUrl = env("WEB_URL") . "/static/#/?useOpenApi=1&activity_id={$this->activityId}&time=" . time();
251
+        Log::info($frontendRedirectUrl);
252
+        $this->sso($redirectUrl, $frontendRedirectUrl);
253
+    }
254
+
255
+    public function frontend(Request $request)
256
+    {
257
+        $redirectUrl = env("WEB_URL") . "/frontend?activity_id=" . $this->activityId . "&redirect=" . urlencode($request->get("redirect"));
258
+        $frontendRedirectUrl = $request->get("redirect");
259
+        $this->sso($redirectUrl, $frontendRedirectUrl);
260
+    }
261
+
262
+
263
+
264
+    /**
265
+     * 单点登录,生成cookie信息
266
+     * @param $redirectUrl
267
+     * @param $frontRedirectUrl
268
+     */
269
+    protected function sso($redirectUrl, $frontRedirectUrl)
270
+    {
271
+
272
+        if (empty($this->oauth["oauth_open_id"])) {
273
+            $queryData = $_GET;
274
+            unset($queryData["_url_"]);
275
+            //如果是知鸟APP
276
+            if(AppClient::browserType()==AppClient::BROWSER_TYPE_PINGAN_ZHINIAO){
277
+                $queryData["useOpenApi"] = 1;
278
+            }
279
+            $queryData["action"] = "login";
280
+            $queryData["redirect"] = $redirectUrl;
281
+            $brainstroming = BrainstormingService::getInstance()->get($this->activityId);
282
+            if (isset($brainstroming["gcorp_id"])) {
283
+                $queryData["gcorp_id"] = $brainstroming["gcorp_id"];
284
+            }
285
+
286
+            $url = env("SSO_URL") . "?" . http_build_query($queryData);
287
+            Log::info($url);
288
+            header("location: " . $url);
289
+        } else {
290
+            header("location:" . $frontRedirectUrl);
291
+        }
292
+
293
+    }
294
+
295
+}

+ 44 - 0
app/Http/Middleware/Authenticate.php Прегледај датотеку

@@ -0,0 +1,44 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use Closure;
6
+use Illuminate\Contracts\Auth\Factory as Auth;
7
+
8
+class Authenticate
9
+{
10
+    /**
11
+     * The authentication guard factory instance.
12
+     *
13
+     * @var \Illuminate\Contracts\Auth\Factory
14
+     */
15
+    protected $auth;
16
+
17
+    /**
18
+     * Create a new middleware instance.
19
+     *
20
+     * @param  \Illuminate\Contracts\Auth\Factory  $auth
21
+     * @return void
22
+     */
23
+    public function __construct(Auth $auth)
24
+    {
25
+        $this->auth = $auth;
26
+    }
27
+
28
+    /**
29
+     * Handle an incoming request.
30
+     *
31
+     * @param  \Illuminate\Http\Request  $request
32
+     * @param  \Closure  $next
33
+     * @param  string|null  $guard
34
+     * @return mixed
35
+     */
36
+    public function handle($request, Closure $next, $guard = null)
37
+    {
38
+        if ($this->auth->guard($guard)->guest()) {
39
+            return response('Unauthorized.', 401);
40
+        }
41
+
42
+        return $next($request);
43
+    }
44
+}

+ 21 - 0
app/Http/Middleware/ExampleMiddleware.php Прегледај датотеку

@@ -0,0 +1,21 @@
1
+<?php
2
+
3
+namespace App\Http\Middleware;
4
+
5
+use App\User;
6
+use Closure;
7
+
8
+class ExampleMiddleware
9
+{
10
+    /**
11
+     * Handle an incoming request.
12
+     *
13
+     * @param  \Illuminate\Http\Request  $request
14
+     * @param  \Closure  $next
15
+     * @return mixed
16
+     */
17
+    public function handle($request, Closure $next)
18
+    {
19
+        return $next($request);
20
+    }
21
+}

+ 26 - 0
app/Jobs/ExampleJob.php Прегледај датотеку

@@ -0,0 +1,26 @@
1
+<?php
2
+
3
+namespace App\Jobs;
4
+
5
+class ExampleJob extends Job
6
+{
7
+    /**
8
+     * Create a new job instance.
9
+     *
10
+     * @return void
11
+     */
12
+    public function __construct()
13
+    {
14
+        //
15
+    }
16
+
17
+    /**
18
+     * Execute the job.
19
+     *
20
+     * @return void
21
+     */
22
+    public function handle()
23
+    {
24
+        //
25
+    }
26
+}

+ 24 - 0
app/Jobs/Job.php Прегледај датотеку

@@ -0,0 +1,24 @@
1
+<?php
2
+
3
+namespace App\Jobs;
4
+
5
+use Illuminate\Bus\Queueable;
6
+use Illuminate\Queue\SerializesModels;
7
+use Illuminate\Queue\InteractsWithQueue;
8
+use Illuminate\Contracts\Queue\ShouldQueue;
9
+
10
+abstract class Job implements ShouldQueue
11
+{
12
+    /*
13
+    |--------------------------------------------------------------------------
14
+    | Queueable Jobs
15
+    |--------------------------------------------------------------------------
16
+    |
17
+    | This job base class provides a central location to place any logic that
18
+    | is shared across all of your jobs. The trait included with the class
19
+    | provides access to the "queueOn" and "delay" queue helper methods.
20
+    |
21
+    */
22
+
23
+    use InteractsWithQueue, Queueable, SerializesModels;
24
+}

+ 76 - 0
app/Libs/Aliyun/Api/Sms/Request/V20170525/QueryInterSmsIsoInfoRequest.php Прегледај датотеку

@@ -0,0 +1,76 @@
1
+<?php
2
+/*
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements.  See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership.  The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License.  You may obtain a copy of the License at
10
+ *
11
+ *     http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied.  See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+namespace Aliyun\Api\Sms\Request\V20170525;
21
+
22
+use Aliyun\Core\RpcAcsRequest;
23
+
24
+class QueryInterSmsIsoInfoRequest extends RpcAcsRequest
25
+{
26
+	function  __construct()
27
+	{
28
+		parent::__construct("Dysmsapi", "2017-05-25", "QueryInterSmsIsoInfo");
29
+		$this->setMethod("POST");
30
+	}
31
+
32
+	private  $resourceOwnerAccount;
33
+
34
+	private  $countryName;
35
+
36
+	private  $resourceOwnerId;
37
+
38
+	private  $ownerId;
39
+
40
+	public function getResourceOwnerAccount() {
41
+		return $this->resourceOwnerAccount;
42
+	}
43
+
44
+	public function setResourceOwnerAccount($resourceOwnerAccount) {
45
+		$this->resourceOwnerAccount = $resourceOwnerAccount;
46
+		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
47
+	}
48
+
49
+	public function getCountryName() {
50
+		return $this->countryName;
51
+	}
52
+
53
+	public function setCountryName($countryName) {
54
+		$this->countryName = $countryName;
55
+		$this->queryParameters["CountryName"]=$countryName;
56
+	}
57
+
58
+	public function getResourceOwnerId() {
59
+		return $this->resourceOwnerId;
60
+	}
61
+
62
+	public function setResourceOwnerId($resourceOwnerId) {
63
+		$this->resourceOwnerId = $resourceOwnerId;
64
+		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
65
+	}
66
+
67
+	public function getOwnerId() {
68
+		return $this->ownerId;
69
+	}
70
+
71
+	public function setOwnerId($ownerId) {
72
+		$this->ownerId = $ownerId;
73
+		$this->queryParameters["OwnerId"]=$ownerId;
74
+	}
75
+	
76
+}

+ 103 - 0
app/Libs/Aliyun/Api/Sms/Request/V20170525/QuerySendDetailsRequest.php Прегледај датотеку

@@ -0,0 +1,103 @@
1
+<?php
2
+
3
+namespace Aliyun\Api\Sms\Request\V20170525;
4
+
5
+use Aliyun\Core\RpcAcsRequest;
6
+
7
+class QuerySendDetailsRequest extends RpcAcsRequest
8
+{
9
+	function  __construct()
10
+	{
11
+		parent::__construct("Dysmsapi", "2017-05-25", "QuerySendDetails");
12
+		$this->setMethod("POST");
13
+	}
14
+
15
+	private  $sendDate;
16
+
17
+	private  $pageSize;
18
+
19
+	private  $phoneNumber;
20
+
21
+	private  $resourceOwnerAccount;
22
+
23
+	private  $currentPage;
24
+
25
+	private  $bizId;
26
+
27
+	private  $resourceOwnerId;
28
+
29
+	private  $ownerId;
30
+
31
+	public function getSendDate() {
32
+		return $this->sendDate;
33
+	}
34
+
35
+	public function setSendDate($sendDate) {
36
+		$this->sendDate = $sendDate;
37
+		$this->queryParameters["SendDate"]=$sendDate;
38
+	}
39
+
40
+	public function getPageSize() {
41
+		return $this->pageSize;
42
+	}
43
+
44
+	public function setPageSize($pageSize) {
45
+		$this->pageSize = $pageSize;
46
+		$this->queryParameters["PageSize"]=$pageSize;
47
+	}
48
+
49
+	public function getPhoneNumber() {
50
+		return $this->phoneNumber;
51
+	}
52
+
53
+	public function setPhoneNumber($phoneNumber) {
54
+		$this->phoneNumber = $phoneNumber;
55
+		$this->queryParameters["PhoneNumber"]=$phoneNumber;
56
+	}
57
+
58
+	public function getResourceOwnerAccount() {
59
+		return $this->resourceOwnerAccount;
60
+	}
61
+
62
+	public function setResourceOwnerAccount($resourceOwnerAccount) {
63
+		$this->resourceOwnerAccount = $resourceOwnerAccount;
64
+		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
65
+	}
66
+
67
+	public function getCurrentPage() {
68
+		return $this->currentPage;
69
+	}
70
+
71
+	public function setCurrentPage($currentPage) {
72
+		$this->currentPage = $currentPage;
73
+		$this->queryParameters["CurrentPage"]=$currentPage;
74
+	}
75
+
76
+	public function getBizId() {
77
+		return $this->bizId;
78
+	}
79
+
80
+	public function setBizId($bizId) {
81
+		$this->bizId = $bizId;
82
+		$this->queryParameters["BizId"]=$bizId;
83
+	}
84
+
85
+	public function getResourceOwnerId() {
86
+		return $this->resourceOwnerId;
87
+	}
88
+
89
+	public function setResourceOwnerId($resourceOwnerId) {
90
+		$this->resourceOwnerId = $resourceOwnerId;
91
+		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
92
+	}
93
+
94
+	public function getOwnerId() {
95
+		return $this->ownerId;
96
+	}
97
+
98
+	public function setOwnerId($ownerId) {
99
+		$this->ownerId = $ownerId;
100
+		$this->queryParameters["OwnerId"]=$ownerId;
101
+	}
102
+	
103
+}

+ 121 - 0
app/Libs/Aliyun/Api/Sms/Request/V20170525/SendBatchSmsRequest.php Прегледај датотеку

@@ -0,0 +1,121 @@
1
+<?php
2
+/*
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements.  See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership.  The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License.  You may obtain a copy of the License at
10
+ *
11
+ *     http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied.  See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+
21
+namespace Aliyun\Api\Sms\Request\V20170525;
22
+
23
+use Aliyun\Core\RpcAcsRequest;
24
+
25
+class SendBatchSmsRequest extends RpcAcsRequest
26
+{
27
+	function  __construct()
28
+	{
29
+		parent::__construct("Dysmsapi", "2017-05-25", "SendBatchSms");
30
+		$this->setMethod("POST");
31
+	}
32
+
33
+	private  $templateCode;
34
+
35
+	private  $templateParamJson;
36
+
37
+	private  $resourceOwnerAccount;
38
+
39
+	private  $smsUpExtendCodeJson;
40
+
41
+	private  $resourceOwnerId;
42
+
43
+	private  $signNameJson;
44
+
45
+	private  $ownerId;
46
+
47
+	private  $phoneNumberJson;
48
+
49
+	public function getTemplateCode() {
50
+		return $this->templateCode;
51
+	}
52
+
53
+	public function setTemplateCode($templateCode) {
54
+		$this->templateCode = $templateCode;
55
+		$this->queryParameters["TemplateCode"]=$templateCode;
56
+	}
57
+
58
+	public function getTemplateParamJson() {
59
+		return $this->templateParamJson;
60
+	}
61
+
62
+	public function setTemplateParamJson($templateParamJson) {
63
+		$this->templateParamJson = $templateParamJson;
64
+		$this->queryParameters["TemplateParamJson"]=$templateParamJson;
65
+	}
66
+
67
+	public function getResourceOwnerAccount() {
68
+		return $this->resourceOwnerAccount;
69
+	}
70
+
71
+	public function setResourceOwnerAccount($resourceOwnerAccount) {
72
+		$this->resourceOwnerAccount = $resourceOwnerAccount;
73
+		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
74
+	}
75
+
76
+	public function getSmsUpExtendCodeJson() {
77
+		return $this->smsUpExtendCodeJson;
78
+	}
79
+
80
+	public function setSmsUpExtendCodeJson($smsUpExtendCodeJson) {
81
+		$this->smsUpExtendCodeJson = $smsUpExtendCodeJson;
82
+		$this->queryParameters["SmsUpExtendCodeJson"]=$smsUpExtendCodeJson;
83
+	}
84
+
85
+	public function getResourceOwnerId() {
86
+		return $this->resourceOwnerId;
87
+	}
88
+
89
+	public function setResourceOwnerId($resourceOwnerId) {
90
+		$this->resourceOwnerId = $resourceOwnerId;
91
+		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
92
+	}
93
+
94
+	public function getSignNameJson() {
95
+		return $this->signNameJson;
96
+	}
97
+
98
+	public function setSignNameJson($signNameJson) {
99
+		$this->signNameJson = $signNameJson;
100
+		$this->queryParameters["SignNameJson"]=$signNameJson;
101
+	}
102
+
103
+	public function getOwnerId() {
104
+		return $this->ownerId;
105
+	}
106
+
107
+	public function setOwnerId($ownerId) {
108
+		$this->ownerId = $ownerId;
109
+		$this->queryParameters["OwnerId"]=$ownerId;
110
+	}
111
+
112
+	public function getPhoneNumberJson() {
113
+		return $this->phoneNumberJson;
114
+	}
115
+
116
+	public function setPhoneNumberJson($phoneNumberJson) {
117
+		$this->phoneNumberJson = $phoneNumberJson;
118
+		$this->queryParameters["PhoneNumberJson"]=$phoneNumberJson;
119
+	}
120
+	
121
+}

+ 131 - 0
app/Libs/Aliyun/Api/Sms/Request/V20170525/SendInterSmsRequest.php Прегледај датотеку

@@ -0,0 +1,131 @@
1
+<?php
2
+/*
3
+ * Licensed to the Apache Software Foundation (ASF) under one
4
+ * or more contributor license agreements.  See the NOTICE file
5
+ * distributed with this work for additional information
6
+ * regarding copyright ownership.  The ASF licenses this file
7
+ * to you under the Apache License, Version 2.0 (the
8
+ * "License"); you may not use this file except in compliance
9
+ * with the License.  You may obtain a copy of the License at
10
+ *
11
+ *     http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing,
14
+ * software distributed under the License is distributed on an
15
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16
+ * KIND, either express or implied.  See the License for the
17
+ * specific language governing permissions and limitations
18
+ * under the License.
19
+ */
20
+namespace Aliyun\Api\Sms\Request\V20170525;
21
+
22
+use Aliyun\Core\RpcAcsRequest;
23
+
24
+class SendInterSmsRequest extends RpcAcsRequest
25
+{
26
+	function  __construct()
27
+	{
28
+		parent::__construct("Dysmsapi", "2017-05-25", "SendInterSms");
29
+		$this->setMethod("POST");
30
+	}
31
+
32
+	private  $templateCode;
33
+
34
+	private  $phoneNumbers;
35
+
36
+	private  $countryCode;
37
+
38
+	private  $signName;
39
+
40
+	private  $resourceOwnerAccount;
41
+
42
+	private  $templateParam;
43
+
44
+	private  $resourceOwnerId;
45
+
46
+	private  $ownerId;
47
+
48
+	private  $outId;
49
+
50
+	public function getTemplateCode() {
51
+		return $this->templateCode;
52
+	}
53
+
54
+	public function setTemplateCode($templateCode) {
55
+		$this->templateCode = $templateCode;
56
+		$this->queryParameters["TemplateCode"]=$templateCode;
57
+	}
58
+
59
+	public function getPhoneNumbers() {
60
+		return $this->phoneNumbers;
61
+	}
62
+
63
+	public function setPhoneNumbers($phoneNumbers) {
64
+		$this->phoneNumbers = $phoneNumbers;
65
+		$this->queryParameters["PhoneNumbers"]=$phoneNumbers;
66
+	}
67
+
68
+	public function getCountryCode() {
69
+		return $this->countryCode;
70
+	}
71
+
72
+	public function setCountryCode($countryCode) {
73
+		$this->countryCode = $countryCode;
74
+		$this->queryParameters["CountryCode"]=$countryCode;
75
+	}
76
+
77
+	public function getSignName() {
78
+		return $this->signName;
79
+	}
80
+
81
+	public function setSignName($signName) {
82
+		$this->signName = $signName;
83
+		$this->queryParameters["SignName"]=$signName;
84
+	}
85
+
86
+	public function getResourceOwnerAccount() {
87
+		return $this->resourceOwnerAccount;
88
+	}
89
+
90
+	public function setResourceOwnerAccount($resourceOwnerAccount) {
91
+		$this->resourceOwnerAccount = $resourceOwnerAccount;
92
+		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
93
+	}
94
+
95
+	public function getTemplateParam() {
96
+		return $this->templateParam;
97
+	}
98
+
99
+	public function setTemplateParam($templateParam) {
100
+		$this->templateParam = $templateParam;
101
+		$this->queryParameters["TemplateParam"]=$templateParam;
102
+	}
103
+
104
+	public function getResourceOwnerId() {
105
+		return $this->resourceOwnerId;
106
+	}
107
+
108
+	public function setResourceOwnerId($resourceOwnerId) {
109
+		$this->resourceOwnerId = $resourceOwnerId;
110
+		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
111
+	}
112
+
113
+	public function getOwnerId() {
114
+		return $this->ownerId;
115
+	}
116
+
117
+	public function setOwnerId($ownerId) {
118
+		$this->ownerId = $ownerId;
119
+		$this->queryParameters["OwnerId"]=$ownerId;
120
+	}
121
+
122
+	public function getOutId() {
123
+		return $this->outId;
124
+	}
125
+
126
+	public function setOutId($outId) {
127
+		$this->outId = $outId;
128
+		$this->queryParameters["OutId"]=$outId;
129
+	}
130
+	
131
+}

+ 113 - 0
app/Libs/Aliyun/Api/Sms/Request/V20170525/SendSmsRequest.php Прегледај датотеку

@@ -0,0 +1,113 @@
1
+<?php
2
+
3
+namespace Aliyun\Api\Sms\Request\V20170525;
4
+
5
+use Aliyun\Core\RpcAcsRequest;
6
+
7
+class SendSmsRequest extends RpcAcsRequest
8
+{
9
+	public function  __construct()
10
+	{
11
+		parent::__construct("Dysmsapi", "2017-05-25", "SendSms");
12
+		$this->setMethod("POST");
13
+	}
14
+
15
+	private  $templateCode;
16
+
17
+	private  $phoneNumbers;
18
+
19
+	private  $signName;
20
+
21
+	private  $resourceOwnerAccount;
22
+
23
+	private  $templateParam;
24
+
25
+	private  $resourceOwnerId;
26
+
27
+	private  $ownerId;
28
+
29
+	private  $outId;
30
+
31
+    private  $smsUpExtendCode;
32
+
33
+	public function getTemplateCode() {
34
+		return $this->templateCode;
35
+	}
36
+
37
+	public function setTemplateCode($templateCode) {
38
+		$this->templateCode = $templateCode;
39
+		$this->queryParameters["TemplateCode"]=$templateCode;
40
+	}
41
+
42
+	public function getPhoneNumbers() {
43
+		return $this->phoneNumbers;
44
+	}
45
+
46
+	public function setPhoneNumbers($phoneNumbers) {
47
+		$this->phoneNumbers = $phoneNumbers;
48
+		$this->queryParameters["PhoneNumbers"]=$phoneNumbers;
49
+	}
50
+
51
+	public function getSignName() {
52
+		return $this->signName;
53
+	}
54
+
55
+	public function setSignName($signName) {
56
+		$this->signName = $signName;
57
+		$this->queryParameters["SignName"]=$signName;
58
+	}
59
+
60
+	public function getResourceOwnerAccount() {
61
+		return $this->resourceOwnerAccount;
62
+	}
63
+
64
+	public function setResourceOwnerAccount($resourceOwnerAccount) {
65
+		$this->resourceOwnerAccount = $resourceOwnerAccount;
66
+		$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
67
+	}
68
+
69
+	public function getTemplateParam() {
70
+		return $this->templateParam;
71
+	}
72
+
73
+	public function setTemplateParam($templateParam) {
74
+		$this->templateParam = $templateParam;
75
+		$this->queryParameters["TemplateParam"]=$templateParam;
76
+	}
77
+
78
+	public function getResourceOwnerId() {
79
+		return $this->resourceOwnerId;
80
+	}
81
+
82
+	public function setResourceOwnerId($resourceOwnerId) {
83
+		$this->resourceOwnerId = $resourceOwnerId;
84
+		$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
85
+	}
86
+
87
+	public function getOwnerId() {
88
+		return $this->ownerId;
89
+	}
90
+
91
+	public function setOwnerId($ownerId) {
92
+		$this->ownerId = $ownerId;
93
+		$this->queryParameters["OwnerId"]=$ownerId;
94
+	}
95
+
96
+	public function getOutId() {
97
+		return $this->outId;
98
+	}
99
+
100
+	public function setOutId($outId) {
101
+		$this->outId = $outId;
102
+		$this->queryParameters["OutId"]=$outId;
103
+	}
104
+
105
+    public function getSmsUpExtendCode() {
106
+        return $this->smsUpExtendCode;
107
+    }
108
+
109
+    public function setSmsUpExtendCode($smsUpExtendCode) {
110
+        $this->smsUpExtendCode = $smsUpExtendCode;
111
+        $this->queryParameters["SmsUpExtendCode"]=$smsUpExtendCode;
112
+    }
113
+}

+ 125 - 0
app/Libs/Aliyun/Core/AcsRequest.php Прегледај датотеку

@@ -0,0 +1,125 @@
1
+<?php
2
+
3
+namespace Aliyun\Core;
4
+
5
+abstract class AcsRequest
6
+{
7
+	protected  $version;
8
+	protected  $product;
9
+	protected  $actionName;
10
+	protected  $regionId;
11
+	protected  $acceptFormat;
12
+	protected  $method;
13
+	protected  $protocolType = "http";
14
+	protected  $content;
15
+	
16
+	protected $queryParameters = array();
17
+	protected $headers = array();
18
+	
19
+	function  __construct($product, $version, $actionName)
20
+	{
21
+	    $this->headers["x-sdk-client"] = "php/2.0.0";
22
+	    $this->product = $product;
23
+	    $this->version = $version;
24
+	    $this->actionName = $actionName;
25
+	}
26
+	
27
+	public abstract function composeUrl($iSigner, $credential, $domain);
28
+	
29
+	public function getVersion()
30
+	{
31
+		return $this->version;
32
+	}
33
+	
34
+	public function setVersion($version)
35
+	{
36
+		$this->version = $version;
37
+	}
38
+	
39
+	public function getProduct()
40
+	{
41
+		return $this->product;
42
+	}
43
+	
44
+	public function setProduct($product)
45
+	{
46
+		$this->product = $product;
47
+	}
48
+	
49
+	public function getActionName()
50
+	{
51
+		return $this->actionName;
52
+	}
53
+	
54
+	public function setActionName($actionName)
55
+	{
56
+		$this->actionName = $actionName;
57
+	}
58
+	
59
+	public function getAcceptFormat()
60
+	{
61
+		return	$this->acceptFormat;
62
+	}
63
+	
64
+	public function setAcceptFormat($acceptFormat)
65
+	{
66
+		$this->acceptFormat = $acceptFormat;
67
+	}
68
+	
69
+	public function getQueryParameters()
70
+	{
71
+		return $this->queryParameters;
72
+	}
73
+	
74
+	public function getHeaders()
75
+	{
76
+		return $this->headers;
77
+	}
78
+	
79
+	public function getMethod()
80
+	{
81
+		return $this->method;
82
+	}
83
+	
84
+	public function setMethod($method)
85
+	{
86
+		$this->method = $method;
87
+	}
88
+	
89
+	public function getProtocol()
90
+	{
91
+		return $this->protocolType;
92
+	}
93
+	
94
+	public function setProtocol($protocol)
95
+	{
96
+		$this->protocolType = $protocol;
97
+	}
98
+	
99
+	public function getRegionId()
100
+	{
101
+		return $this->regionId;
102
+	}
103
+	public function setRegionId($region)
104
+	{
105
+		$this->regionId = $region;
106
+	}
107
+	
108
+	public function getContent()
109
+    {
110
+        return $this->content;
111
+    }
112
+
113
+    public function setContent($content)
114
+    {
115
+        $this->content = $content;
116
+    } 
117
+        
118
+        
119
+    public function addHeader($headerKey, $headerValue)
120
+    {
121
+        $this->headers[$headerKey] = $headerValue;
122
+    } 
123
+	
124
+		
125
+}

+ 29 - 0
app/Libs/Aliyun/Core/AcsResponse.php Прегледај датотеку

@@ -0,0 +1,29 @@
1
+<?php
2
+
3
+namespace Aliyun\Core;
4
+
5
+class AcsResponse
6
+{
7
+	private $code;	
8
+	private $message;
9
+	
10
+	public function getCode()
11
+	{
12
+		return $this->code;
13
+	}
14
+	
15
+	public function setCode($code)
16
+	{
17
+		$this->code = $code;
18
+	}
19
+	
20
+	public function getMessage()
21
+	{
22
+		return $this->message;
23
+	}
24
+	
25
+	public function setMessage($message)
26
+	{
27
+		$this->message = $message;
28
+	}
29
+}

+ 72 - 0
app/Libs/Aliyun/Core/Auth/Credential.php Прегледај датотеку

@@ -0,0 +1,72 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Auth;
4
+
5
+class Credential
6
+{
7
+	private  $dateTimeFormat = 'Y-m-d\TH:i:s\Z'; 
8
+	private	 $refreshDate;
9
+	private  $expiredDate;
10
+	private  $accessKeyId;
11
+	private  $accessSecret;
12
+	private  $securityToken;
13
+	
14
+	function  __construct($accessKeyId, $accessSecret)
15
+	{
16
+	    $this->accessKeyId = $accessKeyId;
17
+	    $this->accessSecret = $accessSecret;
18
+	    $this->refreshDate = date($this->dateTimeFormat);
19
+	}
20
+	
21
+	public function isExpired()
22
+	{
23
+		if($this->expiredDate == null)
24
+		{
25
+			return false;
26
+		}
27
+		if(strtotime($this->expiredDate)>date($this->dateTimeFormat))
28
+		{
29
+			return false;
30
+		}
31
+		return true;
32
+	}
33
+	
34
+	public function getRefreshDate()
35
+	{
36
+		return $this->refreshDate;
37
+	}
38
+	
39
+	public function getExpiredDate()
40
+	{
41
+		return $this->expiredDate;
42
+	}
43
+	
44
+	public function setExpiredDate($expiredHours)
45
+	{
46
+		if($expiredHours>0)
47
+		{
48
+			return $this->expiredDate = date($this->dateTimeFormat, strtotime("+".$expiredHours." hour"));
49
+		}
50
+	}
51
+	
52
+	public function getAccessKeyId()
53
+	{
54
+		return $this->accessKeyId;
55
+	}
56
+	
57
+	public function setAccessKeyId($accessKeyId)
58
+	{
59
+		$this->accessKeyId = $accessKeyId;
60
+	}
61
+	
62
+	public function getAccessSecret()
63
+	{
64
+		return $this->accessSecret;
65
+	}
66
+	
67
+	public function setAccessSecret($accessSecret)
68
+	{
69
+		$this->accessSecret = $accessSecret;
70
+	}
71
+
72
+}

+ 12 - 0
app/Libs/Aliyun/Core/Auth/ISigner.php Прегледај датотеку

@@ -0,0 +1,12 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Auth;
4
+
5
+interface ISigner
6
+{
7
+	public function  getSignatureMethod();
8
+	
9
+	public function  getSignatureVersion();
10
+	
11
+	public function signString($source, $accessSecret); 
12
+}

+ 20 - 0
app/Libs/Aliyun/Core/Auth/ShaHmac1Signer.php Прегледај датотеку

@@ -0,0 +1,20 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Auth;
4
+
5
+class ShaHmac1Signer implements ISigner
6
+{
7
+	public function signString($source, $accessSecret)
8
+	{
9
+		return	base64_encode(hash_hmac('sha1', $source, $accessSecret, true));
10
+	}
11
+	
12
+	public function  getSignatureMethod() {
13
+		return "HMAC-SHA1";
14
+	}
15
+
16
+	public function getSignatureVersion() {
17
+		return "1.0";
18
+	}
19
+
20
+}

+ 20 - 0
app/Libs/Aliyun/Core/Auth/ShaHmac256Signer.php Прегледај датотеку

@@ -0,0 +1,20 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Auth;
4
+
5
+class ShaHmac256Signer implements ISigner
6
+{
7
+	public function signString($source, $accessSecret)
8
+	{
9
+		return	base64_encode(hash_hmac('sha256', $source, $accessSecret, true));
10
+	}
11
+	
12
+	public function  getSignatureMethod() {
13
+		return "HMAC-SHA256";
14
+	}
15
+
16
+	public function getSignatureVersion() {
17
+		return "1.0";
18
+	}
19
+
20
+}

+ 23 - 0
app/Libs/Aliyun/Core/Config.php Прегледај датотеку

@@ -0,0 +1,23 @@
1
+<?php
2
+
3
+namespace Aliyun\Core;
4
+
5
+use Aliyun\Core\Regions\EndpointConfig;
6
+
7
+//config http proxy
8
+define('ENABLE_HTTP_PROXY', FALSE);
9
+define('HTTP_PROXY_IP', '127.0.0.1');
10
+define('HTTP_PROXY_PORT', '8888');
11
+
12
+
13
+class Config
14
+{
15
+    private static $loaded = false;
16
+    public static function load(){
17
+        if(self::$loaded) {
18
+            return;
19
+        }
20
+        EndpointConfig::load();
21
+        self::$loaded = true;
22
+    }
23
+}

+ 124 - 0
app/Libs/Aliyun/Core/DefaultAcsClient.php Прегледај датотеку

@@ -0,0 +1,124 @@
1
+<?php
2
+
3
+namespace Aliyun\Core;
4
+use Aliyun\Core\Exception\ClientException;
5
+use Aliyun\Core\Exception\ServerException;
6
+use Aliyun\Core\Regions\EndpointProvider;
7
+use Aliyun\Core\Http\HttpHelper;
8
+
9
+class DefaultAcsClient implements IAcsClient 
10
+{    
11
+    public $iClientProfile;
12
+    public $__urlTestFlag__;
13
+    
14
+    function  __construct($iClientProfile)
15
+    {
16
+        $this->iClientProfile = $iClientProfile;
17
+        $this->__urlTestFlag__ = false;
18
+    }
19
+    
20
+    public function getAcsResponse($request, $iSigner = null, $credential = null, $autoRetry = true, $maxRetryNumber = 3)
21
+    {
22
+        $httpResponse = $this->doActionImpl($request, $iSigner, $credential, $autoRetry, $maxRetryNumber);
23
+        $respObject = $this->parseAcsResponse($httpResponse->getBody(), $request->getAcceptFormat());
24
+        if(false == $httpResponse->isSuccess())
25
+        {
26
+            $this->buildApiException($respObject, $httpResponse->getStatus());
27
+        }
28
+        return $respObject;
29
+    }
30
+
31
+    private function doActionImpl($request, $iSigner = null, $credential = null, $autoRetry = true, $maxRetryNumber = 3)
32
+    {    
33
+        if(null == $this->iClientProfile && (null == $iSigner || null == $credential 
34
+            || null == $request->getRegionId() || null == $request->getAcceptFormat()))
35
+        {
36
+            throw new ClientException("No active profile found.", "SDK.InvalidProfile");
37
+        }
38
+        if(null == $iSigner)
39
+        {
40
+            $iSigner = $this->iClientProfile->getSigner();
41
+        }
42
+        if(null == $credential)
43
+        {
44
+            $credential = $this->iClientProfile->getCredential();
45
+        }
46
+        $request = $this->prepareRequest($request);
47
+        $domain = EndpointProvider::findProductDomain($request->getRegionId(), $request->getProduct());
48
+
49
+        if(null == $domain)
50
+        {
51
+            throw new ClientException("Can not find endpoint to access.", "SDK.InvalidRegionId");
52
+        }
53
+        $requestUrl = $request->composeUrl($iSigner, $credential, $domain);
54
+
55
+        if ($this->__urlTestFlag__) {
56
+            throw new ClientException($requestUrl, "URLTestFlagIsSet");
57
+        }
58
+
59
+        if(count($request->getDomainParameter())>0){
60
+            $httpResponse = HttpHelper::curl($requestUrl, $request->getMethod(), $request->getDomainParameter(), $request->getHeaders());
61
+        } else {
62
+            $httpResponse = HttpHelper::curl($requestUrl, $request->getMethod(), $request->getContent(), $request->getHeaders());
63
+        }
64
+        
65
+        $retryTimes = 1;
66
+        while (500 <= $httpResponse->getStatus() && $autoRetry && $retryTimes < $maxRetryNumber) {
67
+            $requestUrl = $request->composeUrl($iSigner, $credential,$domain);
68
+            
69
+            if(count($request->getDomainParameter())>0){
70
+                $httpResponse = HttpHelper::curl($requestUrl, $request->getMethod(), $request->getDomainParameter(), $request->getHeaders());
71
+            } else {
72
+                $httpResponse = HttpHelper::curl($requestUrl, $request->getMethod(), $request->getContent(), $request->getHeaders());
73
+            }
74
+            $retryTimes ++;
75
+        }
76
+        return $httpResponse;
77
+    }
78
+    
79
+    public function doAction($request, $iSigner = null, $credential = null, $autoRetry = true, $maxRetryNumber = 3)
80
+    {    
81
+        trigger_error("doAction() is deprecated. Please use getAcsResponse() instead.", E_USER_NOTICE);
82
+        return $this->doActionImpl($request, $iSigner, $credential, $autoRetry, $maxRetryNumber);
83
+    }
84
+    
85
+    private function prepareRequest($request)
86
+    {
87
+        if(null == $request->getRegionId())
88
+        {
89
+            $request->setRegionId($this->iClientProfile->getRegionId());
90
+        }
91
+        if(null == $request->getAcceptFormat())
92
+        {
93
+            $request->setAcceptFormat($this->iClientProfile->getFormat());
94
+        }
95
+        if(null == $request->getMethod())
96
+        {
97
+            $request->setMethod("GET");
98
+        }
99
+        return $request;
100
+    }
101
+    
102
+    
103
+    private function buildApiException($respObject, $httpStatus)
104
+    {
105
+        throw new ServerException($respObject->Message, $respObject->Code, $httpStatus, $respObject->RequestId);
106
+    }
107
+    
108
+    private function parseAcsResponse($body, $format)
109
+    {
110
+        if ("JSON" == $format)
111
+        {    
112
+            $respObject = json_decode($body);
113
+        }
114
+        else if("XML" == $format)
115
+        {
116
+            $respObject = @simplexml_load_string($body);
117
+        }
118
+        else if("RAW" == $format)
119
+        {
120
+            $respObject = $body;
121
+        }
122
+        return $respObject;
123
+    }
124
+}

+ 50 - 0
app/Libs/Aliyun/Core/Exception/ClientException.php Прегледај датотеку

@@ -0,0 +1,50 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Exception;
4
+
5
+class ClientException extends \Exception
6
+{
7
+    function  __construct($errorMessage, $errorCode)
8
+    {
9
+        parent::__construct($errorMessage);
10
+        $this->errorMessage = $errorMessage;
11
+        $this->errorCode = $errorCode;
12
+        $this->setErrorType("Client");
13
+    }
14
+    
15
+    private $errorCode;
16
+    private $errorMessage;
17
+    private $errorType;
18
+    
19
+    public function getErrorCode()
20
+    {
21
+        return $this->errorCode;
22
+    }
23
+    
24
+    public function setErrorCode($errorCode)
25
+    {
26
+        $this->errorCode = $errorCode;
27
+    }
28
+    
29
+    public function getErrorMessage()
30
+    {
31
+        return $this->errorMessage;
32
+    }
33
+    
34
+    public function setErrorMessage($errorMessage)
35
+    {
36
+        $this->errorMessage = $errorMessage;
37
+    }
38
+    
39
+    public function getErrorType()
40
+    {
41
+        return $this->errorType;
42
+    }
43
+    
44
+    public function setErrorType($errorType)
45
+    {
46
+        $this->errorType = $errorType;
47
+    }
48
+    
49
+
50
+}

+ 31 - 0
app/Libs/Aliyun/Core/Exception/ServerException.php Прегледај датотеку

@@ -0,0 +1,31 @@
1
+<?php
2
+
3
+
4
+namespace Aliyun\Core\Exception;
5
+
6
+class ServerException extends ClientException
7
+{
8
+    private $httpStatus;
9
+    private $requestId;
10
+
11
+    function  __construct($errorMessage, $errorCode, $httpStatus, $requestId)
12
+    {
13
+        $messageStr = $errorCode . " " . $errorMessage . " HTTP Status: " . $httpStatus . " RequestID: " . $requestId;
14
+        parent::__construct($messageStr, $errorCode);
15
+        $this->setErrorMessage($errorMessage);
16
+        $this->setErrorType("Server");
17
+        $this->httpStatus = $httpStatus;
18
+        $this->requestId = $requestId;
19
+    }
20
+
21
+    public function getHttpStatus()
22
+    {
23
+        return $this->httpStatus;
24
+    }
25
+
26
+    public function getRequestId()
27
+    {
28
+        return $this->requestId;
29
+    }
30
+
31
+}

+ 69 - 0
app/Libs/Aliyun/Core/Http/HttpHelper.php Прегледај датотеку

@@ -0,0 +1,69 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Http;
4
+use Aliyun\Core\Exception\ClientException;
5
+
6
+class HttpHelper
7
+{
8
+	public static $connectTimeout = 30;//30 second
9
+	public static $readTimeout = 80;//80 second
10
+	
11
+	public static function curl($url, $httpMethod = "GET", $postFields = null,$headers = null)
12
+	{
13
+		$ch = curl_init();
14
+		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); 
15
+		if(ENABLE_HTTP_PROXY) {
16
+			curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); 
17
+			curl_setopt($ch, CURLOPT_PROXY, HTTP_PROXY_IP); 
18
+			curl_setopt($ch, CURLOPT_PROXYPORT, HTTP_PROXY_PORT);
19
+			curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); 
20
+		}
21
+		curl_setopt($ch, CURLOPT_URL, $url);
22
+		curl_setopt($ch, CURLOPT_FAILONERROR, false);
23
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
24
+		curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postFields) ? self::getPostHttpBody($postFields) : $postFields);
25
+		
26
+		if (self::$readTimeout) {
27
+			curl_setopt($ch, CURLOPT_TIMEOUT, self::$readTimeout);
28
+		}
29
+		if (self::$connectTimeout) {
30
+			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
31
+		}
32
+		//https request
33
+		if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
34
+			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
35
+			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
36
+		}
37
+		if (is_array($headers) && 0 < count($headers))
38
+		{
39
+			$httpHeaders =self::getHttpHearders($headers);
40
+			curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeaders);
41
+		}
42
+		$httpResponse = new HttpResponse();
43
+		$httpResponse->setBody(curl_exec($ch));
44
+		$httpResponse->setStatus(curl_getinfo($ch, CURLINFO_HTTP_CODE));
45
+		if (curl_errno($ch))
46
+		{
47
+			throw new ClientException("Server unreachable: Errno: " . curl_errno($ch) . " " . curl_error($ch), "SDK.ServerUnreachable");
48
+		}
49
+		curl_close($ch);
50
+		return $httpResponse;
51
+	}
52
+	static function getPostHttpBody($postFildes){		
53
+		$content = "";
54
+		foreach ($postFildes as $apiParamKey => $apiParamValue)
55
+		{			
56
+			$content .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
57
+		}
58
+		return substr($content, 0, -1);
59
+	}
60
+	static function getHttpHearders($headers)
61
+	{
62
+		$httpHeader = array();
63
+		foreach ($headers as $key => $value)
64
+		{
65
+			array_push($httpHeader, $key.":".$value);	
66
+		}
67
+		return $httpHeader;
68
+	}
69
+}

+ 38 - 0
app/Libs/Aliyun/Core/Http/HttpResponse.php Прегледај датотеку

@@ -0,0 +1,38 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Http;
4
+
5
+class HttpResponse
6
+{
7
+	private $body;
8
+	private $status;
9
+	
10
+	public function getBody()
11
+	{
12
+		return $this->body;
13
+	}
14
+	
15
+	public function setBody($body)
16
+	{
17
+		$this->body = $body;
18
+	}
19
+	
20
+	public function getStatus()
21
+	{
22
+		return $this->status;
23
+	}
24
+	
25
+	public function setStatus($status)
26
+	{
27
+		$this->status  = $status;
28
+	}
29
+	
30
+	public function isSuccess()
31
+	{
32
+		if(200 <= $this->status && 300 > $this->status)
33
+		{
34
+			return true;
35
+		}
36
+		return false;
37
+	}
38
+}

+ 7 - 0
app/Libs/Aliyun/Core/IAcsClient.php Прегледај датотеку

@@ -0,0 +1,7 @@
1
+<?php
2
+
3
+namespace Aliyun\Core;
4
+interface IAcsClient
5
+{
6
+	public function doAction($requst);
7
+}

+ 137 - 0
app/Libs/Aliyun/Core/Profile/DefaultProfile.php Прегледај датотеку

@@ -0,0 +1,137 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Profile;
4
+
5
+use Aliyun\Core\Auth\Credential;
6
+use Aliyun\Core\Auth\ShaHmac1Signer;
7
+use Aliyun\Core\Regions\ProductDomain;
8
+use Aliyun\Core\Regions\Endpoint;
9
+use Aliyun\Core\Regions\EndpointProvider;
10
+
11
+class DefaultProfile implements IClientProfile
12
+{
13
+	private static $profile;
14
+	private static $endpoints;
15
+	private static $credential;
16
+	private static $regionId;
17
+	private static $acceptFormat;
18
+	
19
+	private static $isigner;
20
+	private static $iCredential;
21
+	
22
+	private function  __construct($regionId,$credential)
23
+	{
24
+	    self::$regionId = $regionId;
25
+	    self::$credential = $credential;
26
+	}
27
+	
28
+	public static function getProfile($regionId, $accessKeyId, $accessSecret)
29
+	{
30
+		$credential =new Credential($accessKeyId, $accessSecret);
31
+		self::$profile = new DefaultProfile($regionId, $credential);
32
+		return self::$profile;
33
+	}
34
+	
35
+	public function getSigner()
36
+	{
37
+		if(null == self::$isigner)
38
+		{
39
+			self::$isigner = new ShaHmac1Signer(); 
40
+		}
41
+		return self::$isigner;
42
+	}
43
+	
44
+	public function getRegionId()
45
+	{
46
+		return self::$regionId;
47
+	}
48
+	
49
+	public function getFormat()
50
+	{
51
+		return self::$acceptFormat;
52
+	}
53
+	
54
+	public function getCredential()
55
+	{
56
+		if(null == self::$credential && null != self::$iCredential)
57
+		{
58
+			self::$credential = self::$iCredential;
59
+		}
60
+		return self::$credential;
61
+	}
62
+	
63
+	public static function getEndpoints()
64
+	{
65
+		if(null == self::$endpoints)
66
+		{
67
+			self::$endpoints = EndpointProvider::getEndpoints();
68
+		}
69
+		return self::$endpoints;
70
+	}
71
+	
72
+	public static function addEndpoint($endpointName, $regionId, $product, $domain)
73
+	{
74
+		if(null == self::$endpoints)
75
+		{
76
+			self::$endpoints = self::getEndpoints();
77
+		}
78
+		$endpoint = self::findEndpointByName($endpointName);
79
+		if(null == $endpoint)
80
+		{
81
+			self::addEndpoint_($endpointName, $regionId, $product, $domain);
82
+		}
83
+		else 
84
+		{
85
+			self::updateEndpoint($regionId, $product, $domain, $endpoint);
86
+		}
87
+	}
88
+	
89
+	public static function findEndpointByName($endpointName)
90
+	{
91
+		foreach (self::$endpoints as $key => $endpoint)
92
+		{
93
+			if($endpoint->getName() == $endpointName)
94
+			{
95
+				return $endpoint;
96
+			}
97
+		}
98
+	}
99
+	
100
+	private static function addEndpoint_($endpointName,$regionId, $product, $domain)
101
+	{
102
+		$regionIds = array($regionId);
103
+		$productDomains = array(new ProductDomain($product, $domain));
104
+		$endpoint = new Endpoint($endpointName, $regionIds, $productDomains);
105
+		array_push(self::$endpoints, $endpoint);
106
+	}
107
+	
108
+	private static function updateEndpoint($regionId, $product, $domain, $endpoint)
109
+	{
110
+		$regionIds = $endpoint->getRegionIds();
111
+		if(!in_array($regionId,$regionIds))
112
+		{
113
+			array_push($regionIds, $regionId);
114
+			$endpoint->setRegionIds($regionIds);
115
+		}
116
+
117
+		$productDomains = $endpoint->getProductDomains();
118
+		if(null == self::findProductDomain($productDomains, $product, $domain))
119
+		{
120
+		 	array_push($productDomains, new ProductDomain($product, $domain));	
121
+		}
122
+		$endpoint->setProductDomains($productDomains);
123
+	}
124
+	
125
+	private static function findProductDomain($productDomains, $product, $domain)
126
+	{
127
+		foreach ($productDomains as $key => $productDomain)
128
+		{
129
+			if($productDomain->getProductName() == $product && $productDomain->getDomainName() == $domain)
130
+			{
131
+				return $productDomain;
132
+			}
133
+		}
134
+		return null;
135
+	}
136
+
137
+}

+ 14 - 0
app/Libs/Aliyun/Core/Profile/IClientProfile.php Прегледај датотеку

@@ -0,0 +1,14 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Profile;
4
+
5
+interface IClientProfile
6
+{
7
+	public function getSigner();
8
+	
9
+	public function getRegionId();
10
+	
11
+	public function getFormat();
12
+	
13
+	public function getCredential();
14
+}

+ 47 - 0
app/Libs/Aliyun/Core/Regions/Endpoint.php Прегледај датотеку

@@ -0,0 +1,47 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Regions;
4
+
5
+class Endpoint
6
+{
7
+	private $name;
8
+	private $regionIds; 
9
+	private $productDomains;
10
+	
11
+	function  __construct($name, $regionIds, $productDomains)
12
+	{
13
+		$this->name = $name;
14
+		$this->regionIds = $regionIds;
15
+		$this->productDomains = $productDomains;
16
+	}
17
+	
18
+	public function getName()
19
+	{
20
+		return $this->name;
21
+	}
22
+	
23
+	public function setName($name)
24
+	{
25
+		$this->name = $name;
26
+	}
27
+	
28
+	public function getRegionIds()
29
+	{
30
+		return $this->regionIds;
31
+	}
32
+	
33
+	public function setRegionIds($regionIds)
34
+	{
35
+		$this->regionIds = $regionIds;
36
+	}
37
+	
38
+	public function getProductDomains()
39
+	{
40
+		return $this->productDomains;
41
+	}
42
+	
43
+	public function setProductDomains($productDomains)
44
+	{
45
+		$this->productDomains = $productDomains;
46
+	}
47
+}

+ 63 - 0
app/Libs/Aliyun/Core/Regions/EndpointConfig.php Прегледај датотеку

@@ -0,0 +1,63 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Regions;
4
+
5
+class EndpointConfig {
6
+
7
+    private static $loaded = false;
8
+
9
+    public static function load() {
10
+        if(self::$loaded) {
11
+           return;
12
+        }
13
+        $endpoint_filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . "endpoints.xml";
14
+        $xml = simplexml_load_string(file_get_contents($endpoint_filename));
15
+        $json = json_encode($xml);
16
+        $json_array = json_decode($json, TRUE);
17
+
18
+        $endpoints = array();
19
+
20
+
21
+        foreach ($json_array["Endpoint"] as $json_endpoint) {
22
+            # pre-process RegionId & Product
23
+            if (!array_key_exists("RegionId", $json_endpoint["RegionIds"])) {
24
+                $region_ids = array();
25
+            } else {
26
+                $json_region_ids = $json_endpoint['RegionIds']['RegionId'];
27
+                if (!is_array($json_region_ids)) {
28
+                    $region_ids = array($json_region_ids);
29
+                } else {
30
+                    $region_ids = $json_region_ids;
31
+                }
32
+            }
33
+
34
+            if (!array_key_exists("Product", $json_endpoint["Products"])) {
35
+                $products = array();
36
+
37
+            } else {
38
+                $json_products = $json_endpoint["Products"]["Product"];
39
+
40
+                if (array() === $json_products or !is_array($json_products)) {
41
+                    $products = array();
42
+                } else if (array_keys($json_products) !== range(0, count($json_products) - 1)) {
43
+                    # array is not sequential
44
+                    $products = array($json_products);
45
+                } else {
46
+                    $products = $json_products;
47
+                }
48
+            }
49
+
50
+            $product_domains = array();
51
+            foreach ($products as $product) {
52
+                $product_domain = new ProductDomain($product['ProductName'], $product['DomainName']);
53
+                array_push($product_domains, $product_domain);
54
+            }
55
+
56
+            $endpoint = new Endpoint($region_ids[0], $region_ids, $product_domains);
57
+            array_push($endpoints, $endpoint);
58
+        }
59
+
60
+        EndpointProvider::setEndpoints($endpoints);
61
+        self::$loaded = true;
62
+    }
63
+}

+ 53 - 0
app/Libs/Aliyun/Core/Regions/EndpointProvider.php Прегледај датотеку

@@ -0,0 +1,53 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Regions;
4
+
5
+class EndpointProvider
6
+{
7
+	private static $endpoints;
8
+	
9
+	public static function findProductDomain($regionId, $product)
10
+	{
11
+		if(null == $regionId || null == $product || null == self::$endpoints)
12
+		{
13
+			return null;
14
+		}
15
+		
16
+		foreach (self::$endpoints as $key => $endpoint)
17
+		{
18
+			if(in_array($regionId, $endpoint->getRegionIds()))
19
+			{
20
+			 	return self::findProductDomainByProduct($endpoint->getProductDomains(), $product);
21
+			}	
22
+		}
23
+		return null;
24
+	}
25
+	
26
+	private static function findProductDomainByProduct($productDomains, $product)
27
+	{
28
+		if(null == $productDomains)
29
+		{
30
+			return null;
31
+		}
32
+		foreach ($productDomains as $key => $productDomain)
33
+		{
34
+			if($product == $productDomain->getProductName())
35
+			{
36
+				return $productDomain->getDomainName();
37
+			}
38
+		}
39
+		return null;
40
+	}
41
+	
42
+	
43
+	public static function getEndpoints()
44
+	{
45
+		return self::$endpoints;
46
+	}
47
+	
48
+	public static function setEndpoints($endpoints)
49
+	{
50
+		self::$endpoints = $endpoints;
51
+	}
52
+	
53
+}

+ 28 - 0
app/Libs/Aliyun/Core/Regions/ProductDomain.php Прегледај датотеку

@@ -0,0 +1,28 @@
1
+<?php
2
+
3
+namespace Aliyun\Core\Regions;
4
+
5
+class ProductDomain
6
+{
7
+	private $productName;
8
+	private $domainName;
9
+	
10
+	function  __construct($product, $domain) {
11
+		$this->productName = $product;
12
+		$this->domainName = $domain;
13
+	}
14
+	
15
+	public function getProductName() {
16
+		return $this->productName;
17
+	}
18
+	public function setProductName($productName) {
19
+		$this->productName = $productName;
20
+	}
21
+	public function getDomainName() {
22
+		return $this->domainName;
23
+	}
24
+	public function setDomainName($domainName) {
25
+		$this->domainName = $domainName;
26
+	}
27
+
28
+}

Разлика између датотеке није приказан због своје велике величине
+ 1349 - 0
app/Libs/Aliyun/Core/Regions/endpoints.xml


+ 207 - 0
app/Libs/Aliyun/Core/RoaAcsRequest.php Прегледај датотеку

@@ -0,0 +1,207 @@
1
+<?php
2
+
3
+namespace Aliyun\Core;
4
+
5
+abstract class RoaAcsRequest extends AcsRequest
6
+{
7
+	protected $uriPattern;
8
+	private $pathParameters = array();
9
+	private $domainParameters = array();
10
+	private $dateTimeFormat ="D, d M Y H:i:s \G\M\T";
11
+	private static $headerSeparator = "\n";
12
+	private static $querySeprator = "&"; 
13
+	
14
+	function  __construct($product, $version, $actionName)
15
+	{
16
+		parent::__construct($product, $version, $actionName);
17
+		$this->setVersion($version);
18
+		$this->initialize();
19
+	}
20
+	
21
+	private function initialize()
22
+	{
23
+		$this->setMethod("RAW");
24
+	}
25
+	
26
+	public function composeUrl($iSigner, $credential, $domain)
27
+	{
28
+		$this->prepareHeader($iSigner);
29
+
30
+		$signString = $this->getMethod().self::$headerSeparator;
31
+		if(isset($this->headers["Accept"]))
32
+		{
33
+			$signString = $signString.$this->headers["Accept"];
34
+		}
35
+		$signString = $signString.self::$headerSeparator;
36
+		
37
+		if(isset($this->headers["Content-MD5"]))
38
+		{
39
+			$signString = $signString.$this->headers["Content-MD5"];
40
+		}
41
+		$signString = $signString.self::$headerSeparator;
42
+		
43
+		if(isset($this->headers["Content-Type"]))
44
+		{
45
+			$signString = $signString.$this->headers["Content-Type"];
46
+		}
47
+		$signString = $signString.self::$headerSeparator;
48
+		
49
+		if(isset($this->headers["Date"]))
50
+		{
51
+			$signString = $signString.$this->headers["Date"];
52
+		}
53
+		$signString = $signString.self::$headerSeparator;
54
+		
55
+		$uri = $this->replaceOccupiedParameters();
56
+		$signString = $signString.$this->buildCanonicalHeaders();
57
+		$queryString = $this->buildQueryString($uri);
58
+		$signString .= $queryString;
59
+		$this->headers["Authorization"] = "acs ".$credential->getAccessKeyId().":"
60
+				.$iSigner->signString($signString, $credential->getAccessSecret());
61
+		$requestUrl = $this->getProtocol()."://".$domain.$queryString;
62
+		return $requestUrl;
63
+	}
64
+	
65
+	private function prepareHeader($iSigner)
66
+	{
67
+		$this->headers["Date"] = gmdate($this->dateTimeFormat);
68
+		if(null == $this->acceptFormat)
69
+		{
70
+			$this->acceptFormat = "RAW";
71
+		}
72
+		$this->headers["Accept"] = $this->formatToAccept($this->getAcceptFormat());
73
+		$this->headers["x-acs-signature-method"] = $iSigner->getSignatureMethod();
74
+		$this->headers["x-acs-signature-version"] = $iSigner->getSignatureVersion();
75
+		$this->headers["x-acs-region-id"] = $this->regionId;
76
+		$content = $this->getDomainParameter();
77
+        if ($content != null) {
78
+          $this->headers["Content-MD5"] = base64_encode(md5(json_encode($content),true));
79
+        }
80
+		$this->headers["Content-Type"] = "application/octet-stream;charset=utf-8";
81
+	}
82
+	
83
+	private function replaceOccupiedParameters()
84
+	{
85
+		$result = $this->uriPattern;
86
+		foreach ($this->pathParameters as $pathParameterKey => $apiParameterValue)
87
+		{
88
+			$target = "[".$pathParameterKey."]";
89
+			$result = str_replace($target,$apiParameterValue,$result);
90
+		}
91
+		return $result;
92
+	}
93
+	
94
+	private function buildCanonicalHeaders()
95
+	{
96
+		$sortMap = array();
97
+		foreach ($this->headers as $headerKey => $headerValue)
98
+		{
99
+			$key = strtolower($headerKey);
100
+			if(strpos($key, "x-acs-") === 0)
101
+			{
102
+				$sortMap[$key] = $headerValue;
103
+			}
104
+		}
105
+		ksort($sortMap);
106
+		$headerString = "";
107
+		foreach ($sortMap as $sortMapKey => $sortMapValue)
108
+		{
109
+			$headerString = $headerString.$sortMapKey.":".$sortMapValue.self::$headerSeparator;
110
+		}
111
+		return $headerString;
112
+	}
113
+	
114
+	private function splitSubResource($uri)
115
+	{
116
+		$queIndex = strpos($uri, "?");
117
+		$uriParts = array();
118
+		if(null != $queIndex)
119
+		{
120
+			array_push($uriParts, substr($uri,0,$queIndex));
121
+			array_push($uriParts, substr($uri,$queIndex+1));
122
+		}
123
+		else 
124
+		{
125
+			array_push($uriParts,$uri);
126
+		}
127
+		return $uriParts;
128
+	} 
129
+	
130
+	private function buildQueryString($uri)
131
+	{
132
+		$uriParts = $this->splitSubResource($uri);
133
+		$sortMap  = $this->queryParameters;
134
+		if(isset($uriParts[1]))
135
+		{
136
+			$sortMap[$uriParts[1]] = null;
137
+		}
138
+		$queryString = $uriParts[0];
139
+		if(count($uriParts))
140
+		{
141
+			$queryString = $queryString."?";
142
+		}
143
+		ksort($sortMap);
144
+		foreach ($sortMap as $sortMapKey => $sortMapValue)
145
+		{
146
+			$queryString = $queryString.$sortMapKey;
147
+			if(isset($sortMapValue))
148
+			{
149
+				$queryString = $queryString."=".$sortMapValue;
150
+			}
151
+			$queryString = $queryString.$querySeprator;
152
+		}
153
+		if(null==count($sortMap))
154
+		{
155
+			$queryString = substr($queryString, 0, strlen($queryString)-1);
156
+		}
157
+		return $queryString;
158
+	}
159
+	
160
+	private function formatToAccept($acceptFormat)
161
+	{
162
+		if($acceptFormat == "JSON")
163
+		{
164
+			return "application/json";
165
+		}
166
+		elseif ($acceptFormat == "XML") {
167
+			return "application/xml";
168
+		}
169
+		return "application/octet-stream";
170
+	}
171
+	
172
+	public function getPathParameters()
173
+	{
174
+		return $this->pathParameters;
175
+	}
176
+	
177
+	public function putPathParameter($name, $value)
178
+	{
179
+		$this->pathParameters[$name] = $value;
180
+	}
181
+	
182
+	public function getDomainParameter()	
183
+	{
184
+		return $this->domainParameters;
185
+	}
186
+	
187
+	public function putDomainParameters($name, $value)
188
+	{
189
+		$this->domainParameters[$name] = $value;
190
+	}
191
+	
192
+	public function getUriPattern()
193
+	{
194
+		return $this->uriPattern;
195
+	}
196
+	
197
+	public function setUriPattern($uriPattern)
198
+	{
199
+		return $this->uriPattern = $uriPattern;
200
+	}
201
+	
202
+	public function setVersion($version)
203
+	{
204
+		$this->version = $version;
205
+		$this->headers["x-acs-version"] = $version;
206
+	}
207
+}

+ 105 - 0
app/Libs/Aliyun/Core/RpcAcsRequest.php Прегледај датотеку

@@ -0,0 +1,105 @@
1
+<?php
2
+
3
+namespace Aliyun\Core;
4
+
5
+abstract class RpcAcsRequest extends AcsRequest
6
+{
7
+	private $dateTimeFormat = 'Y-m-d\TH:i:s\Z'; 
8
+	private $domainParameters = array();
9
+	
10
+	function  __construct($product, $version, $actionName)
11
+	{
12
+		parent::__construct($product, $version, $actionName);
13
+		$this->initialize();
14
+	}
15
+	
16
+	private function initialize()
17
+	{
18
+		$this->setMethod("GET");	
19
+		$this->setAcceptFormat("JSON");
20
+	}
21
+	
22
+
23
+    private function prepareValue($value)
24
+    {
25
+        if (is_bool($value)) {
26
+            if ($value) {
27
+                return "true";
28
+            } else {
29
+                return "false";
30
+            }
31
+        } else {
32
+            return $value;
33
+        }
34
+    }
35
+
36
+	public function composeUrl($iSigner, $credential, $domain)
37
+	{
38
+		$apiParams = parent::getQueryParameters();
39
+        foreach ($apiParams as $key => $value) {
40
+            $apiParams[$key] = $this->prepareValue($value);
41
+        }
42
+		$apiParams["RegionId"] = $this->getRegionId();
43
+		$apiParams["AccessKeyId"] = $credential->getAccessKeyId();
44
+		$apiParams["Format"] = $this->getAcceptFormat();
45
+		$apiParams["SignatureMethod"] = $iSigner->getSignatureMethod();
46
+		$apiParams["SignatureVersion"] = $iSigner->getSignatureVersion();
47
+		$apiParams["SignatureNonce"] = uniqid(mt_rand(0,0xffff), true);
48
+        $apiParams["Timestamp"] = gmdate($this->dateTimeFormat);
49
+		$apiParams["Action"] = $this->getActionName();
50
+		$apiParams["Version"] = $this->getVersion();
51
+		$apiParams["Signature"] = $this->computeSignature($apiParams, $credential->getAccessSecret(), $iSigner);
52
+		if(parent::getMethod() == "POST") {
53
+			
54
+			$requestUrl = $this->getProtocol()."://". $domain . "/";			
55
+			foreach ($apiParams as $apiParamKey => $apiParamValue)
56
+			{
57
+				$this->putDomainParameters($apiParamKey,$apiParamValue);
58
+			}
59
+			return $requestUrl;			
60
+		}
61
+		else {	
62
+			$requestUrl = $this->getProtocol()."://". $domain . "/?";
63
+
64
+			foreach ($apiParams as $apiParamKey => $apiParamValue)
65
+			{
66
+				$requestUrl .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
67
+			}
68
+			return substr($requestUrl, 0, -1);
69
+		}
70
+	}
71
+	
72
+	private function computeSignature($parameters, $accessKeySecret, $iSigner)
73
+	{
74
+	    ksort($parameters);
75
+	    $canonicalizedQueryString = '';
76
+	    foreach($parameters as $key => $value)
77
+	    {
78
+			$canonicalizedQueryString .= '&' . $this->percentEncode($key). '=' . $this->percentEncode($value);
79
+	    }
80
+	    $stringToSign = parent::getMethod().'&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
81
+	    $signature = $iSigner->signString($stringToSign, $accessKeySecret."&");
82
+
83
+	    return $signature;
84
+	}
85
+	
86
+	protected function percentEncode($str)
87
+	{
88
+	    $res = urlencode($str);
89
+	    $res = preg_replace('/\+/', '%20', $res);
90
+	    $res = preg_replace('/\*/', '%2A', $res);
91
+	    $res = preg_replace('/%7E/', '~', $res);
92
+	    return $res;
93
+	}
94
+	
95
+	public function getDomainParameter()	
96
+	{
97
+		return $this->domainParameters;
98
+	}
99
+	
100
+	public function putDomainParameters($name, $value)
101
+	{
102
+		$this->domainParameters[$name] = $value;
103
+	}
104
+	
105
+}

+ 91 - 0
app/Libs/AppClient.php Прегледај датотеку

@@ -0,0 +1,91 @@
1
+<?php
2
+/**
3
+ * APP 客户端
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/5/24
7
+ * Time: 15:09
8
+ */
9
+
10
+namespace App\Libs;
11
+
12
+
13
+class AppClient
14
+{
15
+    const BROWSER_TYPE_WECHAT = 'wechat';
16
+    const BROWSER_TYPE_WESUITAPP = 'wesuit_app';
17
+    const BROWSER_TYPE_CMB_MOBILE_OA = 'cmb_mobile_oa';
18
+    const BROWSER_TYPE_PINGAN_ZHINIAO = 'pingan_zhiniao';
19
+    const BROWSER_TYPE_YUNZHIJIA = 'yunzhijia';
20
+    const BROWSER_TYPE_DINGTALK = 'dingtalk';
21
+    const BROWSER_TYPE_KARA = 'kara';
22
+    const BROWSER_TYPE_NOT_WX = '';
23
+
24
+    /**
25
+     * 得到APP client的类型
26
+     * @return string
27
+     */
28
+    public static function browserType() {
29
+        if(strpos($_SERVER['HTTP_USER_AGENT'], 'wxwork') !== false) {
30
+            return self::BROWSER_TYPE_WESUITAPP;
31
+        } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'CMBMobileOA') !== false) {
32
+            return self::BROWSER_TYPE_CMB_MOBILE_OA;
33
+        } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'PinganZhiniao') !== false) {
34
+            return self::BROWSER_TYPE_PINGAN_ZHINIAO;
35
+        } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
36
+            return self::BROWSER_TYPE_WECHAT;
37
+        } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Qing') !== false) {
38
+            return self::BROWSER_TYPE_YUNZHIJIA;
39
+        } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'DingTalk') !== false) {
40
+            return self::BROWSER_TYPE_DINGTALK;
41
+        } elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'kara') !== false) {
42
+            return self::BROWSER_TYPE_KARA;
43
+        } else {
44
+            return self::BROWSER_TYPE_NOT_WX;
45
+        }
46
+    }
47
+
48
+    /**
49
+     * 是否微信访问
50
+     * @return bool
51
+     */
52
+    public static function isWxBrowser() {
53
+        return (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) ||
54
+            (strpos($_SERVER['HTTP_USER_AGENT'], 'wxwork') !== false);
55
+    }
56
+
57
+    // 查看是否为手机端的方法
58
+    //判断是手机登录还是电脑登录
59
+    public static function isMobile() {
60
+        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
61
+        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
62
+            return true;
63
+
64
+        //此条摘自TPM智能切换模板引擎,适合TPM开发
65
+        if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
66
+            return true;
67
+        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
68
+        if (isset ($_SERVER['HTTP_VIA']))
69
+            //找不到为flase,否则为true
70
+            return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
71
+        //判断手机发送的客户端标志,兼容性有待提高
72
+        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
73
+            $clientkeywords = array(
74
+                'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
75
+            );
76
+            //从HTTP_USER_AGENT中查找手机浏览器的关键字
77
+            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
78
+                return true;
79
+            }
80
+        }
81
+        //协议法,因为有可能不准确,放到最后判断
82
+        if (isset ($_SERVER['HTTP_ACCEPT'])) {
83
+            // 如果只支持wml并且不支持html那一定是移动设备
84
+            // 如果支持wml和html但是wml在html之前则是移动设备
85
+            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
86
+                return true;
87
+            }
88
+        }
89
+        return false;
90
+    }
91
+}

+ 162 - 0
app/Libs/Curl.php Прегледај датотеку

@@ -0,0 +1,162 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/5/24
6
+ * Time: 11:30
7
+ */
8
+
9
+namespace App\Libs;
10
+
11
+class Curl {
12
+    private $http_code_ = 0;
13
+    private $errno_ = 0;
14
+    private $error_ = '';
15
+    private $response_ = '';
16
+    private $headers_ = array();
17
+    private $options_ = array();
18
+    private $info_ = array();
19
+    private $handle_ = null;
20
+
21
+
22
+    /**
23
+     * CuteCurl constructor.
24
+     * @param $url
25
+     * @param bool|false $require_response_body 非200状态保存返回内容
26
+     */
27
+    function __construct($url, $require_response_body = false) {
28
+        $this->handle_ = curl_init($url);
29
+        $this->option(CURLOPT_FAILONERROR, !$require_response_body);
30
+    }
31
+
32
+    public function setTimeout($t) {
33
+        $this->option('timeout', $t);
34
+    }
35
+
36
+    /**
37
+     * @return int
38
+     */
39
+    public function getErrno() {
40
+        return $this->errno_;
41
+    }
42
+
43
+    /**
44
+     * @return string
45
+     */
46
+    public function getError() {
47
+        return $this->error_;
48
+    }
49
+
50
+    /**
51
+     * @return array
52
+     */
53
+    public function getInfo() {
54
+        return $this->info_;
55
+    }
56
+
57
+    /**
58
+     * @return int
59
+     */
60
+    public function getHttpCode() {
61
+        return $this->http_code_;
62
+    }
63
+
64
+
65
+    public function httpGet() {
66
+        return $this->send();
67
+    }
68
+
69
+    public function httpPost($params = array(), $options = array()) {
70
+        // If its an array (instead of a query string) then format it correctly
71
+        if (is_array($params)) {
72
+            $params = http_build_query($params);
73
+        }
74
+        // Add in the specific options provided
75
+        $this->options($options);
76
+        $this->option(CURLOPT_POST, TRUE);
77
+        $this->option(CURLOPT_POSTFIELDS, $params);
78
+        return $this->send();
79
+    }
80
+
81
+    public function httpHeader($header, $content = NULL) {
82
+        $this->headers_[] = $content ? $header . ': ' . $content : $header;
83
+    }
84
+
85
+    public function sendCookie($cookie,$prefix) {
86
+        if(!empty($cookie)) {
87
+            $str = '';
88
+            foreach ($cookie as $key => $value) {
89
+                if(strpos($key,$prefix) === 0 ) {
90
+                    $str .= $key.'='.$value.';';
91
+                }
92
+            }
93
+            $this->headers_[] = 'Cookie: '.substr($str,0,-1);
94
+        }
95
+    }
96
+
97
+    private function send() {
98
+        // Set two default options_, and merge any extra ones in
99
+        if (!isset($this->options_[CURLOPT_TIMEOUT])) {
100
+            $this->options_[CURLOPT_TIMEOUT] = 30;
101
+        }
102
+        if (!isset($this->options_[CURLOPT_RETURNTRANSFER])) {
103
+            $this->options_[CURLOPT_RETURNTRANSFER] = TRUE;
104
+        }
105
+        if (!isset($this->options_[CURLOPT_FAILONERROR])) {
106
+            $this->options_[CURLOPT_FAILONERROR] = TRUE;
107
+        }
108
+
109
+        if (!empty($this->headers_)) {
110
+            $this->option(CURLOPT_HTTPHEADER, $this->headers_);
111
+        }
112
+
113
+        $this->options();
114
+
115
+        // Execute the request & and hide all output
116
+        $this->response_ = curl_exec($this->handle_);
117
+        $this->info_ = curl_getinfo($this->handle_);
118
+        $this->http_code_ = $this->info_['http_code'];
119
+
120
+        // Request failed
121
+        if ($this->response_ === FALSE) {
122
+            $this->errno_ = curl_errno($this->handle_);
123
+            $this->error_ = curl_error($this->handle_);
124
+            curl_close($this->handle_);
125
+            return FALSE;
126
+        } // Request successful
127
+        else {
128
+            curl_close($this->handle_);
129
+            return $this->response_;
130
+        }
131
+    }
132
+
133
+    public function ssl($verify_peer = TRUE, $verify_host = 2, $path_to_cert = NULL) {
134
+        if ($verify_peer) {
135
+            $this->option(CURLOPT_SSL_VERIFYPEER, TRUE);
136
+            $this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
137
+            $this->option(CURLOPT_CAINFO, $path_to_cert);
138
+        } else {
139
+            $this->option(CURLOPT_SSL_VERIFYPEER, FALSE);
140
+        }
141
+        return $this;
142
+    }
143
+
144
+    public function options($options = array()) {
145
+        // Merge options in with the rest - done as array_merge() does not overwrite numeric keys
146
+        foreach ($options as $option_code => $option_value) {
147
+            $this->option($option_code, $option_value);
148
+        }
149
+        // Set all options provided
150
+        curl_setopt_array($this->handle_, $this->options_);
151
+        return $this;
152
+    }
153
+
154
+    public function option($code, $value) {
155
+        if (is_string($code) && !is_numeric($code)) {
156
+            $code = constant('CURLOPT_' . strtoupper($code));
157
+        }
158
+        $this->options_[$code] = $value;
159
+        return $this;
160
+    }
161
+
162
+}

+ 31 - 0
app/Listeners/ExampleListener.php Прегледај датотеку

@@ -0,0 +1,31 @@
1
+<?php
2
+
3
+namespace App\Listeners;
4
+
5
+use App\Events\ExampleEvent;
6
+use Illuminate\Queue\InteractsWithQueue;
7
+use Illuminate\Contracts\Queue\ShouldQueue;
8
+
9
+class ExampleListener
10
+{
11
+    /**
12
+     * Create the event listener.
13
+     *
14
+     * @return void
15
+     */
16
+    public function __construct()
17
+    {
18
+        //
19
+    }
20
+
21
+    /**
22
+     * Handle the event.
23
+     *
24
+     * @param  ExampleEvent  $event
25
+     * @return void
26
+     */
27
+    public function handle(ExampleEvent $event)
28
+    {
29
+        //
30
+    }
31
+}

+ 24 - 0
app/Models/Blockade.php Прегледај датотеку

@@ -0,0 +1,24 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/19
7
+ * Time: 18:43
8
+ */
9
+
10
+namespace App\Models;
11
+
12
+use Illuminate\Database\Eloquent\Model;
13
+
14
+class Blockade extends Model
15
+{
16
+    protected $table = "bs_blockades";
17
+    protected $primaryKey = "blockade_id";
18
+
19
+    protected $dateFormat = 'U';
20
+    const CREATED_AT = "create_time";
21
+    const UPDATED_AT = "update_time";
22
+
23
+    public $fillable=["corp_id","activity_id","user_id","question_ids","status","is_success"];
24
+}

+ 20 - 0
app/Models/BlockadeUserAnswer.php Прегледај датотеку

@@ -0,0 +1,20 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/19
6
+ * Time: 18:43
7
+ */
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class BlockadeUserAnswer extends Model{
13
+    protected $table = "bs_blockade_user_answers";
14
+    protected $primaryKey = "id";
15
+
16
+    protected $dateFormat = 'U';
17
+    const CREATED_AT = "create_time";
18
+    const UPDATED_AT = "update_time";
19
+    public $fillable=["corp_id","activity_id","user_id","blockade_id","question_id","user_answer","is_correct"];
20
+}

+ 33 - 0
app/Models/Corp.php Прегледај датотеку

@@ -0,0 +1,33 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/19
7
+ * Time: 18:43
8
+ */
9
+namespace App\Models;
10
+
11
+use Illuminate\Database\Eloquent\Model;
12
+
13
+class Corp extends Model
14
+{
15
+    protected $table = "agh_corps";
16
+    protected $primaryKey = "corp_id";
17
+
18
+    protected $dateFormat = 'U';
19
+    const CREATED_AT = "create_time";
20
+    const UPDATED_AT = "update_time";
21
+
22
+    public $fillable = [
23
+        "corp_id",
24
+        "corp_name",
25
+        "contact_address",
26
+        "contact_phone",
27
+        "contact_email",
28
+        "corp_short_name",
29
+        "source_id",
30
+        "qy_corp_id",
31
+        "source_type"
32
+    ];
33
+}

+ 23 - 0
app/Models/Department.php Прегледај датотеку

@@ -0,0 +1,23 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/19
7
+ * Time: 18:43
8
+ */
9
+namespace App\Models;
10
+
11
+use Illuminate\Database\Eloquent\Model;
12
+
13
+class Department extends Model
14
+{
15
+    protected $table = "bs_departments";
16
+    protected $primaryKey = "department_id";
17
+
18
+    protected $dateFormat = 'U';
19
+    const CREATED_AT = "create_time";
20
+    const UPDATED_AT = "update_time";
21
+
22
+    public $fillable=["corp_id","activity_id","department_name","status"];
23
+}

+ 22 - 0
app/Models/KnowledgeMoneyRecord.php Прегледај датотеку

@@ -0,0 +1,22 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/19
7
+ * Time: 18:43
8
+ */
9
+namespace App\Models;
10
+
11
+use Illuminate\Database\Eloquent\Model;
12
+
13
+class KnowledgeMoneyRecord extends Model
14
+{
15
+    protected $table = "bs_knowledge_money_records";
16
+    protected $primaryKey = "id";
17
+
18
+    protected $dateFormat = 'U';
19
+    const CREATED_AT = "create_time";
20
+
21
+    public $fillable=["corp_id","activity_id","user_id","get_mode","mode_id","money"];
22
+}

+ 25 - 0
app/Models/Lottery.php Прегледај датотеку

@@ -0,0 +1,25 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Model;
6
+
7
+class Lottery extends Model
8
+{
9
+    protected $table = "bs_user_lotterys";
10
+
11
+    protected $primaryKey = "lottery_id";
12
+
13
+    public $timestamps = false;
14
+
15
+
16
+    protected $fillable = [
17
+        'lottery_id','corp_id','activity_id','user_id','lottery_level','lottery_time','prize_id'
18
+    ];
19
+
20
+    public function prize()
21
+    {
22
+        return $this -> hasOne('App\Models\Prize','prize_id');
23
+    }
24
+
25
+}

+ 20 - 0
app/Models/LotteryBoxs.php Прегледај датотеку

@@ -0,0 +1,20 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Model;
6
+
7
+class LotteryBoxs extends Model
8
+{
9
+    protected $table = "bs_lottery_boxs";
10
+
11
+    protected $primaryKey = "id";
12
+
13
+    public $timestamps = false;
14
+
15
+
16
+    protected $fillable = [
17
+        'id','corp_id','activity_id','lottery_name','lottery_level','status','open_mode','open_rule','update_time','create_time'
18
+    ];
19
+
20
+}

+ 23 - 0
app/Models/PkRoom.php Прегледај датотеку

@@ -0,0 +1,23 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/19
7
+ * Time: 18:43
8
+ */
9
+namespace App\Models;
10
+
11
+use Illuminate\Database\Eloquent\Model;
12
+
13
+class PkRoom extends Model
14
+{
15
+    protected $table = "bs_pk_rooms";
16
+    protected $primaryKey = "room_id";
17
+
18
+    protected $dateFormat = 'U';
19
+    const CREATED_AT = "create_time";
20
+    const UPDATED_AT = "update_time";
21
+
22
+    public $fillable=["corp_id","activity_id","sponsor_user_id","challenger_user_id","question_ids","status","knowledge_money","winter_user_id","is_dispose"];
23
+}

+ 21 - 0
app/Models/PkUserAnswer.php Прегледај датотеку

@@ -0,0 +1,21 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/19
6
+ * Time: 18:43
7
+ */
8
+namespace App\Models;
9
+
10
+use Illuminate\Database\Eloquent\Model;
11
+
12
+class PkUserAnswer extends Model
13
+{
14
+    protected $table = "bs_pk_user_answers";
15
+    protected $primaryKey = "id";
16
+
17
+    protected $dateFormat = 'U';
18
+    const CREATED_AT = "create_time";
19
+
20
+    public $fillable=["corp_id","activity_id","user_id","room_id","question_id","user_answer","is_correct"];
21
+}

+ 21 - 0
app/Models/Prize.php Прегледај датотеку

@@ -0,0 +1,21 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Model;
6
+
7
+class Prize extends Model
8
+{
9
+    protected $table = "bs_prizes";
10
+
11
+    protected $primaryKey = "prize_id";
12
+
13
+    protected $dateFormat = 'U';
14
+    const CREATED_AT = "create_time";
15
+    const UPDATED_AT = "update_time";
16
+
17
+    protected $fillable = [
18
+        'prize_id',"activity_id","corp_id",'prize_name','prize_image_url','prize_count','prize_grant_count','prize_weights','status','prize_day_rule'
19
+    ];
20
+
21
+}

+ 24 - 0
app/Models/Question.php Прегледај датотеку

@@ -0,0 +1,24 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/19
7
+ * Time: 18:43
8
+ */
9
+
10
+namespace App\Models;
11
+
12
+use Illuminate\Database\Eloquent\Model;
13
+
14
+class Question extends Model
15
+{
16
+    protected $table = "bs_questions";
17
+    protected $primaryKey = "question_id";
18
+
19
+    protected $dateFormat = 'U';
20
+    const CREATED_AT = "create_time";
21
+    const UPDATED_AT = "update_time";
22
+
23
+    public $fillable = ["corp_id","activity_id", "category_id","question_title", "question_options", "question_answer", "is_must_answer", "status"];
24
+}

+ 23 - 0
app/Models/QuestionCategory.php Прегледај датотеку

@@ -0,0 +1,23 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/19
7
+ * Time: 18:43
8
+ */
9
+namespace App\Models;
10
+
11
+use Illuminate\Database\Eloquent\Model;
12
+
13
+class QuestionCategory extends Model
14
+{
15
+    protected $table = "bs_question_categorys";
16
+    protected $primaryKey = "category_id";
17
+
18
+    protected $dateFormat = 'U';
19
+    const CREATED_AT = "create_time";
20
+    const UPDATED_AT = "update_time";
21
+
22
+    public $fillable=["corp_id","activity_id","category_name"];
23
+}

+ 21 - 0
app/Models/User.php Прегледај датотеку

@@ -0,0 +1,21 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Illuminate\Database\Eloquent\Model;
6
+
7
+class User extends Model
8
+{
9
+    protected $table = "bs_users";
10
+
11
+    protected $primaryKey = "user_id";
12
+
13
+    protected $dateFormat = 'U';
14
+    const CREATED_AT = "create_time";
15
+    const UPDATED_AT = "update_time";
16
+
17
+    protected $fillable = [
18
+        'corp_id',"activity_id",'open_id','login_name','name','phone','email','department_id','knowledge_money','status','guid','nickname','avatar','platform','user_level','user_star','win_continuity'
19
+    ];
20
+
21
+}

+ 18 - 0
app/Providers/AppServiceProvider.php Прегледај датотеку

@@ -0,0 +1,18 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use Illuminate\Support\ServiceProvider;
6
+
7
+class AppServiceProvider extends ServiceProvider
8
+{
9
+    /**
10
+     * Register any application services.
11
+     *
12
+     * @return void
13
+     */
14
+    public function register()
15
+    {
16
+        //
17
+    }
18
+}

+ 39 - 0
app/Providers/AuthServiceProvider.php Прегледај датотеку

@@ -0,0 +1,39 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use App\User;
6
+use Illuminate\Support\Facades\Gate;
7
+use Illuminate\Support\ServiceProvider;
8
+
9
+class AuthServiceProvider extends ServiceProvider
10
+{
11
+    /**
12
+     * Register any application services.
13
+     *
14
+     * @return void
15
+     */
16
+    public function register()
17
+    {
18
+        //
19
+    }
20
+
21
+    /**
22
+     * Boot the authentication services for the application.
23
+     *
24
+     * @return void
25
+     */
26
+    public function boot()
27
+    {
28
+        // Here you may define how you wish users to be authenticated for your Lumen
29
+        // application. The callback which receives the incoming request instance
30
+        // should return either a User instance or null. You're free to obtain
31
+        // the User instance via an API token or any other method necessary.
32
+
33
+        $this->app['auth']->viaRequest('api', function ($request) {
34
+            if ($request->input('api_token')) {
35
+                return User::where('api_token', $request->input('api_token'))->first();
36
+            }
37
+        });
38
+    }
39
+}

+ 19 - 0
app/Providers/EventServiceProvider.php Прегледај датотеку

@@ -0,0 +1,19 @@
1
+<?php
2
+
3
+namespace App\Providers;
4
+
5
+use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;
6
+
7
+class EventServiceProvider extends ServiceProvider
8
+{
9
+    /**
10
+     * The event listener mappings for the application.
11
+     *
12
+     * @var array
13
+     */
14
+    protected $listen = [
15
+        'App\Events\SomeEvent' => [
16
+            'App\Listeners\EventListener',
17
+        ],
18
+    ];
19
+}

+ 47 - 0
app/Services/AccessToken.php Прегледај датотеку

@@ -0,0 +1,47 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/20
6
+ * Time: 14:30
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Traits\Singleton;
12
+use Illuminate\Support\Facades\Log;
13
+use Illuminate\Support\Facades\Redis;
14
+
15
+class AccessToken
16
+{
17
+    use Singleton;
18
+    const REDIS_ACCESS_TOKENS = "bs_accesstoken";
19
+
20
+    public function create($user)
21
+    {
22
+        $accessToken = $this->generate(64);
23
+        Log::info($accessToken);
24
+        Redis::hset(self::REDIS_ACCESS_TOKENS, $user["user_id"], $accessToken);
25
+        return $accessToken;
26
+    }
27
+
28
+    public function generate($length = 32)
29
+    {
30
+        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
31
+        $useChars = array();
32
+        // select some random chars:
33
+        for ($i = 0; $i < $length; $i++) {
34
+            $useChars[] = $characters[mt_rand(0, strlen($characters) - 1)];
35
+        }
36
+        // Add numbers
37
+        array_push($useChars, rand(0, 9), rand(0, 9), rand(0, 9));
38
+        shuffle($useChars);
39
+        $randomString = trim(implode('', $useChars));
40
+        $randomString = substr($randomString, 0, $length);
41
+        return base64_encode($randomString);
42
+    }
43
+
44
+    public function getAccessToken($userId){
45
+        return Redis::hGet(self::REDIS_ACCESS_TOKENS,$userId);
46
+    }
47
+}

+ 66 - 0
app/Services/BrainstormingService.php Прегледај датотеку

@@ -0,0 +1,66 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/5/14
6
+ * Time: 17:59
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Traits\Singleton;
12
+use Illuminate\Support\Facades\DB;
13
+use Illuminate\Support\Facades\Redis;
14
+use Yansongda\Pay\Log;
15
+
16
+class BrainstormingService
17
+{
18
+    use Singleton;
19
+
20
+    const BRAINSTORMING = "bs_brainstorming";
21
+
22
+    public function cache($activityId){
23
+        $activity = DB::table("agh_activitys")->where("activity_id",$activityId)->first();
24
+        $corp = DB::table("agh_corps")->where("corp_id",$activity->corp_id)->first();
25
+        $config = DB::table("bs_configs")->where("activity_id",$activityId)->first();
26
+        $brainstorming = collect($config)->toArray();
27
+        $extendConfigs =[];
28
+        if(!empty($brainstorming["extend_configs"])){
29
+            $extendConfigs = json_decode($brainstorming["extend_configs"],true);
30
+        }
31
+        unset($brainstorming["extend_configs"]);
32
+        $brainstorming = array_merge(collect($activity)->toArray(),$brainstorming);
33
+        $brainstorming = array_merge($brainstorming,$extendConfigs);
34
+
35
+        $brainstorming["title"] = $activity->title;
36
+        $brainstorming["logo"] = $activity->logo;
37
+        $brainstorming["regulation"] = $activity->regulation;
38
+        $brainstorming["corp_name"] = $corp->corp_name;
39
+        $brainstorming["corp_short_name"] = $corp->corp_short_name;
40
+        $brainstorming["qy_corp_id"] = $corp->qy_corp_id;
41
+        $brainstorming["gcorp_id"] = $corp->source_id;
42
+
43
+        unset($brainstorming["update_time"]);
44
+        unset($brainstorming["create_time"]);
45
+
46
+        \Illuminate\Support\Facades\Log::info(json_encode($brainstorming,256));
47
+        Redis::hMset(self::BRAINSTORMING.":".$activityId,$brainstorming);
48
+        Redis::expire(self::BRAINSTORMING.":".$activityId,600);
49
+        //缓存题目
50
+        if(!Redis::exists("question_cache:".$activityId)){
51
+            QuestionService::getInstance()->cache($activityId);
52
+            Redis::setex("question_cache:".$activityId,86400,$activityId);
53
+        }
54
+        return $brainstorming;
55
+
56
+    }
57
+
58
+    public function get($activityId){
59
+        $data = Redis::hGetall(self::BRAINSTORMING.":".$activityId);
60
+        if($data){
61
+            return $data;
62
+        }else{
63
+            return $this->cache($activityId);
64
+        }
65
+    }
66
+}

+ 121 - 0
app/Services/CookieService.php Прегледај датотеку

@@ -0,0 +1,121 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/6/5
6
+ * Time: 11:29
7
+ */
8
+
9
+namespace App\Services;
10
+use Illuminate\Support\Facades\Cookie;
11
+
12
+class CookieService
13
+{
14
+    /**
15
+     * 获得Oauth的COOKIE
16
+     * @return array
17
+     */
18
+
19
+    public static function getOauth(){
20
+        $data = [
21
+            "oauth_open_id" => Cookie::get("oauth_open_id"),
22
+            "oauth_avatar" => Cookie::get("oauth_avatar"),
23
+            "oauth_nickname" => Cookie::get("oauth_nickname"),
24
+            "oauth_platform" => Cookie::get("oauth_platform"),
25
+            "oauth_guid" => Cookie::get("oauth_guid"),
26
+            "oauth_department" => Cookie::get("oauth_department"),
27
+            "oauth_gcorp_id" => Cookie::get("oauth_gcorp_id"),
28
+        ];
29
+
30
+        return $data;
31
+    }
32
+
33
+    /**
34
+     * 设置oAuth cookies
35
+     * @param $data
36
+     */
37
+    public static function setOauth($data){
38
+        setcookie("oauth_open_id", $data["oauth_open_id"], 0,"/",env("COOKIE_DOMAIN"));
39
+        setcookie("oauth_avatar", $data["oauth_avatar"], 0,"/",env("COOKIE_DOMAIN"));
40
+        setcookie("oauth_nickname", $data["oauth_nickname"], 0,"/",env("COOKIE_DOMAIN"));
41
+        setcookie("oauth_platform", $data["oauth_platform"], 0,"/",env("COOKIE_DOMAIN"));
42
+        setcookie("oauth_guid", $data["oauth_guid"], 0,"/",env("COOKIE_DOMAIN"));
43
+    }
44
+
45
+    /**
46
+     * 清除Oauth cookies信息
47
+     */
48
+    public static function unsetOauth(){
49
+        setcookie("oauth_open_id", '', null,"/",env("COOKIE_DOMAIN"));
50
+        setcookie("oauth_avatar", '', null,"/",env("COOKIE_DOMAIN"));
51
+        setcookie("oauth_nickname", '', null,"/",env("COOKIE_DOMAIN"));
52
+        setcookie("oauth_platform", '', null,"/",env("COOKIE_DOMAIN"));
53
+        setcookie("oauth_guid", '', null,"/",env("COOKIE_DOMAIN"));
54
+        setcookie("oauth_department", '', null,"/",env("COOKIE_DOMAIN"));
55
+        setcookie("oauth_gcorp_id", '', null,"/",env("COOKIE_DOMAIN"));
56
+    }
57
+
58
+    public static function setQyCorpId($qyCorpId){
59
+        setcookie("qyCorpId", $qyCorpId,null,"/",env("COOKIE_DOMAIN"));
60
+    }
61
+
62
+    /**
63
+     * 获得用户信息
64
+     * @return mixed|null
65
+     */
66
+    public static function getBsAuthUser(){
67
+        $userData = Cookie::get("bs_access_user_data");
68
+        $user = empty($userData)? null:json_decode(base64_decode($userData),true);
69
+        return $user;
70
+    }
71
+
72
+    /**
73
+     * 获得accessToken的cookie信息
74
+     * @return string
75
+     */
76
+    public static function getBsAccessToken(){
77
+        return Cookie::get("bs_access_token");
78
+    }
79
+
80
+    /**
81
+     * 设置认证后的cookie信息
82
+     * @param $user
83
+     * @param $accessToken
84
+     */
85
+
86
+    public static function setBsAuth($user,$accessToken){
87
+        setcookie("bs_access_user_data", base64_encode(json_encode(["user_id" => $user["user_id"],"corp_id"=>$user["corp_id"],"activity_id"=>$user["activity_id"]])),null,"/",env("COOKIE_DOMAIN"));
88
+        setcookie("bs_access_token", $accessToken,null,"/",env("COOKIE_DOMAIN"));
89
+    }
90
+
91
+    /**
92
+     * 清除认证后的auth Cookie信息
93
+     */
94
+    public static function unsetBsAuth(){
95
+        setcookie("bs_access_user_data", null,0,"/",env("COOKIE_DOMAIN"));
96
+        setcookie("bs_access_token", null,0,"/",env("COOKIE_DOMAIN"));
97
+    }
98
+
99
+    /**
100
+     * 增加登录尝试次数
101
+     */
102
+    public static function incrLoginTrialNum(){
103
+        $loginNum = intval(self::getLoginTrialNum())+1;
104
+        setcookie("bs_login_trials",$loginNum,null,"/",env("COOKIE_DOMAIN"));
105
+    }
106
+
107
+    /**
108
+     * 获得登录尝试的次数
109
+     * @return string
110
+     */
111
+    public static function getLoginTrialNum(){
112
+        return intval(Cookie::get("bs_login_trials"));
113
+    }
114
+
115
+    /**
116
+     * 清除登录尝试次数
117
+     */
118
+    public static function unsetLoginTrialNum(){
119
+        setcookie("bs_login_trials", '', null,"/",env("COOKIE_DOMAIN"));
120
+    }
121
+}

+ 68 - 0
app/Services/DepartmentService.php Прегледај датотеку

@@ -0,0 +1,68 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/3/31
6
+ * Time: 18:51
7
+ */
8
+
9
+namespace App\Services;
10
+use App\Models\Department;
11
+use App\Models\User;
12
+use App\Traits\Singleton;
13
+use Illuminate\Support\Facades\Redis;
14
+
15
+class DepartmentService
16
+{
17
+    use Singleton;
18
+    const DEPARTMENTS = "bs_departments";
19
+    /**
20
+     * 获得所有部门信息
21
+     * @return mixed
22
+     */
23
+    public function all($activityId){
24
+        $departments = Department::where("activity_id",$activityId)->where("status",1)->pluck("department_name","department_id");
25
+        //$departments = collect($departments)->toArray();
26
+        return $departments;
27
+    }
28
+
29
+    /**
30
+     * 获得所有部门的总人数
31
+     * @return mixed
32
+     */
33
+    public function allPcount($activityId){
34
+        $departments = Department::where("activity_id",$activityId)->where("status",1)->pluck("user_num","department_id");
35
+        return collect($departments)->toArray();
36
+    }
37
+
38
+    /**
39
+     * 获取部门人员Id
40
+     * @param $departmentId
41
+     * @return mixed
42
+     */
43
+    public function getUserIdsByDepartmentId($departmentId){
44
+        $userIds = User::where("department_id",$departmentId)->pluck("user_id");
45
+        return $userIds;
46
+    }
47
+
48
+    /**
49
+     * 获得部门名称
50
+     * @param $departmentId
51
+     * @return string
52
+     */
53
+    public function getDepartmentName($departmentId){
54
+        $departmentName = "";
55
+        if(!empty($departmentId)){
56
+            $departmentName = Redis::get(self::DEPARTMENTS.":".$departmentId);
57
+            if(empty($departmentName)){
58
+                $department = Department::find($departmentId);
59
+                if($department){
60
+                    $departmentName = $department->department_name;
61
+                    Redis::set(self::DEPARTMENTS.":".$departmentId,$departmentName);
62
+                    Redis::expire(self::DEPARTMENTS.":".$departmentId,600);
63
+                }
64
+            }
65
+        }
66
+        return $departmentName;
67
+    }
68
+}

+ 33 - 0
app/Services/ErrorMessageService.php Прегледај датотеку

@@ -0,0 +1,33 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/6/5
6
+ * Time: 16:32
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+
12
+use Illuminate\Support\Facades\Log;
13
+
14
+class ErrorMessageService
15
+{
16
+
17
+    public static function redirect($message=""){
18
+        Log::info("User agent");
19
+        Log::info($_SERVER['HTTP_USER_AGENT']);
20
+        $url = env("ERROR_MESSAGE_URL");
21
+        if($message) $url.="?error=".$message;
22
+        header("location: ".$url);
23
+        die;
24
+    }
25
+
26
+    public static function forward($message=""){
27
+        Log::info("User agent");
28
+        Log::info($_SERVER['HTTP_USER_AGENT']);
29
+        $url = env("ERROR_MESSAGE_URL");
30
+        if($message) $url.="?error=".$message;
31
+        die(json_encode(["error"=>302,"message"=>$message,"redirect"=>$url]));
32
+    }
33
+}

+ 69 - 0
app/Services/GameTimeService.php Прегледај датотеку

@@ -0,0 +1,69 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/4/4
6
+ * Time: 0:08
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Traits\Singleton;
12
+use Illuminate\Support\Facades\Redis;
13
+
14
+
15
+class GameTimeService
16
+{
17
+    use Singleton;
18
+
19
+    /**
20
+     * @param $activityId
21
+     * @return bool
22
+     */
23
+    public function isReachStartTime($activityId)
24
+    {
25
+
26
+        $brainstorming = BrainstormingService::getInstance()->get($activityId);
27
+
28
+        if ($brainstorming["start_time"] <= time()) {
29
+            return 1;
30
+        } else {
31
+            return 0;
32
+        }
33
+    }
34
+
35
+    /**
36
+     * @param $activityId
37
+     * @return bool
38
+     */
39
+    public function isReachEndTime($activityId)
40
+    {
41
+        $brainstorming = BrainstormingService::getInstance()->get($activityId);
42
+        $endTime = $brainstorming["end_time"];
43
+        $now = time();
44
+        if ($endTime > 0 && $now > $endTime) {
45
+            return true;
46
+        }
47
+        return false;
48
+    }
49
+
50
+    /**
51
+     * @param $activityId
52
+     * @return bool
53
+     */
54
+    public function isCanGame($activityId,$userId)
55
+    {
56
+        $brainstorming = BrainstormingService::getInstance()->get($activityId);
57
+        $user = UserService::getInstance()->getUser($userId);
58
+        $startTime = $brainstorming["start_time"];
59
+        $endTime = $brainstorming["end_time"];
60
+        $now = time();
61
+        if ($startTime > 0 && $now < $startTime && $user["is_white_list"]==0) {
62
+            return false;
63
+        }
64
+        if ($endTime > 0 && $now > $endTime) {
65
+            return false;
66
+        }
67
+        return true;
68
+    }
69
+}

+ 30 - 0
app/Services/LogEventService.php Прегледај датотеку

@@ -0,0 +1,30 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/7/27
6
+ * Time: 11:45
7
+ * 记录用户操作日志,例如用户上下线,用户答题
8
+ */
9
+
10
+namespace App\Services;
11
+
12
+use App\Traits\Singleton;
13
+
14
+class LogEventService
15
+{
16
+    use Singleton;
17
+    const REDIS_KEY="log_event:brainstorming";
18
+
19
+    public function push($activityId,$userId,$channel,$event,$data=[]){
20
+        $redisData = [
21
+            "activity_id" => $activityId,
22
+            "user_id" => $userId,
23
+            "channel" => $channel,
24
+            "event" => $event,
25
+            "event_time" => time(),
26
+            "data" => $data
27
+        ];
28
+        app("redisLog")->lPush(self::REDIS_KEY,json_encode($redisData));
29
+    }
30
+}

+ 67 - 0
app/Services/OnlineLimitService.php Прегледај датотеку

@@ -0,0 +1,67 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/7/3
6
+ * Time: 11:23
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+
12
+use App\Models\OnlineLimits;
13
+use App\Traits\Singleton;
14
+use Illuminate\Support\Facades\DB;
15
+use Illuminate\Support\Facades\Redis;
16
+
17
+class OnlineLimitService
18
+{
19
+    use Singleton;
20
+
21
+    const REDIS_ONLINE = "bs_online";
22
+    const REDIS_ONLINE_LIMIT = "bs_online_limit";
23
+    const REDIS_APPS = "agh_apps";
24
+
25
+    /**
26
+     * 判断是否超过在线人数
27
+     */
28
+    public function isOverOnline($activityId){
29
+        $onlineLimitNumber = 0;
30
+        if(!Redis::exists(self::REDIS_ONLINE_LIMIT.":".$activityId)){
31
+            $brainstorming = BrainstormingService::getInstance()->get($activityId);
32
+            if(isset($brainstorming["activity_type"])){
33
+                $freeNum = $this->getFreeNum();
34
+                if($brainstorming["activity_type"]==1){
35
+                    $onlineLimitNumber = $freeNum;
36
+                }
37
+            }
38
+            Redis::setex(self::REDIS_ONLINE_LIMIT.":".$activityId,300,$onlineLimitNumber);
39
+        }else{
40
+            $onlineLimitNumber = Redis::get(self::REDIS_ONLINE_LIMIT.":".$activityId);
41
+        }
42
+
43
+        if($onlineLimitNumber>0){
44
+            $onlineCount = Redis::get(self::REDIS_ONLINE.":".$activityId);
45
+            if($onlineCount>=$onlineLimitNumber){
46
+                return true;
47
+            }
48
+        }
49
+        return false;
50
+    }
51
+
52
+    public function onlineLimitCount($activityId){
53
+        return Redis::get(self::REDIS_ONLINE_LIMIT.":".$activityId);
54
+    }
55
+
56
+    public function getFreeNum(){
57
+        $freeNum = 0;
58
+        if(!Redis::exists(self::REDIS_APPS.":brainstorming")){
59
+            $app = DB::table("agh_apps")->where("app_code","brainstorming")->first();
60
+            if($app){
61
+                $freeNum = $app->free_num;
62
+                Redis::setex(self::REDIS_APPS.":brainstorming",300,json_encode($app,256));
63
+            }
64
+        }
65
+        return $freeNum;
66
+    }
67
+}

+ 280 - 0
app/Services/PkService.php Прегледај датотеку

@@ -0,0 +1,280 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/5/16
6
+ * Time: 17:49
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Models\PkRoom;
12
+use App\Traits\Singleton;
13
+use Illuminate\Support\Facades\Log;
14
+use Illuminate\Support\Facades\Redis;
15
+
16
+class PkService
17
+{
18
+    use Singleton;
19
+    const QUESTION_COLLECT = "bs_question_collect";
20
+    const PK_ROOMS = "bs_pk_rooms";
21
+    const PK_ROOM_ANSWERS = "bs_pk_room_answers";
22
+    const PK_QUEUE = "bs_pk_queue";
23
+    const PK_STATUS_QUEUE = "bs_pk_room_queue";
24
+    const PK_ROOM_JOINS = "bs_pk_room_joins";
25
+    const PK_RUN = "bs_pk_room_run";
26
+    const NOT_COMPLETE_PKS = "bs_pk_room_not_completes";
27
+    const QUESTION_COUNT = 5;
28
+    const COUNT_DOWN = 13;
29
+    const ROOM_OVER_TIME = 300;
30
+    /**
31
+     * 获取房间信息
32
+     * @param $roomId
33
+     * @return array
34
+     */
35
+    public function getRoomInfo($roomId)
36
+    {
37
+        return Redis::hGetAll(self::PK_ROOMS . ":" . $roomId);
38
+    }
39
+
40
+    /**
41
+     * 获取PK对战的双方信息
42
+     * @param $sponsorUserId
43
+     * @param $challengerUserId
44
+     * @return array
45
+     */
46
+    public function getPkUserInfo($sponsorUserId, $challengerUserId)
47
+    {
48
+        $data = [
49
+            "sponsor_user_id" => $sponsorUserId,
50
+            "sponsor_name" => "",
51
+            "sponsor_short_name" => "",
52
+            "sponsor_headpic_url" => "",
53
+            "sponsor_department" => "",
54
+            "challenger_user_id" => $challengerUserId,
55
+            "challenger_name" => "",
56
+            "challenger_short_name" => "",
57
+            "challenger_headpic_url" => "",
58
+            "challenger_department" => ""
59
+        ];
60
+        if ($sponsorUserId) {
61
+            $sponsor = UserService::getInstance()->getUser($sponsorUserId);
62
+            if ($sponsor) {
63
+                $data["sponsor_name"] = $sponsor["name"];
64
+                $data["sponsor_short_name"] = mb_substr($sponsor["name"], -2, 2, "utf-8");
65
+                $data["sponsor_headpic_url"] = $sponsor["avatar"];
66
+                $data["sponsor_department"] = DepartmentService::getInstance()->getDepartmentName($sponsor["department_id"]);
67
+            }
68
+        }
69
+        if ($challengerUserId) {
70
+            $challenger = UserService::getInstance()->getUser($challengerUserId);
71
+            if ($challenger) {
72
+                $data["challenger_name"] = $challenger["name"];
73
+                $data["challenger_short_name"] = mb_substr($challenger["name"], -2, 2, "utf-8");
74
+                $data["challenger_headpic_url"] = $challenger["avatar"];
75
+                $data["challenger_department"] = DepartmentService::getInstance()->getDepartmentName($challenger["department_id"]);
76
+            }
77
+        }
78
+        return $data;
79
+    }
80
+
81
+    /**
82
+     * 开始PK
83
+     * @param $activityId
84
+     * @param $sponsorUserId
85
+     * @param $challengerUserId
86
+     * @return mixed
87
+     */
88
+    public function startPk($activityId,$sponsorUserId, $challengerUserId){
89
+
90
+        try{
91
+
92
+            //如果发起人已经在PK则,返回null
93
+            if(UserService::getInstance()->getUserCurrentWork($sponsorUserId)){
94
+                return null;
95
+            }
96
+
97
+            $brainstorming = BrainstormingService::getInstance()->get($activityId);
98
+            $corpId = $brainstorming["corp_id"];
99
+
100
+            $count = $brainstorming["pk_question_num"];
101
+
102
+            $questionIds = Redis::sRandMember(self::QUESTION_COLLECT.":".$activityId.":pk", $count);
103
+            $data = [
104
+                "corp_id" => $corpId,
105
+                "activity_id" => $activityId,
106
+                "sponsor_user_id" => $sponsorUserId,
107
+                "challenger_user_id" => $challengerUserId,
108
+                "start_time" => time(),
109
+                "knowledge_money" => 0,
110
+                "question_ids" => implode(",", $questionIds),
111
+                "win_user_id" => 0,
112
+                "status" => 3,
113
+                "is_success" => 0
114
+            ];
115
+
116
+            $pkRoomModel = PkRoom::create($data);
117
+            if (!empty($pkRoomModel)) {
118
+                $roomId = $pkRoomModel->room_id;
119
+                $data["create_time"] = time();
120
+                $data["room_id"] = $roomId;
121
+                $data["fd"] = 0;
122
+                $data["question_count"] = $count;
123
+                $data["step"] = 0;
124
+                $data["sponsor_score"] = 0;
125
+                $data["challenger_score"] = 0;
126
+                Redis::hMset(self::PK_ROOMS . ":" . $roomId, $data);
127
+                Redis::expire(self::PK_ROOMS . ":" . $roomId,86400);
128
+                Redis::sAdd(self::PK_RUN, $roomId);
129
+
130
+                $questions = QuestionService::getInstance()->mget($questionIds);
131
+                $step = 1;
132
+                //生成答题
133
+                foreach ($questions as $question) {
134
+                    $this->addAnswer($roomId, $question, $step, $count, $sponsorUserId);
135
+                    $this->addAnswer($roomId, $question, $step, $count, $challengerUserId);
136
+                    $step++;
137
+                }
138
+
139
+                //发送PK开始通知
140
+                $pkUserInfo = $this->getPkUserInfo($sponsorUserId, $challengerUserId);
141
+                $responseData = [
142
+                    "room_id" => $roomId,
143
+                    "knowledge_money" => 0,
144
+                    "status" => 3,
145
+                    "create_time" => time()
146
+                ];
147
+                $responseData = array_merge($responseData, $pkUserInfo);
148
+
149
+
150
+                PushMessageService::getInstance()->pushByUserId("pk", "startNotify", $responseData, $sponsorUserId,0);
151
+                PushMessageService::getInstance()->pushByUserId("pk", "startNotify", $responseData, $challengerUserId,0);
152
+                //设置用户正在PK
153
+                UserService::getInstance()->setUserCurrentWork($sponsorUserId,'pk',$roomId,20);
154
+                UserService::getInstance()->setUserCurrentWork($challengerUserId,'pk',$roomId,20);
155
+
156
+
157
+                //延时3秒发送开始答题
158
+                Redis::hSet(self::PK_ROOMS . ":" . $roomId, "step", 1);
159
+                //处理发起人
160
+                Redis::hSet(self::PK_ROOM_ANSWERS . ":" . $roomId . ":" . $sponsorUserId . ":1" , "answer_start_time", time());
161
+                $this->addAnswerQueue($roomId, 1, $sponsorUserId);
162
+                //处理挑战人
163
+                Redis::hSet(self::PK_ROOM_ANSWERS . ":" . $roomId . ":" . $challengerUserId . ":1", "answer_start_time", time());
164
+                $this->addAnswerQueue($roomId, 1, $challengerUserId);
165
+
166
+                $this->sendQuestion($roomId,1,$sponsorUserId,3);
167
+                $this->sendQuestion($roomId,1,$challengerUserId,3);
168
+
169
+                return $roomId;
170
+            }
171
+        }catch (\Exception $exception){
172
+            Log::info($exception->getTraceAsString());
173
+            return null;
174
+        }
175
+
176
+    }
177
+
178
+
179
+    /**
180
+     * 获取某闯关的第几到题目
181
+     * @param $roomId
182
+     * @param $step
183
+     * @param $userId
184
+     * @return mixed
185
+     */
186
+    public function getQuestion($roomId, $step, $userId)
187
+    {
188
+        $userAnswer = $this->getUserAnswer($roomId, $step, $userId);
189
+        if ($userAnswer) {
190
+            $question = QuestionService::getInstance()->get($userAnswer["question_id"]);
191
+            return [
192
+                "room_id" => $roomId,
193
+                "count" => $userAnswer["count"],
194
+                "step" => $step,
195
+                "question_type" => $question["question_type"],
196
+                "correct_answer" => $question["correct_answer"],
197
+                "question_id" => $userAnswer["question_id"],
198
+                "question_title" => $question["question_title"],
199
+                "question_options" => $question["question_options"]
200
+            ];
201
+        }
202
+        return null;
203
+    }
204
+
205
+
206
+    /**
207
+     * 发送答题
208
+     * @param $roomId
209
+     * @param $step
210
+     * @param $userId
211
+     * @param $delay
212
+     */
213
+    public function sendQuestion($roomId, $step, $userId, $delay = 0)
214
+    {
215
+        $question = $this->getQuestion($roomId, $step, $userId);
216
+        $question["count_down"] = self::COUNT_DOWN;
217
+        //unset($question["correct_answer"]);
218
+        PushMessageService::getInstance()->pushByUserId("pk", "question", $question, $userId,$delay);
219
+    }
220
+
221
+
222
+
223
+    /**
224
+     * 获取用户答题
225
+     * @param $roomId
226
+     * @param $step
227
+     * @param $userId
228
+     * @return array
229
+     */
230
+    public function getUserAnswer($roomId, $step, $userId)
231
+    {
232
+        return Redis::hGetAll(self::PK_ROOM_ANSWERS . ":" . $roomId . ":" . $userId . ":" . $step);
233
+    }
234
+
235
+    /**
236
+     * 添加答题
237
+     * @param $roomId
238
+     * @param $question
239
+     * @param $step
240
+     * @param $count
241
+     * @param $userId
242
+     * @return mixed
243
+     */
244
+    public function addAnswer($roomId, $question, $step, $count, $userId)
245
+    {
246
+        $data = [
247
+            "room_id" => $roomId,
248
+            "step" => $step,
249
+            "question_id" => $question["question_id"],
250
+            "count" => $count,
251
+            "user_answer" => "",
252
+            "user_id" => $userId,
253
+            "correct_answer" => $question["correct_answer"],
254
+            "answer_start_time" => 0,
255
+            "answer_time" => 0,
256
+            "score" => 0,
257
+            "is_over_time" => 0,
258
+            "is_correct" => 0
259
+        ];
260
+        $ret = Redis::hMset(self::PK_ROOM_ANSWERS . ":" . $roomId . ":" . $userId . ":" . $step, $data);
261
+        Redis::expire(self::PK_ROOM_ANSWERS . ":" . $roomId . ":" . $userId . ":" . $step,86400);
262
+        return $ret;
263
+    }
264
+
265
+    /**
266
+     * 加入到答题倒计队列
267
+     * @param $roomId
268
+     * @param $step
269
+     * @param $userId
270
+     * @return mixed
271
+     */
272
+    public function addAnswerQueue($roomId, $step, $userId)
273
+    {
274
+        $countDown = self::COUNT_DOWN;
275
+        if($step==1){
276
+            $countDown+=3;
277
+        }
278
+        Redis::hSet(self::PK_QUEUE, $roomId . "_" . $step . "_" . $userId, $countDown);
279
+    }
280
+}

+ 54 - 0
app/Services/PushMessageService.php Прегледај датотеку

@@ -0,0 +1,54 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/8/16
6
+ * Time: 14:03
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+
12
+use App\Traits\Singleton;
13
+use Illuminate\Support\Facades\Redis;
14
+
15
+class PushMessageService
16
+{
17
+    use Singleton;
18
+    const PUSH_QUEUE_DELAY = "bs_push_queue:delay";
19
+
20
+    /**
21
+     * Websocket 消息发送接口
22
+     * @param $channel
23
+     * @param $action
24
+     * @param $data
25
+     * @param $userId
26
+     * @param int $delay
27
+     * @return null
28
+     */
29
+    public function pushByUserId($channel, $action, $data, $userId, $delay = 0)
30
+    {
31
+        $value = [
32
+            "key" => uniqid(),
33
+            "channel" => $channel,
34
+            "action" => $action,
35
+            "data" => $data,
36
+            "user_id" => $userId
37
+        ];
38
+
39
+        $userOnlineInfo = UserService::getInstance()->getOnlineInfo($userId);
40
+        if(isset($userOnlineInfo["fd"])){
41
+            if($userOnlineInfo["fd"]>0){
42
+                $server = $userOnlineInfo["server"];
43
+                $score = time() + $delay;
44
+                return Redis::zAdd(self::PUSH_QUEUE_DELAY . ":" . $server, $score, json_encode($value));
45
+            }else{
46
+                return null;
47
+            }
48
+        }else{
49
+            return null;
50
+        }
51
+
52
+    }
53
+
54
+}

+ 112 - 0
app/Services/QuestionService.php Прегледај датотеку

@@ -0,0 +1,112 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/5/14
6
+ * Time: 17:55
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Models\Question;
12
+use App\Models\QuestionCategory;
13
+use App\Traits\Singleton;
14
+use Illuminate\Support\Facades\Redis;
15
+class QuestionService
16
+{
17
+    use Singleton;
18
+
19
+    const QUESTIONS = "bs_questions";
20
+    const QUESTION_COLLECT = "bs_question_collect";
21
+    const QUESTION_CLASS = "bs_question_class";
22
+
23
+    public function cache($activityId){
24
+
25
+        $brainstorming = BrainstormingService::getInstance()->get($activityId);
26
+        $questions = Question::where("activity_id",$activityId)->get();
27
+        $classes = QuestionCategory::where("activity_id",$activityId)->get();
28
+
29
+        $mustQuestionCategorys = explode(",",$brainstorming["must_category_ids"]);
30
+        $blockadeQuestionCategorys = explode(",",$brainstorming["blockade_category_ids"]);
31
+        $pkQuestionCategorys = explode(",",$brainstorming["pk_category_ids"]);
32
+
33
+        //删除以前的缓存
34
+        Redis::del(self::QUESTION_COLLECT.":".$activityId.":must");
35
+        Redis::del(self::QUESTION_COLLECT.":".$activityId.":blockade");
36
+        Redis::del(self::QUESTION_COLLECT.":".$activityId.":pk");
37
+        Redis::del(self::QUESTION_CLASS.":".$activityId.":0");
38
+        Redis::del(self::QUESTION_CLASS.":".$activityId.":1");
39
+        foreach ($questions as $question){
40
+            $question = $question->toArray();
41
+            Redis::del(self::QUESTION_COLLECT.":".$activityId.":blockade".":".$question["category_id"]);
42
+        }
43
+
44
+        foreach ($classes as $class) {
45
+            $class = $class -> toArray();
46
+            if (in_array($class["category_id"],$blockadeQuestionCategorys)){
47
+                if ($class["direct_employees"]) {
48
+                    Redis::hMset(self::QUESTION_CLASS . ":" . $activityId.":1", $class['category_id'], json_encode($class));
49
+                } else {
50
+                    Redis::hMset(self::QUESTION_CLASS . ":" . $activityId.":0", $class['category_id'], json_encode($class));
51
+                }
52
+            }
53
+        }
54
+
55
+        foreach ($questions as $question){
56
+            $question = $question->toArray();
57
+            unset($question["update_time"]);
58
+            unset($question["create_time"]);
59
+            Redis::hMset(self::QUESTIONS.":".$question["question_id"], $question);
60
+
61
+            if(in_array($question["category_id"],$mustQuestionCategorys)){
62
+                Redis::sAdd(self::QUESTION_COLLECT.":".$activityId.":must", $question["question_id"]);
63
+                Redis::sAdd(self::QUESTION_COLLECT.":".$activityId.":must", $question["question_id"]);
64
+            }
65
+            if(in_array($question["category_id"],$blockadeQuestionCategorys)){
66
+                Redis::sAdd(self::QUESTION_COLLECT.":".$activityId.":blockade", $question["question_id"]);
67
+                Redis::sAdd(self::QUESTION_COLLECT.":".$activityId.":blockade", $question["question_id"]);
68
+                Redis::sAdd(self::QUESTION_COLLECT.":".$activityId.":blockade".":".$question["category_id"], $question["question_id"]);
69
+            }
70
+            if(in_array($question["category_id"],$pkQuestionCategorys)){
71
+                Redis::sAdd(self::QUESTION_COLLECT.":".$activityId.":pk", $question["question_id"]);
72
+                Redis::sAdd(self::QUESTION_COLLECT.":".$activityId.":pk", $question["question_id"]);
73
+            }
74
+        }
75
+    }
76
+
77
+    public function getClassDirect($activityId){
78
+        return Redis::hGetAll(self::QUESTION_CLASS.":".$activityId.":1");
79
+    }
80
+
81
+    public function getClassNotDirect($activityId){
82
+        return Redis::hGetAll(self::QUESTION_CLASS.":".$activityId.":0");
83
+    }
84
+
85
+    /**
86
+     * 获取单个题目信息
87
+     * @param $questionId
88
+     * @return mixed
89
+     */
90
+    public function get($questionId)
91
+    {
92
+        $data = Redis::hGetAll(self::QUESTIONS.":".$questionId);
93
+        if($data){
94
+            $data["question_options"] = unserialize($data["question_options"]);
95
+        }
96
+        return $data;
97
+    }
98
+
99
+    /**
100
+     * 获取多个题目信息
101
+     * @param array $questionIds
102
+     * @return mixed
103
+     */
104
+    public function mget(array $questionIds)
105
+    {
106
+        $datas = [];
107
+        foreach ($questionIds as $questionId){
108
+            $datas[$questionId] = Redis::hGetAll(self::QUESTIONS.":".$questionId);
109
+        }
110
+        return $datas;
111
+    }
112
+}

+ 93 - 0
app/Services/SmsService.php Прегледај датотеку

@@ -0,0 +1,93 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: gevnc
5
+ * Date: 2018/5/17
6
+ * Time: 14:47
7
+ */
8
+
9
+namespace App\Services;
10
+
11
+use App\Traits\Singleton;
12
+use Aliyun\Core\Config;
13
+use Aliyun\Core\Profile\DefaultProfile;
14
+use Aliyun\Core\DefaultAcsClient;
15
+use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
16
+use Aliyun\Api\Sms\Request\V20170525\SendBatchSmsRequest;
17
+use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
18
+
19
+class SmsService
20
+{
21
+    static $acsClient = null;
22
+
23
+    /**
24
+     * 取得AcsClient
25
+     *
26
+     * @return DefaultAcsClient
27
+     */
28
+    public static function getAcsClient() {
29
+        //产品名称:云通信流量服务API产品,开发者无需替换
30
+        $product = "Dysmsapi";
31
+
32
+        //产品域名,开发者无需替换
33
+        $domain = "dysmsapi.aliyuncs.com";
34
+
35
+        // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
36
+        $accessKeyId = env("ALIYUN_ACCESS_KEY_ID"); // AccessKeyId
37
+
38
+        $accessKeySecret = env("ALIYUN_ACCESS_KEY_SECRET"); // AccessKeySecret
39
+
40
+        // 暂时不支持多Region
41
+        $region = "cn-hangzhou";
42
+
43
+        // 服务结点
44
+        $endPointName = "cn-hangzhou";
45
+
46
+
47
+        if(static::$acsClient == null) {
48
+
49
+            //初始化acsClient,暂不支持region化
50
+            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
51
+
52
+            // 增加服务结点
53
+            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
54
+
55
+            // 初始化AcsClient用于发起请求
56
+            static::$acsClient = new DefaultAcsClient($profile);
57
+        }
58
+        return static::$acsClient;
59
+    }
60
+
61
+    /**
62
+     * 发送短信
63
+     * @return stdClass
64
+     */
65
+    public static function sendSms($phone,$code) {
66
+
67
+        // 初始化SendSmsRequest实例用于设置发送短信的参数
68
+        $request = new SendSmsRequest();
69
+
70
+        //可选-启用https协议
71
+        //$request->setProtocol("https");
72
+
73
+        // 必填,设置短信接收号码
74
+        $request->setPhoneNumbers($phone);
75
+
76
+        // 必填,设置签名名称,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
77
+        $request->setSignName(env("SMS_SIGN_NAME"));
78
+
79
+        // 必填,设置模板CODE,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
80
+        $request->setTemplateCode(env("SMS_TEMPLATE_CODE"));
81
+
82
+        // 可选,设置模板参数, 假如模板中存在变量需要替换则为必填项
83
+        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
84
+            "code"=>$code
85
+        ), JSON_UNESCAPED_UNICODE));
86
+
87
+
88
+        // 发起访问请求
89
+        $acsResponse = static::getAcsClient()->getAcsResponse($request);
90
+
91
+        return $acsResponse;
92
+    }
93
+}

+ 457 - 0
app/Services/TopService.php Прегледај датотеку

@@ -0,0 +1,457 @@
1
+<?php
2
+/**
3
+ * 排行榜
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/27
7
+ * Time: 9:13
8
+ */
9
+
10
+namespace App\Services;
11
+
12
+use App\Models\User;
13
+use App\Traits\Singleton;
14
+use Illuminate\Support\Facades\DB;
15
+use Illuminate\Support\Facades\Redis;
16
+
17
+class TopService
18
+{
19
+    use Singleton;
20
+    const KNOWLEDGE_TOP = "bs_top:km";
21
+    const JOIN_TOP = "bs_top:join";
22
+    const JOIN_RATE_TOP = "bs_top:joinrate";
23
+    const KM_AVG_TOP = "bs_top:kmavg";
24
+    const PK_TOP = "bs_top:users:pk";
25
+    const KM_TOP = "bs_top:users:km";
26
+    const TOP_USERS = "bs_top:users";
27
+
28
+    /**
29
+     * @param $activityId
30
+     */
31
+    protected function cacheDepartmentTop($activityId){
32
+
33
+        $datas = DB::select("select count(*) as user_num,sum(is_blockade_success_copy) as sum_is_blockade_success,sum(knowledge_money)as sum_knowledge_money,department_id,avg(knowledge_money) as avg_knowledge_money from bs_users where department_id>0 and status=1 and activity_id={$activityId} 
34
+GROUP BY department_id");
35
+
36
+        foreach ($datas as $data){
37
+            $joinRate = 0;
38
+            if($data->user_num>0){
39
+                $joinRate = ($data->sum_is_blockade_success/$data->user_num)*100;
40
+            }
41
+            Redis::zAdd(self::KNOWLEDGE_TOP.":".$activityId,$data->sum_knowledge_money,$data->department_id);
42
+            Redis::zAdd(self::JOIN_TOP.":".$activityId,$data->sum_is_blockade_success,$data->department_id);
43
+            Redis::zAdd(self::JOIN_RATE_TOP.":".$activityId,$joinRate,$data->department_id);
44
+            Redis::zAdd(self::KM_AVG_TOP.":".$activityId,$data->avg_knowledge_money,$data->department_id);
45
+        }
46
+
47
+        Redis::expire(self::KNOWLEDGE_TOP.":".$activityId,300);
48
+        Redis::expire(self::JOIN_RATE_TOP.":".$activityId,300);
49
+        Redis::expire(self::JOIN_TOP.":".$activityId,300);
50
+        Redis::expire(self::KM_AVG_TOP.":".$activityId,300);
51
+
52
+    }
53
+
54
+    /**
55
+     * 个人知识币全行排行榜信息
56
+     * @param $activityId
57
+     * @param string $limit
58
+     * @return mixed
59
+     */
60
+    public function personKmTop($activityId,$limit = "")
61
+    {
62
+       return $this->getKmTop($activityId,$limit);
63
+    }
64
+
65
+    /**
66
+     * 得到用户在全行的排名
67
+     * @param $activityId
68
+     * @param $userId
69
+     * @return mixed
70
+     */
71
+    public function personKmRank($activityId,$userId)
72
+    {
73
+        return $this->getKmRank($activityId,$userId);
74
+    }
75
+
76
+    /**
77
+     * 所有用户在全行的PK排名
78
+     * @param $activityId
79
+     * @param string $limit
80
+     * @return mixed
81
+     */
82
+    public function personPktop($activityId,$limit=""){
83
+        return $this->getPkTop($activityId,$limit);
84
+    }
85
+
86
+    /**
87
+     * 当前用户在全行的排名
88
+     * @param $activityId
89
+     * @param $userId
90
+     * @return int
91
+     */
92
+    public function personPkRank($activityId,$userId)
93
+    {
94
+        return $this->getPkRank($activityId,$userId);
95
+    }
96
+
97
+    /**
98
+     * 现在1000名的知识币
99
+     * 可以获得奖项的知识币
100
+     * @param $activityId
101
+     * @param int $rank
102
+     * @return int
103
+     */
104
+    public function prizeKmRank($activityId,$rank = 1000)
105
+    {
106
+        $users = User::where("activity_id",$activityId)->where("status",1)
107
+                                                        ->where("is_blockade_success",1)
108
+                                                        ->orderBy("knowledge_money","desc")
109
+                                                        ->pluck("knowledge_money","user_id");
110
+        $users = collect($users)->toArray();
111
+        $i=0;
112
+        foreach ($users as $key=>$knowledgeMoney){
113
+            $i++;
114
+            if($i==$rank){
115
+                return $knowledgeMoney;
116
+            }
117
+        }
118
+        return 0;
119
+    }
120
+
121
+    /**
122
+     * 个人知识币分行排行榜信息
123
+     * @param $activityId
124
+     * @param $departmentId
125
+     * @param string $limit
126
+     * @return mixed
127
+     */
128
+    public function personKmDepartmentTop($activityId,$departmentId,$limit = "")
129
+    {
130
+
131
+        $userIds = DepartmentService::getInstance()->getUserIdsByDepartmentId($departmentId);
132
+        $users = [];
133
+        if($userIds){
134
+            $users = $this->getUsers($activityId,collect($userIds)->toArray());
135
+        }
136
+        if($limit>0){
137
+            $users = collect($users)->sortByDesc("knowledge_money")->values()->take($limit);
138
+        }else{
139
+            $users = collect($users)->sortByDesc("knowledge_money")->values()->all();
140
+        }
141
+
142
+        return $users;
143
+
144
+    }
145
+
146
+
147
+    /**
148
+     * 得到用户在分行的排名
149
+     * @param $activityId
150
+     * @param $userId
151
+     * @param $departmentId
152
+     * @return mixed
153
+     */
154
+    public function personKmDepartmentRank($activityId,$userId, $departmentId)
155
+    {
156
+        $userIds = DepartmentService::getInstance()->getUserIdsByDepartmentId($departmentId);
157
+        $users = [];
158
+        if($userIds){
159
+            $users = $this->getUsers($activityId,collect($userIds)->toArray());
160
+        }
161
+        $users = collect($users)->sortByDesc("knowledge_money")->values()->all();
162
+        $i=0;
163
+        foreach ($users as $user){
164
+            $i++;
165
+            if($user["user_id"]==$userId){
166
+                return $i;
167
+            }
168
+        }
169
+    }
170
+
171
+    /**
172
+     * 获取所有分行员工完成必答排行
173
+     * @param $activityId
174
+     * @param string $limit
175
+     * @return mixed
176
+     */
177
+    public function departmentJoinTop($activityId,$limit = "")
178
+    {
179
+        $redisKey = self::JOIN_TOP . ":".$activityId;
180
+        if(!Redis::exists($redisKey)){
181
+            $this->cacheDepartmentTop($activityId);
182
+        }
183
+        $options = array('withscores' => true);
184
+        if ($limit) {
185
+            $options["limit"] = $limit;
186
+        }
187
+        return Redis::zRevrangebyscore($redisKey, "+inf", "-inf", $options);
188
+    }
189
+
190
+    /**
191
+     * 获取所有分行的总知识币
192
+     * @param $activityId
193
+     * @param string $limit
194
+     * @return mixed
195
+     */
196
+    public function departmentKmTop($activityId,$limit="")
197
+    {
198
+        $redisKey = self::KNOWLEDGE_TOP . ":".$activityId;
199
+        if(!Redis::exists($redisKey)){
200
+            $this->cacheDepartmentTop($activityId);
201
+        }
202
+        $options = array('withscores' => true);
203
+        if ($limit) {
204
+            $options["limit"] = $limit;
205
+        }
206
+        return Redis::zRevrangebyscore($redisKey, "+inf", "-inf", $options);
207
+    }
208
+
209
+    /**
210
+     * 获取分行参与率的排行榜
211
+     * @param $activityId
212
+     * @param string $limit
213
+     * @return
214
+     */
215
+    public function departmentJoinRateTop($activityId,$limit = "")
216
+    {
217
+        $redisKey = self::JOIN_RATE_TOP . ":".$activityId;
218
+        if(!Redis::exists($redisKey)){
219
+            $this->cacheDepartmentTop($activityId);
220
+        }
221
+        $options = array('withscores' => true);
222
+        if ($limit) {
223
+            $options["limit"] = $limit;
224
+        }
225
+        return Redis::zRevrangebyscore($redisKey, "+inf", "-inf", $options);
226
+    }
227
+
228
+    /**
229
+     * 获取分行平均分排行榜
230
+     * @param $limit
231
+     * @return mixed
232
+     */
233
+    public function departmentKmAvgTop($activityId,$limit = "")
234
+    {
235
+        $redisKey = self::KM_AVG_TOP . ":".$activityId;
236
+        if(!Redis::exists($redisKey)){
237
+            $this->cacheDepartmentTop($activityId);
238
+        }
239
+        $options = array('withscores' => true);
240
+        if ($limit) {
241
+            $options["limit"] = $limit;
242
+        }
243
+        return Redis::zRevrangebyscore($redisKey, "+inf", "-inf", $options);
244
+    }
245
+
246
+    /**
247
+     * 某分行的排名
248
+     * @param $activityId
249
+     * @param $departmentId
250
+     * @return array
251
+     */
252
+    public function departmentJoinRateRank($activityId,$departmentId)
253
+    {
254
+        $redisKey = self::JOIN_RATE_TOP . ":".$activityId;
255
+        if(!Redis::exists($redisKey)){
256
+            $this->cacheDepartmentTop($activityId);
257
+        }
258
+
259
+        $rank = Redis::zRevrank($redisKey, $departmentId);
260
+        if (is_null($rank)) {
261
+            return ["index" => 0, "rate" => 0];
262
+        } else {
263
+            $rate = Redis::zScore($redisKey, $departmentId);
264
+            return ["index" => $rank + 1, "rate" => $rate];
265
+        }
266
+    }
267
+
268
+    /**
269
+     * 某分行的排名
270
+     * @param $departmentId
271
+     * @return array
272
+     */
273
+    public function departmentKmAvgRank($activityId,$departmentId)
274
+    {
275
+        $redisKey = self::KM_AVG_TOP . ":".$activityId;
276
+        if(!Redis::exists($redisKey)){
277
+            $this->cacheDepartmentTop($activityId);
278
+        }
279
+
280
+        $rank = Redis::zRevrank($redisKey, $departmentId);
281
+        if (is_null($rank)) {
282
+            return ["index" => 0, "avg_knowledge_money" => 0];
283
+        } else {
284
+            $avgKm = Redis::zScore($redisKey, $departmentId);
285
+            return ["index" => $rank + 1, "avg_knowledge_money" => round($avgKm,2)];
286
+        }
287
+    }
288
+
289
+    /**
290
+     * 获得用户排行信息
291
+     * @param $activityId
292
+     * @param array $userIds
293
+     * @return array
294
+     */
295
+    public function getUsers($activityId,$userIds=[]){
296
+        $redisKey = self::TOP_USERS.":".$activityId;
297
+        if(!Redis::exists($redisKey)){
298
+            $departments = DepartmentService::getInstance()->all($activityId);
299
+            $pagesize = 5000;
300
+            $count = User::where("activity_id",$activityId)->where("status",1)->count();
301
+            $pageCount = ceil($count/$pagesize);
302
+            for ($page=0;$page<$pageCount;$page++){
303
+                $users = User::where("activity_id",$activityId)->where("status",1)->offset($page*$pagesize)->limit($pagesize)->get([
304
+                    "user_id","name","avatar","department_id","knowledge_money","user_level","user_star"
305
+                ]);
306
+
307
+                $redisData = [];
308
+                foreach ($users as $user){
309
+                    $user = collect($user)->toArray();
310
+                    $user["department_name"] = empty($departments[$user["department_id"]])? "":$departments[$user["department_id"]];
311
+                    $redisData[$user["user_id"]] = json_encode($user,256);
312
+                }
313
+                if($redisData){
314
+                    Redis::hmset($redisKey,$redisData);
315
+                }
316
+            }
317
+            Redis::expire($redisKey,864000);
318
+        }
319
+        if(empty($userIds)){
320
+            $users = Redis::hgetall($redisKey);
321
+        }else{
322
+            $users = Redis::hmget($redisKey,$userIds);
323
+        }
324
+        $datas = [];
325
+        foreach ($users as $key=>$val){
326
+            $datas[$key] = json_decode($val,true);
327
+        }
328
+        return $datas;
329
+    }
330
+
331
+
332
+    /**
333
+     * 更新用户的排名信息
334
+     * @param $userId
335
+     * @return mixed
336
+     */
337
+
338
+    public function updateUserTop($userId){
339
+        $user = UserService::getInstance()->getUser($userId,"",true);
340
+        if($user){
341
+            $activityId = $user["activity_id"];
342
+            $redisData = [
343
+                "user_id" => $userId,
344
+                "name" => $user["name"],
345
+                "avatar" => $user["avatar"],
346
+                "department_id" => $user["department_id"],
347
+                "department_name" => DepartmentService::getInstance()->getDepartmentName($user["department_id"]),
348
+                "knowledge_money" => $user["knowledge_money"],
349
+                "user_level" => $user["user_level"],
350
+                "user_star" => $user["user_star"]
351
+            ];
352
+            if(Redis::exists(self::TOP_USERS . ":".$activityId)) {
353
+                Redis::hset(self::TOP_USERS . ":" . $activityId, $userId, json_encode($redisData, 256));
354
+            }
355
+            if(Redis::exists(self::KM_TOP . ":".$activityId)){
356
+                Redis::zadd(self::KM_TOP . ":".$activityId,$user["knowledge_money"],$userId);
357
+            }
358
+            if(Redis::exists(self::PK_TOP . ":".$activityId)) {
359
+                Redis::zadd(self::PK_TOP . ":" . $activityId, $user["user_level"] * 1000 + $user["user_star"], $userId);
360
+            }
361
+            return true;
362
+        }
363
+        return false;
364
+    }
365
+
366
+
367
+    /**
368
+     * 取用户的km段位排名
369
+     * @param $activityId
370
+     * @param $userId
371
+     * @return int
372
+     */
373
+    public function getKmRank($activityId,$userId){
374
+        $redisKey = self::KM_TOP . ":".$activityId;
375
+        $this->getKmTop($activityId,1);
376
+        $rank = Redis::zRevrank($redisKey, $userId);
377
+        if (is_null($rank)) {
378
+            return 0;
379
+        } else {
380
+            return $rank + 1;
381
+        }
382
+    }
383
+
384
+
385
+    /**
386
+     * 取用户的PK段位排名
387
+     * @param $activityId
388
+     * @param $userId
389
+     * @return int
390
+     */
391
+    public function getPkRank($activityId,$userId){
392
+        $redisKey = self::PK_TOP . ":".$activityId;
393
+        $this->getPkTop($activityId,1);
394
+        $rank = Redis::zRevrank($redisKey, $userId);
395
+        if (is_null($rank)) {
396
+            return 0;
397
+        } else {
398
+            return $rank + 1;
399
+        }
400
+    }
401
+
402
+    /**
403
+     * PK段位排行榜
404
+     * @param $activityId
405
+     * @param int $limit
406
+     * @return mixed
407
+     */
408
+    public function getPkTop($activityId,$limit=100){
409
+        $redisKey = self::PK_TOP . ":".$activityId;
410
+        if(!Redis::exists($redisKey)){
411
+            $users = $this->getUsers($activityId);
412
+            foreach ($users as $key=>$val){
413
+                Redis::zadd($redisKey,$val["user_level"]*1000+$val["user_star"],$key);
414
+            }
415
+            Redis::expire($redisKey,84600);
416
+        }
417
+
418
+        $options = [];
419
+        if ($limit) {
420
+            $options["limit"] = [0,$limit];
421
+        }
422
+        $datas = [];
423
+        $userIds =  Redis::zRevrangebyscore($redisKey, "+inf", "-inf", $options);
424
+        if($userIds){
425
+            $datas = $this->getUsers($activityId,$userIds);
426
+        }
427
+        return $datas;
428
+    }
429
+
430
+    /**
431
+     * 知识币排行
432
+     * @param $activityId
433
+     * @param int $limit
434
+     * @return mixed
435
+     */
436
+    public function getKmTop($activityId,$limit=100){
437
+        $redisKey = self::KM_TOP . ":".$activityId;
438
+        if(!Redis::exists($redisKey)){
439
+            $users = $this->getUsers($activityId);
440
+            foreach ($users as $key=>$val){
441
+                Redis::zadd($redisKey,$val["knowledge_money"],$key);
442
+            }
443
+            Redis::expire($redisKey,84600);
444
+        }
445
+
446
+        $options = [];
447
+        if ($limit) {
448
+            $options["limit"] = [0,$limit];
449
+        }
450
+        $userIds =  Redis::zRevrangebyscore($redisKey, "+inf", "-inf", $options);
451
+        $datas = [];
452
+        if($userIds){
453
+            $datas = $this->getUsers($activityId,$userIds);
454
+        }
455
+        return $datas;
456
+    }
457
+}

+ 350 - 0
app/Services/UserService.php Прегледај датотеку

@@ -0,0 +1,350 @@
1
+<?php
2
+/**
3
+ * User Service
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/23
7
+ * Time: 19:20
8
+ */
9
+
10
+namespace App\Services;
11
+
12
+use App\Models\Corp;
13
+use App\Models\Department;
14
+use App\Models\User;
15
+use App\Traits\Singleton;
16
+use Illuminate\Support\Facades\DB;
17
+use Illuminate\Support\Facades\Log;
18
+use Illuminate\Support\Facades\Redis;
19
+
20
+class UserService
21
+{
22
+
23
+    use Singleton;
24
+
25
+    const REDIS_USERS = "bs_users";
26
+    const REDIS_USERS_OPEN_ID = "bs_users_open_id";
27
+    const REDIS_AGH_GCORP = "agh_gcorp";
28
+    const WHITE_LIST = "bs_white_list";
29
+    const REDIS_USERS_GUID = "bs_user_guid";
30
+    const REDIS_AGH_GUID = "agh_guid";
31
+    const USER_CURRENT_WORK = "bs_user_current_work";
32
+    const WEBSOCKET_USERS = "bs_websocket_users";
33
+
34
+    public function auth2($activityId, $openid, $avatar, $nickname, $platform)
35
+    {
36
+
37
+        try {
38
+            $key = self::REDIS_USERS_OPEN_ID . ":" . $activityId . ":" . $openid;
39
+            $userId = Redis::get($key);
40
+            if (empty($userId)) {
41
+                $user = User::where("activity_id", $activityId)->where("open_id", $openid)->where("status", 1)->first();
42
+                if (empty($user)) {
43
+                    //此微信之前是否有绑定过手机号码
44
+                    $phones = DB::table("agh_wechats")->where("open_id", $openid)->pluck("phone")->toArray();
45
+                    if (!empty($phones)) {
46
+                        $user = User::where("activity_id", $activityId)->whereIn("phone", $phones)->first();
47
+                    }
48
+                }
49
+
50
+                if (!empty($user)) {
51
+                    if (!empty($openid)) $user->open_id = $openid;
52
+                    if (!empty($avatar)) $user->avatar = $avatar;
53
+                    if (!empty($nickname)) $user->nickname = $nickname;
54
+                    $user->platform = $platform;
55
+                    $user->save();
56
+                    $user = collect($user)->toArray();
57
+                    $user["department_name"] = DepartmentService::getInstance()->getDepartmentName($user["department_id"]);
58
+                    Redis::hMset(self::REDIS_USERS . ":" . $user["user_id"], $user);
59
+                    Redis::expire(self::REDIS_USERS . ":" . $user["user_id"], 600);
60
+                    Redis::set($key, $user["user_id"]);
61
+                    Redis::expire($key, 600);
62
+                    return $user;
63
+                }
64
+
65
+            } else {
66
+                return $this->getUser($userId);
67
+            }
68
+        } catch (\Exception $exception) {
69
+            Log::info($exception->getMessage());
70
+        }
71
+        return null;
72
+
73
+    }
74
+
75
+    /**
76
+     * 判断是否在白名单里面
77
+     */
78
+    public function isWhiteList($ystId)
79
+    {
80
+        return Redis::sismember(self::WHITE_LIST, $ystId);
81
+    }
82
+
83
+    /**
84
+     * 获得用户信息
85
+     * @param $userId
86
+     * @param string $hashKey
87
+     * @param bool $force 强制从数据库里面获取
88
+     * @return mixed
89
+     */
90
+    public function getUser($userId, $hashKey = "", $force = false)
91
+    {
92
+        $key = self::REDIS_USERS . ":" . $userId;
93
+        if (!Redis::exists($key) || $force) {
94
+            $user = User::find($userId);
95
+            if ($user) {
96
+                $user = collect($user)->toArray();
97
+                $user["department_name"] = DepartmentService::getInstance()->getDepartmentName($user["department_id"]);
98
+                Redis::hMset($key, $user);
99
+                Redis::expire($key, 600);
100
+            } else {
101
+                return null;
102
+            }
103
+        }
104
+        if (empty($hashKey)) {
105
+            return Redis::hGetAll(self::REDIS_USERS . ":" . $userId);
106
+        } else {
107
+            return Redis::hGet(self::REDIS_USERS . ":" . $userId, $hashKey);
108
+        }
109
+    }
110
+
111
+    /**
112
+     * 根据openId增加用户
113
+     * @param $activityId
114
+     * @param $openid
115
+     * @param $avatar
116
+     * @param $nickname
117
+     * @param $platform
118
+     * @param string $departmentName
119
+     * @return bool
120
+     */
121
+    public function addUserByOpenId($activityId, $openid, $avatar, $nickname, $platform, $departmentName = "")
122
+    {
123
+        $activity = BrainstormingService::getInstance()->get($activityId);
124
+        $departmentId = 0;
125
+
126
+        if (!empty($departmentName)) {
127
+            $department = Department::where("activity_id", $activityId)->where("department_name", $departmentName)->first();
128
+            if (empty($department)) {
129
+                $data = [];
130
+                $data['activity_id'] = $activityId;
131
+                $data["corp_id"] = $activity["corp_id"];
132
+                $data["department_name"] = $departmentName;
133
+                $department = Department::create($data);
134
+            } else {
135
+                if ($department->status == 0) {
136
+                    $department->status = 1;
137
+                    $department->save();
138
+                }
139
+            }
140
+            $departmentId = empty($department) ? 0 : $department->department_id;
141
+        }
142
+
143
+
144
+        $user = User::where("activity_id", $activityId)
145
+            ->where("open_id", $openid)->where("status", 1)->first();
146
+
147
+        if (empty($user)) {
148
+            $query = [];
149
+            $query['activity_id'] = $activityId;
150
+            $query["corp_id"] = $activity["corp_id"];
151
+            $query['open_id'] = $openid;
152
+            $query['guid'] = $openid;
153
+            $query['name'] = $nickname;
154
+            $query['nickname'] = "";
155
+            $query['department_id'] = $departmentId;
156
+            $query['email'] = "";
157
+            $query['phone'] = "";
158
+            $query['avatar'] = $avatar;
159
+            $query['platform'] = $platform;
160
+
161
+            User::create($query);
162
+        } else {
163
+            if ($departmentId != $user->department_id) {
164
+                $user->department_id = $departmentId;
165
+                $user->save();
166
+            }
167
+        }
168
+        return true;
169
+    }
170
+
171
+    /**
172
+     * 使用Guid的用户信息,新增用户
173
+     * @param $activityId int 活动ID
174
+     * @param $guid int 爱关怀的用户ID
175
+     * @param $gCorpId
176
+     * @param bool $hasDepartment 是否需要新增部门
177
+     * @return mixed
178
+     */
179
+    public function addUserByGuid($activityId, $guid, $gCorpId, $hasDepartment = false)
180
+    {
181
+
182
+        $gUser = Redis::get(self::REDIS_AGH_GUID . ":" . $guid);
183
+        $brainstorming = BrainstormingService::getInstance()->get($activityId);
184
+        $gCorp = $this->getCorpByGcorpId($gCorpId);
185
+        $corpId = isset($gCorp["corp_id"]) ? $gCorp["corp_id"] : 0;
186
+        if ($brainstorming["corp_id"] != $corpId) {
187
+            return ["error" => 1000, "corp_short_name" => $brainstorming["corp_short_name"]];
188
+        }
189
+
190
+        if ($gUser) {
191
+            $gUser = json_decode($gUser, true);
192
+            $departmentId = 0;
193
+            if ($hasDepartment) {
194
+                if (!empty($gCorp)) {
195
+                    $department = Department::where("activity_id", $activityId)
196
+                        ->where("corp_id", $gCorp["corp_id"])->first();
197
+                    if (empty($department)) {
198
+                        $department = Department::create([
199
+                            "activity_id" => $activityId,
200
+                            "corp_id" => $gCorp["corp_id"],
201
+                            "department_name" => $gCorp["corp_short_name"]
202
+                        ]);
203
+                    }
204
+                    if ($department) {
205
+                        $departmentId = $department->department_id;
206
+                    }
207
+                }
208
+            }
209
+
210
+
211
+            $user = User::where("activity_id", $activityId)
212
+                ->where("guid", $guid)->where("status", 1)->first();
213
+
214
+            if (empty($user)) {
215
+                foreach ($gUser["subUids"] as $subUser) {
216
+                    if ($subUser["corpId"] == $gCorpId) {
217
+                        $query = [];
218
+                        $query['corp_id'] = $gCorp["corp_id"];
219
+                        $query['activity_id'] = $activityId;
220
+                        $query['guid'] = $guid;
221
+                        $query['name'] = $subUser['realName'];
222
+                        $query['nickname'] = "";
223
+                        $query['department_id'] = $departmentId;
224
+                        $query['email'] = $subUser['email'];
225
+                        $query['phone'] = $subUser['mobile'];
226
+                        $query['avatar'] = "";
227
+                        $query['platform'] = "";
228
+
229
+                        User::create($query);
230
+                        break;
231
+                    }
232
+                }
233
+            }
234
+
235
+        }
236
+        return ["error" => 0, "corp_name" => $brainstorming["corp_name"]];
237
+    }
238
+
239
+    /**
240
+     * @param $gCorpId
241
+     * @return mixed
242
+     */
243
+    public function getCorpByGcorpId($gCorpId)
244
+    {
245
+        $redisKey = self::REDIS_AGH_GCORP . ":" . $gCorpId;
246
+        $gcorp = Redis::get($redisKey);
247
+        if (empty($gcorp)) {
248
+            $gcorp = Corp::where("source_id", $gCorpId)->where("source_type", "agh")->first();
249
+            if ($gcorp) {
250
+                $gcorp = collect($gcorp)->toArray();
251
+                Redis::set($redisKey, json_encode($gcorp));
252
+                Redis::expire($redisKey, 300);
253
+            }
254
+        } else {
255
+            $gcorp = json_decode($gcorp, true);
256
+        }
257
+        return $gcorp;
258
+    }
259
+
260
+    /**
261
+     * 使用guid认证
262
+     * @param $activityId
263
+     * @param $openid
264
+     * @param $avatar
265
+     * @param $nickname
266
+     * @param $platform
267
+     * @param $guid
268
+     * @return array|mixed|null
269
+     */
270
+
271
+    public function authByGuid($activityId, $openid, $avatar, $nickname, $platform, $guid)
272
+    {
273
+
274
+        try {
275
+            $key = self::REDIS_USERS_GUID . ":" . $activityId . ":" . $guid;
276
+            $userId = Redis::get($key);
277
+            if (empty($userId)) {
278
+                $user = User::where("activity_id", $activityId)->where("guid", $guid)->where("status", 1)->first();
279
+                if (!empty($user)) {
280
+                    if (!empty($avatar)) $user->avatar = $avatar;
281
+                    if (!empty($nickname)) $user->nickname = $nickname;
282
+                    if ($user->name == "***") $user->name = $nickname;
283
+                    $user->open_id = $openid;
284
+                    $user->platform = $platform;
285
+                    $user->save();
286
+                    $user = collect($user)->toArray();
287
+                    $user["department_name"] = DepartmentService::getInstance()->getDepartmentName($user["department_id"]);
288
+                    Redis::hMset(self::REDIS_USERS . ":" . $user["user_id"], $user);
289
+                    Redis::expire(self::REDIS_USERS . ":" . $user["user_id"], 600);
290
+                    Redis::set($key, $user["user_id"]);
291
+                    Redis::expire($key, 600);
292
+                    return $user;
293
+                }
294
+
295
+            } else {
296
+                return $this->getUser($userId);
297
+            }
298
+        } catch (\Exception $exception) {
299
+            Log::info($exception->getMessage());
300
+        }
301
+        return null;
302
+
303
+    }
304
+
305
+    /**
306
+     * 获得用户在线信息
307
+     * @param $userId
308
+     * @return mixed
309
+     */
310
+    public function getOnlineInfo($userId)
311
+    {
312
+        return Redis::hGetAll(self::WEBSOCKET_USERS . ":" . $userId);
313
+    }
314
+
315
+
316
+    /**
317
+     * 设置现在用户正在进行的事项,如答题,PK
318
+     * @param $userId
319
+     * @param $channel
320
+     * @param $id
321
+     * @param int $timeout
322
+     */
323
+    public function setUserCurrentWork($userId, $channel, $id, $timeout = 600)
324
+    {
325
+        Redis::hMset(self::USER_CURRENT_WORK . ":" . $userId, [
326
+            "channel" => $channel,
327
+            "id" => $id
328
+        ]);
329
+        Redis::expire(self::USER_CURRENT_WORK . ":" . $userId, $timeout);
330
+    }
331
+
332
+    /**
333
+     * 清除用户的工作项
334
+     * @param $userId
335
+     */
336
+    public function unsetUserCurrentWork($userId)
337
+    {
338
+        Redis::del(self::USER_CURRENT_WORK . ":" . $userId);
339
+    }
340
+
341
+    /**
342
+     * 获取用户当前正在工作项
343
+     * @param $userId
344
+     * @return mixed
345
+     */
346
+    public function getUserCurrentWork($userId)
347
+    {
348
+        return Redis::hGetAll(self::USER_CURRENT_WORK . ":" . $userId);
349
+    }
350
+}

+ 23 - 0
app/Traits/Singleton.php Прегледај датотеку

@@ -0,0 +1,23 @@
1
+<?php
2
+
3
+/**
4
+ * Created by PhpStorm.
5
+ * User: guanxl
6
+ * Date: 2018/3/22
7
+ * Time: 19:57
8
+ */
9
+namespace App\Traits;
10
+
11
+
12
+trait Singleton
13
+{
14
+    private static $instance;
15
+
16
+    static function getInstance(...$args)
17
+    {
18
+        if(!isset(self::$instance)){
19
+            self::$instance = new static(...$args);
20
+        }
21
+        return self::$instance;
22
+    }
23
+}

+ 35 - 0
artisan Прегледај датотеку

@@ -0,0 +1,35 @@
1
+#!/usr/bin/env php
2
+<?php
3
+
4
+use Symfony\Component\Console\Input\ArgvInput;
5
+use Symfony\Component\Console\Output\ConsoleOutput;
6
+
7
+/*
8
+|--------------------------------------------------------------------------
9
+| Create The Application
10
+|--------------------------------------------------------------------------
11
+|
12
+| First we need to get an application instance. This creates an instance
13
+| of the application / container and bootstraps the application so it
14
+| is ready to receive HTTP / Console requests from the environment.
15
+|
16
+*/
17
+
18
+$app = require __DIR__.'/bootstrap/app.php';
19
+
20
+/*
21
+|--------------------------------------------------------------------------
22
+| Run The Artisan Application
23
+|--------------------------------------------------------------------------
24
+|
25
+| When we run the console application, the current CLI command will be
26
+| executed in this console and the response sent back to a terminal
27
+| or another output device for the developers. Here goes nothing!
28
+|
29
+*/
30
+
31
+$kernel = $app->make(
32
+    'Illuminate\Contracts\Console\Kernel'
33
+);
34
+
35
+exit($kernel->handle(new ArgvInput, new ConsoleOutput));

+ 115 - 0
bootstrap/app.php Прегледај датотеку

@@ -0,0 +1,115 @@
1
+<?php
2
+
3
+require_once __DIR__.'/../vendor/autoload.php';
4
+
5
+try {
6
+    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
7
+} catch (Dotenv\Exception\InvalidPathException $e) {
8
+    //
9
+}
10
+
11
+/*
12
+|--------------------------------------------------------------------------
13
+| Create The Application
14
+|--------------------------------------------------------------------------
15
+|
16
+| Here we will load the environment and create the application instance
17
+| that serves as the central piece of this framework. We'll use this
18
+| application as an "IoC" container and router for this framework.
19
+|
20
+*/
21
+
22
+$app = new Laravel\Lumen\Application(
23
+    realpath(__DIR__.'/../')
24
+);
25
+
26
+$app->configure('errcode');
27
+$app->configure('errmsg');
28
+
29
+$app->withFacades();
30
+
31
+$app->withEloquent();
32
+
33
+/*
34
+|--------------------------------------------------------------------------
35
+| Register Container Bindings
36
+|--------------------------------------------------------------------------
37
+|
38
+| Now we will register a few bindings in the service container. We will
39
+| register the exception handler and the console kernel. You may add
40
+| your own bindings here if you like or you can make another file.
41
+|
42
+*/
43
+
44
+$app->singleton(
45
+    Illuminate\Contracts\Debug\ExceptionHandler::class,
46
+    App\Exceptions\Handler::class
47
+);
48
+
49
+$app->singleton(
50
+    Illuminate\Contracts\Console\Kernel::class,
51
+    App\Console\Kernel::class
52
+);
53
+
54
+$app->singleton('redisLog',function (){
55
+    $redis = new \Redis();
56
+    $redis->connect(env("REDIS_HOST_LOG"), env("REDIS_PORT_LOG"));
57
+    if(!empty(env("REDIS_PASSWORD_LOG"))) $redis->auth(env("REDIS_PASSWORD_LOG"));
58
+    return $redis;
59
+});
60
+
61
+/*
62
+|--------------------------------------------------------------------------
63
+| Register Middleware
64
+|--------------------------------------------------------------------------
65
+|
66
+| Next, we will register the middleware with the application. These can
67
+| be global middleware that run before and after each request into a
68
+| route or middleware that'll be assigned to some specific routes.
69
+|
70
+*/
71
+
72
+ $app->middleware([
73
+
74
+ ]);
75
+
76
+ $app->routeMiddleware([
77
+
78
+ ]);
79
+// $app->routeMiddleware([
80
+//     'auth' => App\Http\Middleware\Authenticate::class,
81
+// ]);
82
+
83
+/*
84
+|--------------------------------------------------------------------------
85
+| Register Service Providers
86
+|--------------------------------------------------------------------------
87
+|
88
+| Here we will register all of the application's service providers which
89
+| are used to bind services into the container. Service providers are
90
+| totally optional, so you are not required to uncomment this line.
91
+|
92
+*/
93
+
94
+// $app->register(App\Providers\AppServiceProvider::class);
95
+// $app->register(App\Providers\AuthServiceProvider::class);
96
+// $app->register(App\Providers\EventServiceProvider::class);
97
+$app->register(Illuminate\Redis\RedisServiceProvider::class);
98
+/*
99
+|--------------------------------------------------------------------------
100
+| Load The Application Routes
101
+|--------------------------------------------------------------------------
102
+|
103
+| Next we will include the routes file so that they can all be added to
104
+| the application. This will provide all of the URLs the application
105
+| can respond to, as well as the controllers that may handle them.
106
+|
107
+*/
108
+
109
+$app->router->group([
110
+    'namespace' => 'App\Http\Controllers',
111
+], function ($router) {
112
+    require __DIR__.'/../routes/web.php';
113
+});
114
+
115
+return $app;

+ 46 - 0
composer.json Прегледај датотеку

@@ -0,0 +1,46 @@
1
+{
2
+    "name": "brainstorming backend",
3
+    "description": "brainstorming backend",
4
+    "keywords": ["brainstorming", "backend", "api"],
5
+    "license": "MIT",
6
+    "type": "project",
7
+    "require": {
8
+        "laravel/lumen-framework": "5.6.*",
9
+        "vlucas/phpdotenv": "~2.2",
10
+        "illuminate/redis": "^5.6",
11
+        "qiniu/php-sdk": "^7.2"
12
+    },
13
+    "require-dev": {
14
+        "fzaninotto/faker": "~1.4",
15
+        "phpunit/phpunit": "~6.0",
16
+        "mockery/mockery": "~1.0"
17
+    },
18
+    "autoload": {
19
+        "psr-4": {
20
+            "App\\": "app/",
21
+            "Aliyun\\": "app/Libs/Aliyun"
22
+        }
23
+    },
24
+    "autoload-dev": {
25
+        "classmap": [
26
+            "tests/",
27
+            "database/"
28
+        ]
29
+    },
30
+    "scripts": {
31
+        "post-root-package-install": [
32
+            "php -r \"copy('.env.example', '.env');\""
33
+        ]
34
+    },
35
+    "minimum-stability": "dev",
36
+    "prefer-stable": true,
37
+    "config": {
38
+        "optimize-autoloader": true
39
+    },
40
+    "repositories": {
41
+        "packagist": {
42
+            "type": "composer",
43
+            "url": "https://packagist.phpcomposer.com"
44
+        }
45
+    }
46
+}

Разлика између датотеке није приказан због своје велике величине
+ 4073 - 0
composer.lock


+ 15 - 0
config/errCode.php Прегледај датотеку

@@ -0,0 +1,15 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/5/18
6
+ * Time: 18:06
7
+ */
8
+return [
9
+    "success" => "0",
10
+    "not_found" => 404,
11
+    "forward" => 302,
12
+    "server_error" => 500,
13
+    "default_error" => 1000,
14
+    "permission_denied" =>401
15
+];

+ 17 - 0
config/errMsg.php Прегледај датотеку

@@ -0,0 +1,17 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: guanxl
5
+ * Date: 2018/5/18
6
+ * Time: 18:20
7
+ */
8
+return [
9
+    "success" => "ok",
10
+    "404" => "404错误",
11
+    "302" => "302跳转",
12
+    "500" => "服务器内部错误",
13
+    "1000" => "操作失败",
14
+    "not_found_activity" => "找不到活动信息",
15
+    "not_oauth" => "未获到认证信息",
16
+    "401" => "无权限访问"
17
+];

+ 19 - 0
database/factories/ModelFactory.php Прегледај датотеку

@@ -0,0 +1,19 @@
1
+<?php
2
+
3
+/*
4
+|--------------------------------------------------------------------------
5
+| Model Factories
6
+|--------------------------------------------------------------------------
7
+|
8
+| Here you may define all of your model factories. Model factories give
9
+| you a convenient way to create models for testing and seeding your
10
+| database. Just tell the factory how a default model should look.
11
+|
12
+*/
13
+
14
+$factory->define(App\User::class, function (Faker\Generator $faker) {
15
+    return [
16
+        'name' => $faker->name,
17
+        'email' => $faker->email,
18
+    ];
19
+});

+ 0 - 0
database/migrations/.gitkeep Прегледај датотеку


+ 16 - 0
database/seeds/DatabaseSeeder.php Прегледај датотеку

@@ -0,0 +1,16 @@
1
+<?php
2
+
3
+use Illuminate\Database\Seeder;
4
+
5
+class DatabaseSeeder extends Seeder
6
+{
7
+    /**
8
+     * Run the database seeds.
9
+     *
10
+     * @return void
11
+     */
12
+    public function run()
13
+    {
14
+        // $this->call('UsersTableSeeder');
15
+    }
16
+}

+ 53 - 0
example.env Прегледај датотеку

@@ -0,0 +1,53 @@
1
+APP_ENV=product
2
+APP_DEBUG=false
3
+APP_KEY=
4
+APP_TIMEZONE=PRC
5
+APP_LOCALE=zh-CN
6
+
7
+LOG_CHANNEL=stack
8
+LOG_SLACK_WEBHOOK_URL=
9
+
10
+DB_CONNECTION=mysql
11
+DB_HOST=""
12
+DB_PORT=3306
13
+DB_DATABASE=activity
14
+DB_USERNAME=brainstorming
15
+DB_PASSWORD=""
16
+
17
+REDIS_HOST=""
18
+REDIS_PORT=6379
19
+REDIS_PASSWORD=""
20
+REDIS_DATABASE=8
21
+
22
+REDIS_HOST_LOG=""
23
+REDIS_PORT_LOG=6379
24
+REDIS_PASSWORD_LOG=""
25
+REDIS_DATABASE=8
26
+
27
+CACHE_DRIVER=redis
28
+QUEUE_DRIVER=redis
29
+
30
+ALIYUN_ACCESS_KEY_ID="LTAIRwTwDdeclRzu"
31
+ALIYUN_ACCESS_KEY_SECRET="Iz68nzAgp1LD8Relicz0Z8stdH2RHR"
32
+SMS_TEMPLATE_CODE="SMS_135031096"
33
+SMS_SIGN_NAME="爱关怀"
34
+
35
+NO_PRIZE_IMG=""
36
+
37
+SSO_URL="https://activity.51guanhuai.com/common/sso"
38
+
39
+COOKIE_DOMAIN="51guanhuai.com"
40
+
41
+WEB_URL="https://activity.51guanhuai.com/brainstorming"
42
+
43
+NOT_FOUND_URL="https://s1-hn.aghcdn.com/activity/common/page/crowd/index.html"
44
+ERROR_MESSAGE_URL="https://s1-hn.aghcdn.com/activity/common/page/crowd/errEvir.html"
45
+
46
+QINIU_ACCESS_KEY="4zxzx2L8XVodROkDhK-p8Vcr7Dn-fqN9feC5Zghx"
47
+QINIU_SECRET_KEY="CXJp6zx-Z2-Y-9ITPmwJgmjc6vUNI0s9emhEVMSZ"
48
+QINIU_BUCKET=game
49
+
50
+APP_NAME="爱答题"
51
+
52
+APP_SUPPORT="点滴关怀"
53
+

+ 27 - 0
phpunit.xml Прегледај датотеку

@@ -0,0 +1,27 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<phpunit backupGlobals="false"
3
+         backupStaticAttributes="false"
4
+         bootstrap="bootstrap/app.php"
5
+         colors="true"
6
+         convertErrorsToExceptions="true"
7
+         convertNoticesToExceptions="true"
8
+         convertWarningsToExceptions="true"
9
+         processIsolation="false"
10
+         stopOnFailure="false"
11
+         syntaxCheck="false">
12
+    <testsuites>
13
+        <testsuite name="Application Test Suite">
14
+            <directory suffix="Test.php">./tests</directory>
15
+        </testsuite>
16
+    </testsuites>
17
+    <filter>
18
+        <whitelist processUncoveredFilesFromWhitelist="true">
19
+            <directory suffix=".php">./app</directory>
20
+        </whitelist>
21
+    </filter>
22
+    <php>
23
+        <env name="APP_ENV" value="testing"/>
24
+        <env name="CACHE_DRIVER" value="array"/>
25
+        <env name="QUEUE_DRIVER" value="sync"/>
26
+    </php>
27
+</phpunit>

+ 28 - 0
public/index.php Прегледај датотеку

@@ -0,0 +1,28 @@
1
+<?php
2
+
3
+/*
4
+|--------------------------------------------------------------------------
5
+| Create The Application
6
+|--------------------------------------------------------------------------
7
+|
8
+| First we need to get an application instance. This creates an instance
9
+| of the application / container and bootstraps the application so it
10
+| is ready to receive HTTP / Console requests from the environment.
11
+|
12
+*/
13
+
14
+$app = require __DIR__.'/../bootstrap/app.php';
15
+
16
+/*
17
+|--------------------------------------------------------------------------
18
+| Run The Application
19
+|--------------------------------------------------------------------------
20
+|
21
+| Once we have the application, we can handle the incoming request
22
+| through the kernel, and send the associated response back to
23
+| the client's browser allowing them to enjoy the creative
24
+| and wonderful application we have prepared for them.
25
+|
26
+*/
27
+
28
+$app->run();

+ 0 - 0
public/static/index - 副本.html Прегледај датотеку


Неке датотеке нису приказане због велике количине промена