Repository navigation
Expand file tree
/
Copy pathBaseController.php
More file actions
426 lines (360 loc) · 13.9 KB
/
Copy pathBaseController.php
File metadata and controls
426 lines (360 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
<?php
/**
* Created by PhpStorm.
* User: childeYin<尹少爷>
* Date: 13/07/2018
* Time: 6:32 PM
*/
use Google\Protobuf\Any;
use Zaly\Proto\Core\TransportData;
use Zaly\Proto\Core\TransportDataHeaderKey;
use Google\Protobuf\Internal\Message;
abstract class BaseController extends \Wpf_Controller
{
protected $logger;
protected $httpHeader = ["KeepSocket" => true];
protected $headers = [];
protected $bodyFormatType;
protected $bodyFormatArr = [
"json",
"pb",
"base64pb"
];
protected $defaultBodyFormat = "json";
protected $action = '';
protected $requestTransportData;
private $whiteAction = [
"api.site.config",
"api.site.login",
"im.cts.ping",
"api.passport.passwordReg",
"api.passport.passwordLogin",
"api.session.verify",
"api.passport.passwordFindPassword",
"api.passport.passwordResetPassword",
"api.passport.passwordUpdateInvitationCode",
"api.passport.passwordModifyPassword",
"api.plugin.proxy",
];
protected $sessionIdTimeOut = 3600000; //一个小时
protected $userId;
protected $sessionId;
protected $deviceId;
protected $userInfo;
public $defaultErrorCode = "success";
public $defaultPageSize = 200;
public $defaultPage = 1;
public $errorSiteInit = "error.site.init";
protected $siteConfig;
protected $language = Zaly\Proto\Core\UserClientLangType::UserClientLangEN;
/**
* @var BaseCtx
*/
protected $ctx;
// return the name for parse json to Any.
abstract public function rpcRequestClassName();
// waiting for son~
abstract public function rpc(\Google\Protobuf\Internal\Message $request, \Google\Protobuf\Internal\Message $transportData);
/**
* 设置transData header
* @param $key
* @param $val
*/
public function setTransDataHeaders($key, $val)
{
$key = "_{$key}";
$this->headers[$key] = $val;
}
public function keepSocket()
{
header("KeepSocket: true");
}
//set errCode && errInfo by error
public function setZalyError($error)
{
$errCode = ZalyError::getErrCode($error);
$errInfo = ZalyError::getErrorInfo($error, $this->language);
$this->setRpcError($errCode, $errInfo);
}
//set errCode && errInfo by error && throw exception
public function throwZalyException($error)
{
$errCode = ZalyError::getErrCode($error);
$errInfo = ZalyError::getErrorInfo($error, $this->language);
$this->setRpcError($errCode, $errInfo);
throw new ZalyException($errCode, $errInfo);
}
//only set errCode ,errInfo
public function setRpcError($errorCode, $errorInfo)
{
$this->setTransDataHeaders(TransportDataHeaderKey::HeaderErrorCode, $errorCode);
$this->setTransDataHeaders(TransportDataHeaderKey::HeaderErrorInfo, $errorInfo);
}
public function getRpcError()
{
return isset($this->headers[TransportDataHeaderKey::HeaderErrorCode]) ? $this->headers[TransportDataHeaderKey::HeaderErrorCode] : false;
}
public function getRequestAction()
{
return $this->action;
}
/**
* 返回需要格式的数据
* @param $action
* @param \Google\Protobuf\Internal\Message $response
*/
public function rpcReturn($action, $response)
{
$transData = new TransportData();
$transData->setAction($action);
if (null != $response) {
$anyBody = new Any();
$anyBody->pack($response);
$transData->setBody($anyBody);
}
$transData->setHeader($this->headers);
$transData->setPackageId($this->requestTransportData->getPackageId());
$body = "";
if ("json" == $this->bodyFormatType) {
$body = $transData->serializeToJsonString();
$body = trim($body);
} elseif ("pb" == $this->bodyFormatType) {
$body = $transData->serializeToString();
} elseif ("base64pb" == $this->bodyFormatType) {
$body = $transData->serializeToString();
$body = base64_encode($body);
} else {
return;
}
echo $body;
return;
}
//rpc response return success
public function returnSuccessRPC($response)
{
$this->setRpcError($this->defaultErrorCode, "");
$this->rpcReturn($this->action, $response);
}
//return rpc exception
public function returnErrorRPC($response, $e)
{
$this->setRpcError("error.alert", $e->getMessage());
$this->rpcReturn($this->action, $response);
}
public function returnErrorCodeRPC($errCode, $errInfo, $response = null)
{
$this->setRpcError($errCode, $errInfo);
$this->rpcReturn($this->action, $response);
}
// ignore.~
public function __construct(Wpf_Ctx $context)
{
if (!$this->checkDBIsExist()) {
$this->action = $_GET['action'];
$this->requestTransportData = new \Zaly\Proto\Core\TransportData();
$pageSiteInit = ZalyHelper::getFullReqUrl(ZalyConfig::getConfig("apiPageSiteInit"));
$this->setRpcError($this->errorSiteInit, $pageSiteInit);
$this->bodyFormatType = isset($_GET['body_format']) ? $_GET['body_format'] : "";
$this->bodyFormatType = strtolower($this->bodyFormatType);
if (!in_array($this->bodyFormatType, $this->bodyFormatArr)) {
$this->bodyFormatType = $this->defaultBodyFormat;
}
$this->rpcReturn($this->action, null);
exit();
}
$this->ctx = new BaseCtx();
$this->logger = new Wpf_Logger();
}
/**
* 处理方法, 根据bodyFormatType, 获取transData
* @return string|void
*/
public function doIndex()
{
$tag = __CLASS__ . "-" . __FUNCTION__;
parent::doIndex();
$this->ctx = new BaseCtx();
// 判断请求格式 json, pb, pb64
// body_format 只从$_GET中接收
$this->action = $_GET['action'];
// $this->checkDBCanWrite();
$this->bodyFormatType = isset($_GET['body_format']) ? $_GET['body_format'] : "";
$this->bodyFormatType = strtolower($this->bodyFormatType);
if (!in_array($this->bodyFormatType, $this->bodyFormatArr)) {
$this->bodyFormatType = $this->defaultBodyFormat;
}
// 接收的数据流
$reqData = file_get_contents("php://input");
// 将数据转为TransportData
$this->requestTransportData = new \Zaly\Proto\Core\TransportData();
if (!ZalyHelper::checkOpensslEncryptExists()) {
$this->ctx->Wpf_Logger->error($tag, "none has openssl function exists");
// disabled the rpcReturn online.
$this->setRpcError("error.proto.parse", "openssl_encrypt is not exists");
$this->rpcReturn($this->action, null);
die();
}
////判断 request proto 类 是否存在。
$requestClassName = $this->rpcRequestClassName();
if (class_exists($requestClassName, true)) {
$usefulForProtobufAnyParse = new $requestClassName();
} else {
trigger_error("no request proto class: " . $requestClassName, E_USER_ERROR);
die();
}
try {
if ("json" == $this->bodyFormatType) {
if (empty($reqData)) {
$reqData = "{}";
}
$this->requestTransportData->mergeFromJsonString($reqData);
} elseif ("pb" == $this->bodyFormatType) {
$this->requestTransportData->mergeFromString($reqData);
} elseif ("base64pb" == $this->bodyFormatType) {
$realData = base64_decode($reqData);
$this->requestTransportData->mergeFromString($realData);
}
} catch (Exception $e) {
$error = sprintf("parse proto error, format: %s, error: %s", $this->bodyFormatType, $e->getMessage());
$this->ctx->Wpf_Logger->error($tag, $error);
// disabled the rpcReturn online.
$this->setRpcError("error.proto.parse", $error);
$this->rpcReturn($this->action, null);
die();
}
$requestMessage = $usefulForProtobufAnyParse;
////解析请求数据,
///
if (null !== $this->requestTransportData->getBody()) {
$requestMessage = $this->requestTransportData->getBody()->unpack();
}
// $this->ctx->Wpf_Logger->error($tag, "request packageId =" . $this->requestTransportData->getPackageId());
$this->handleHeader();
$this->getAndSetClientLang();
$this->checkSessionId($this->action);
$this->rpc($requestMessage, $this->requestTransportData);
}
private function handleHeader()
{
$headers = $this->requestTransportData->getHeader();
foreach ($headers as $key => $val) {
$key = str_replace("_", "", $key);
$headers[$key] = $val;
}
$this->requestTransportData->setHeader($headers);
}
/**
* @param Message $transportData
* @return string
*/
public function getSessionId(\Google\Protobuf\Internal\Message $transportData)
{
$header = $transportData->getHeader();
$sessionId = $header[TransportDataHeaderKey::HeaderSessionid];
return $sessionId;
}
public function checkSessionId($action)
{
$this->siteConfig = $this->ctx->Site_Config->getAllConfig();
if (empty($this->siteConfig)) {
$this->returnErrorSession("site config is empty");
}
$tag = __CLASS__ . "-" . __FUNCTION__;
$requestTransportData = $this->requestTransportData;
$headers = $requestTransportData->getHeader();
if (in_array($action, $this->whiteAction)) {
return;
}
if (!isset($headers[TransportDataHeaderKey::HeaderSessionid])) {
$this->returnErrorSession();
}
$this->sessionId = $headers[TransportDataHeaderKey::HeaderSessionid];
//check session by sessionId
$sessionInfo = $this->ctx->SiteSessionTable->getSessionInfoBySessionId($this->sessionId);
if (empty($sessionInfo) || !$this->checkSessionByTime($sessionInfo)) {
$this->returnErrorSession();
}
$this->userId = $sessionInfo['userId'];
$this->deviceId = $sessionInfo['deviceId'];
$this->userInfo = $this->ctx->SiteUserTable->getUserByUserId($this->userId);
if (empty($this->userInfo)) {
$this->returnErrorSession();
}
//update session
$this->ctx->SiteSessionTable->updateSessionActive($this->sessionId);
}
private function checkSessionByTime($sessionInfo)
{
//check session by session time
$currentTime = $this->ctx->ZalyHelper->getMsectime();
$timeActive = $sessionInfo['timeActive'];
if (($currentTime - $timeActive) < $this->sessionIdTimeOut * 24 * 365) {
return true;
}
return false;
}
public function getPublicUserProfile($userInfo)
{
try {
$publicUserProfile = new \Zaly\Proto\Core\PublicUserProfile();
$avatar = isset($userInfo['avatar']) ? $userInfo['avatar'] : "";
$publicUserProfile->setAvatar($avatar);
$publicUserProfile->setUserId($userInfo['userId']);
$publicUserProfile->setLoginname($userInfo['loginName']);
$publicUserProfile->setNickname($userInfo['nickname']);
$publicUserProfile->setNicknameInLatin($userInfo['nicknameInLatin']);
if (isset($userInfo['availableType'])) {
$publicUserProfile->setAvailableType($userInfo['availableType']);
} else {
$publicUserProfile->setAvailableType(\Zaly\Proto\Core\UserAvailableType::UserAvailableNormal);
}
return $publicUserProfile;
} catch (Exception $ex) {
$this->ctx->Wpf_Logger->error("get public user profile", $ex);
$publicUserProfile = new \Zaly\Proto\Core\PublicUserProfile();
return $publicUserProfile;
}
}
public function getGroupMemberUserProfile($user)
{
$tag = __CLASS__ . "-" . __FUNCTION__;
$this->ctx->Wpf_Logger->info($tag, "user userMemberType = " . $user['memberType']);
$publicUserProfile = $this->getPublicUserProfile($user);
$groupMemberUserProfile = new \Zaly\Proto\Site\ApiGroupMembersUserProfile();
$groupMemberUserProfile->setProfile($publicUserProfile);
$groupMemberUserProfile->setType((int)$user['memberType']);
return $groupMemberUserProfile;
}
protected function finish_request()
{
if (!function_exists("fastcgi_finish_request")) {
function fastcgi_finish_request()
{
}
}
fastcgi_finish_request();
}
protected function getAndSetClientLang()
{
$requestTransportData = $this->requestTransportData;
$headers = $requestTransportData->getHeader();
$headLang = isset($headers[TransportDataHeaderKey::HeaderUserClientLang]) ? $headers[TransportDataHeaderKey::HeaderUserClientLang] : "";
if (isset($headLang) && $headLang == Zaly\Proto\Core\UserClientLangType::UserClientLangZH) {
$this->language = Zaly\Proto\Core\UserClientLangType::UserClientLangZH;
$this->zalyError = $this->ctx->ZalyErrorZh;
} else {
$this->language = Zaly\Proto\Core\UserClientLangType::UserClientLangEN;
$this->zalyError = $this->ctx->ZalyErrorEn;
}
}
private function returnErrorSession($errorInfo = false)
{
$errorCode = $this->zalyError->errorSession;
if (empty($errorInfo)) {
$errorInfo = $this->zalyError->getErrorInfo($errorCode);
}
$this->setRpcError($errorCode, $errorInfo);
$this->rpcReturn($this->action, null);
die();
}
}