public static function saveWeChatUser($user) { $oldUser = self::getWeChatUserByOpenId($user->openId); if (isset($oldUser)) { $oldUser->unionId = $user->unionId; $oldUser->nickname = $user->nickname; $oldUser->sex = $user->sex; $oldUser->city = $user->city; $oldUser->province = $user->province; $oldUser->country = $user->country; $oldUser->subscribeTime = $user->subscribeTime; $oldUser->subscribe = $user->subscribe; $oldUser->headImgUrl = $user->headImgUrl; $oldUser->openId = $user->openId; $oldUser->save(); $mcdKey = 'm:weChatUserService?openId=' . $user->openId; Wk::redis()->delete($mcdKey); return true; } else { $oldUser = new TAR_WechatUser(); $oldUser->unionId = $user->unionId; $oldUser->nickname = $user->nickname; $oldUser->sex = $user->sex; $oldUser->city = $user->city; $oldUser->province = $user->province; $oldUser->country = $user->country; $oldUser->subscribeTime = $user->subscribeTime; $oldUser->subscribe = $user->subscribe; $oldUser->headImgUrl = $user->headImgUrl; $oldUser->openId = $user->openId; $oldUser->save(); return true; } return false; }
public function _templateAction() { $config = isset($_GET['__config__']) ? $_GET['__config__'] : null; if (!isset($config)) { throw new Wk_Exception("", -1); } if (!empty($config['redirect'])) { Wk_Request::redirect($config['redirect']); } $needLogin = isset($config['needLogin']) ? $config['needLogin'] : 0; if (isset($needLogin) && $needLogin == 1 && !$this->isLogin()) { $this->redirectLogin(); } $needLogout = isset($config['needLogout']) ? $config['needLogout'] : 0; if (isset($needLogout) && $needLogout == 1 && $this->isLogin()) { // throw new K_Exception('', TErrorConstants::E_LOGIN); Wk_Request::redirect("/"); } $path = $config['path']; if (!empty($path)) { unset($_GET['__config__']); $content = $this->renderReleaseTemplate($path, true); echo $content; } Wk::app()->stop(); }
public function beforeAction() { parent::beforeAction(); Wk_Request::startSession(WAKA_DOMAIN); if (isset($_SESSION['user'])) { $this->curUser = $_SESSION['user']; } if (isset($this->curUser)) { Wk::app()->user = new Wk_WebUser(); Wk::app()->user->userid = $this->curUser->id; Wk::app()->user->utoken = ""; } if (isset($this->curUser)) { WkAdminUserService::getInstance()->setLoginCookie($this->curUser); } else { unset($_COOKIE['WAKAUID']); unset($_COOKIE['WAKAUMB']); setcookie('WAKAUID', '', time() - 3600, '/', WAKA_DOMAIN); setcookie('WAKAUMB', '', time() - 3600, '/', WAKA_DOMAIN); } $access = $this->access(); if (!empty($access['?']) && in_array($this->actionName, $access['?'])) { if ($this->isLogin()) { throw new Wk_Exception('', TErrorConstants::E_LOGIN); } } elseif (!empty($access['*']) && in_array($this->actionName, $access['*'])) { } elseif ($this->isGuest()) { throw new Wk_Exception('', TErrorConstants::E_NOT_LOGIN); } }
public function returnError($errorMsg = '', $errorCode = -1, $httpStatus = 200) { if (preg_match("/too many connection/i", $errorMsg)) { $errorMsg = "流量爆表啦!小伙伴们请稍后重试吧~我们正在马不停蹄地解决!"; } if (isset($_SERVER['HTTP_ORIGIN'])) { $origin = $_SERVER['HTTP_ORIGIN']; if (preg_match(self::DOMAIN_PATTERN, $origin) === 1) { header('Access-Control-Allow-Origin: ' . $origin); header('Access-Control-Allow-Credentials: true'); } } header("Expires: 0"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header('Content-Type: application/json; charset=utf-8'); if (!empty($errorMsg)) { echo json_encode(['ok' => 0, 'code' => $errorCode, 'msg' => $errorMsg], JSON_UNESCAPED_UNICODE); } else { echo json_encode(['ok' => 0, 'code' => $errorCode, 'msg' => TErrorConstants::getErrorMsg($errorCode)], JSON_UNESCAPED_UNICODE); } Wk::app()->stop(); }
public function destroy($id) { $redKey = 'wk:session:' . $id; $n = Wk::redis()->del($redKey); if ($n == 1) { return true; } return false; }
public function renderAjax($obj = null) { $json = ['ok' => 1]; if (isset($obj)) { $json['obj'] = $obj; } header('Content-Type: application/json; charset=utf-8'); echo json_encode($json, JSON_UNESCAPED_UNICODE); Wk::app()->stop(); }
function catchFatalError() { $error = error_get_last(); if (empty($error)) { return; } $ignore = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_STRICT | E_DEPRECATED | E_USER_DEPRECATED; if (($error['type'] & $ignore) == 0) { // handle the error - but DO NOT THROW ANY EXCEPTION HERE. Wk::logger()->err('Fatal error: ' . print_r($error, true)); die; } }
public function renderAjax($obj = null) { $json = ['ok' => 1]; if (isset($obj)) { $json['obj'] = $obj; } $jsonStr = json_encode($json, JSON_UNESCAPED_UNICODE); if (isset($_SERVER['HTTP_ORIGIN'])) { $origin = $_SERVER['HTTP_ORIGIN']; if (preg_match(self::DOMAIN_PATTERN, $origin) === 1) { header('Access-Control-Allow-Origin: ' . $origin); header('Access-Control-Allow-Credentials: true'); } } header('Content-Type: application/json; charset=utf-8'); echo $jsonStr; Wk::app()->stop(); }
public function _templateAction() { if ($this->isGuest() && strpos($_SERVER['REQUEST_URI'], '/admin/login') !== 0) { Wk_Request::redirect('/admin/login'); } if ($this->isLogin() && strpos($_SERVER['REQUEST_URI'], '/admin/login') === 0) { Wk_Request::redirect('/admin'); } $config = isset($_GET['__config__']) ? $_GET['__config__'] : null; if (!isset($config)) { throw new Wk_Exception("", -1); } $path = $config['path']; if (!empty($path)) { unset($_GET['__config__']); $content = $this->renderReleaseTemplate($path, true); echo $content; } Wk::app()->stop(); }
public static function sendCode($mobile, $userid = 0) { $key = self::CACHEKEY . $mobile; $value = Wk::redis()->get($key); if ($value !== false) { throw new Wk_Exception("", TErrorConstants::E_SMS_CODE_TOO_FREQUENCY); } if (WAKA_ENV == "production") { $randstr = mt_rand(10000, 99999); } else { $randstr = "12345"; } // to do 发短信 Wk::redis()->set($key, $randstr, 60); $mobileVerify = new TAR_MobileVerify(); $mobileVerify->mobile = $mobile; $mobileVerify->userid = 0; $mobileVerify->randstr = $randstr; $mobileVerify->state = 0; $mobileVerify->expire = date("Y-m-d H:i:s", time() + 5 * 60); $mobileVerify->save(); }
/** * @return Wk_City_List */ public function getWkCityList() { $cityListRKey = "wk:city:getCityList"; $res = unserialize(Wk::redis()->get($cityListRKey)); if (!$res) { $cities = TAR_City::findAll("where status in (0, 1) order by status asc"); $res = new Wk_City_List(); $res->list = []; foreach ($cities as $city) { $item = new Wk_City(); $item->id = $city->id; $item->name = $city->name; $item->province = $city->province; $item->status = $city->status; $item->lat = $city->lat; $item->lng = $city->lng; $res->list[] = $item; } Wk::redis()->set($cityListRKey, serialize($res), 20 * 60); } return $res; }
public static function redis($redis = "default") { $hash = 'wk_redis_' . $redis; if (!isset(self::$componentStack[$hash])) { if (empty(self::$config['redis']) || empty(self::$config['redis'][$redis])) { return new Wk_Redis(); } $host = self::$config['redis'][$redis]['host']; $port = self::$config['redis'][$redis]['port']; $_redis = new Wk_Redis(); try { $success = $_redis->pconnect($host, $port); } catch (Exception $e) { Wk::logger()->err($e); return $_redis; } if (!$success) { Wk::logger()->err("connect to redis {$host}:{$port} return false: " . $_redis->getLastError()); return $_redis; } self::$componentStack[$hash] = $_redis; } return self::$componentStack[$hash]; }
/** * (PHP 5 >= 5.0.0)<br/> * Offset to set * @link http://php.net/manual/en/arrayaccess.offsetset.php * @param mixed $offset <p> * The offset to assign the value to. * </p> * @param mixed $value <p> * The value to set. * </p> * @throws Wk_Exception */ public function offsetSet($offset, $value) { if ($this->offsetExists($offset)) { $this->{$offset} = $value; } Wk::logger()->err("property {$offset} not exists in " . get_called_class()); throw new Wk_Exception("property {$offset} not exists in " . get_called_class(), -1); }
private static function formatSMessage() { $prefix = date('Y-m-d H:i:s ', Wk_Request::getTime()); $user = Wk::app()->user; if (isset($user) && !empty($user->userid) && !empty($user->utoken)) { $prefix .= '[userid:' . $user->userid . ']'; $prefix .= '[usertoken:' . $user->utoken . ']'; } if (session_status() == PHP_SESSION_ACTIVE) { $prefix .= '[SESSION_ID:' . session_id() . ']'; } if (!empty($_COOKIE['SERVERID'])) { $prefix .= '[SERVERID:' . $_COOKIE['SERVERID'] . ']'; } $prefix .= $_SERVER['REQUEST_URI']; $referStr = '[REFER:'; $hasRefer = false; $locStr = '[LOC:'; $hasLoc = false; if (!empty($_SERVER['REQUEST_URI'])) { $urlArr = parse_url($_SERVER['REQUEST_URI']); //$prefix .= "[PATH:{$urlArr['path']}]"; $getParams = []; parse_str($urlArr['query'], $getParams); if (!empty($getParams)) { //$prefix .= '[GET:'; foreach ($getParams as $key => $value) { // if (!in_array($key, ['v','vc','vd','token','timestr','sign','lang'])) { // $prefix .= "$key=$value&"; // } } //$prefix .= ']'; } } $prefix .= " "; // if (isset(K::app()->getController()) && !empty(K::app()->getController()->appParam)) { // $prefix .= '[APP_PARAM:'; // foreach (K::app()->getController()->appParam as $key => $value) { // $prefix .= "$key=$value&"; // } // $prefix .= ']'; // } //$prefix .= self::getServerVariable('SERVER_SIGNATURE'); //$prefix .= self::getServerVariable('REQUEST_URI'); //$prefix .= self::getServerVariable('QUERY_STRING'); if (!empty($_POST)) { $prefix .= '[POST:'; foreach ($_POST as $key => $value) { if (in_array($key, ['refer', 'id1', 'id2'])) { $hasRefer = true; $referStr .= "{$key}={$value}&"; continue; } $prefix .= $key . '=' . urlencode($value) . '&'; } $prefix .= ']'; } $referStr .= ']'; $locStr .= ']'; if ($hasRefer) { $prefix .= $referStr; } if ($hasLoc) { $prefix .= $locStr; } $prefix .= $_SERVER['HTTP_USER_AGENT']; $prefix .= $_SERVER['REMOTE_ADDR']; $prefix .= $_SERVER['HTTP_REFERER']; // $prefix .= '[NETCOUNT:db('.Wk::db()->getExecuteCnt().'),mc('.K::mcd()->getUseCnt().'),redis('.K::redis()->getUseCnt().'),tbapi('.TB_BaseSrv::getUseCnt().'),trapi('.TRoad_BaseSrv::getUseCnt().'),solr('.K::solr()->getUseCnt().')]'; if (isset($_SERVER["REQUEST_TIME_FLOAT"])) { $prefix .= '[WAITING:' . round(Wk::app()->startTime - $_SERVER["REQUEST_TIME_FLOAT"], 8) * 1000 . 'ms]'; $prefix .= '[DURATION:' . round(microtime(true) - Wk::app()->startTime, 8) * 1000 . 'ms]'; } return $prefix . "\n"; }
public function stop() { Wk::logger()->s(); die; }
/** * @param $function * @return bool */ private function _wrapBoolReturn($function) { try { $success = $function(); if (!$success) { $errMsg = self::getLastError(); if (!isset($errMsg)) { $errMsg = 'unknown redis error'; } try { throw new Exception($errMsg); } catch (Exception $e) { Wk::logger()->err($e); } } return $success; } catch (Exception $e) { Wk::logger()->err($e); } return false; }
public function rollback() { if (!$this->_db->rollback()) { Wk::logger()->err($this->error); } $this->_db->autocommit(true); }
private static function printTransferCertainCustomerService($fromUsername, $toUsername, $createTime, $kfAccount) { $textTpl = "<xml>\n <ToUserName><![CDATA[%s]]></ToUserName>\n <FromUserName><![CDATA[%s]]></FromUserName>\n <CreateTime>%s</CreateTime>\n <MsgType><![CDATA[transfer_customer_service]]></MsgType>\n <TransInfo>\n <KfAccount>%s</KfAccount>\n </TransInfo>\n </xml>"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $createTime, $kfAccount); Wk::logger()->log($resultStr); return $resultStr; }
<?php //if (function_exists('xhprof_enable')) { // xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY); //} $startTime = microtime(true); error_reporting(E_ALL); include __DIR__ . '/../framework/bootstrap.php'; Wk::createWebApp(include APP_ROOT . '/configs/config.php', $startTime)->run();
/** * @throws Wk_Exception */ public final function delete() { if (!isset($this->id)) { Wk::logger()->err('obj not inserted'); throw new Wk_Exception('', -1); } if (property_exists($this, 'isDeleted')) { $this->isDeleted = 1; $this->save(); } else { $sql = 'delete from ' . $this->getTableName() . ' where id=?'; if (Wk::db()->execute($sql, 'i', $this->id)) { unset($this->id); } else { Wk::logger()->err('db error'); throw new Wk_Exception('', -1); } } }
/** * 返回错误信息 * * @param string $errorMsg * @param int $errorCode * @param int $httpStatus */ public function returnError($errorMsg = '', $errorCode = -1, $httpStatus = 200) { if ($httpStatus !== 200) { switch ($httpStatus) { case 404: header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found'); echo '404 Not Found'; break; case 403: header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden'); echo '403 Forbidden'; break; case 500: header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error'); echo '500 Internal Server Error'; break; default: header($_SERVER['SERVER_PROTOCOL'] . ' ' . $httpStatus . ' Http Error'); echo $httpStatus . ' Http Error'; break; } } elseif (Wk_Request::isAjax()) { header('Content-Type: application/json; charset=utf-8'); if (!empty($errorMsg)) { echo json_encode(['ok' => 0, 'msg' => $errorMsg, 'code' => $errorCode], JSON_UNESCAPED_UNICODE); } else { echo json_encode(['ok' => 0, 'msg' => TErrorConstants::getErrorMsg($errorCode), 'code' => $errorCode], JSON_UNESCAPED_UNICODE); } } else { if (empty($errorMsg)) { $errorMsg = TErrorConstants::getErrorMsg($errorCode); } Wk::logger()->err('page error:' . $errorCode . (empty($errorMsg) ? '' : '(' . $errorMsg . ')')); // $this->renderView('/layouts/404'); echo 'error: ' . $errorCode . (empty($errorMsg) ? '' : '(' . $errorMsg . ')'); } Wk::app()->stop(); }
/** * @return int */ public static function getTime() { if (!Wk::app() instanceof WebApp) { return time(); } return $_SERVER['REQUEST_TIME']; }