记录FLASH包含日志
@param $ip string IP地址
@param $request string[] 请求参数数组
@param $server string[] 环境变量数组
343056
public function flash(string $ip, array $request, array $server): void
    {
        $this->isConfigDebug ? print('anti flash') : null;
        $this->log(configDefault('anti/flash', 'log', 'anti', 'flash'), ['ip' => $ip, 'request' => $request, 'server' => $server]);
    }
1312470
public function getlocation($ip = '')
    {
        if (!$this->fp)
            return null;            // 如果数据文件没有被正确打开，则直接返回空
        if (empty($ip))
            $ip = Utils::getClientIp();
        $location['ip'] = gethostbyname($ip);   // 将输入的域名转化为IP地址
        $ip = $this->packip($location['ip']);   // 将输入的IP地址转化为可比较的IP地址
        // 不合法的IP地址会被转化为255.255.255.255
        // 对分搜索
        $l = 0;                         // 搜索的下边界
        $u = $this->totalip;            // 搜索的上边界
        $findip = $this->lastip;        // 如果没有找到就返回最后一条IP记录（QQWry.Dat的版本信息）
        while ($l <= $u) {              // 当上边界小于下边界时，查找失败
            $i = floor(($l + $u) / 2);  // 计算近似中间记录
            fseek($this->fp, $this->firstip + $i * 7);
            $beginip = strrev(fread($this->fp, 4));     // 获取中间记录的开始IP地址
            // strrev函数在这里的作用是将little-endian的压缩IP地址转化为big-endian的格式
            // 以便用于比较，后面相同。
            if ($ip < $beginip) {       // 用户的IP小于中间记录的开始IP地址时
                $u = $i - 1;            // 将搜索的上边界修改为中间记录减一
            } else {
                fseek($this->fp, $this->getlong3());
                $endip = strrev(fread($this->fp, 4));   // 获取中间记录的结束IP地址
                if ($ip > $endip) {     // 用户的IP大于中间记录的结束IP地址时
                    $l = $i + 1;        // 将搜索的下边界修改为中间记录加一
                } else {                  // 用户的IP在中间记录的IP范围内时
                    $findip = $this->firstip + $i * 7;
                    break;              // 则表示找到结果，退出循环
                }
            }
        }
        
        //获取查找到的IP地理位置信息
        fseek($this->fp, $findip);
        $location['beginip'] = long2ip($this->getlong());   // 用户IP所在范围的开始地址
        $offset = $this->getlong3();
        fseek($this->fp, $offset);
        $location['endip'] = long2ip($this->getlong());     // 用户IP所在范围的结束地址
        $byte = fread($this->fp, 1);    // 标志字节
        switch (ord($byte)) {
            case 1:                     // 标志字节为1，表示国家和区域信息都被同时重定向
                $countryOffset = $this->getlong3();         // 重定向地址
                fseek($this->fp, $countryOffset);
                $byte = fread($this->fp, 1);    // 标志字节
                switch (ord($byte)) {
                    case 2:             // 标志字节为2，表示国家信息又被重定向
                        fseek($this->fp, $this->getlong3());
                        $location['country'] = $this->getstring();
                        fseek($this->fp, $countryOffset + 4);
                        $location['area'] = $this->getarea();
                        break;
                    default:            // 否则，表示国家信息没有被重定向
                        $location['country'] = $this->getstring($byte);
                        $location['area'] = $this->getarea();
                        break;
                }
                break;
            case 2:                     // 标志字节为2，表示国家信息被重定向
                fseek($this->fp, $this->getlong3());
                $location['country'] = $this->getstring();
                fseek($this->fp, $offset + 8);
                $location['area'] = $this->getarea();
                break;
            default:                    // 否则，表示国家信息没有被重定向
                $location['country'] = $this->getstring($byte);
                $location['area'] = $this->getarea();
                break;
        }
        if (trim($location['country']) == 'CZ88.NET') {  // CZ88.NET表示没有有效信息
            $location['country'] = '未知';
        }
        if (trim($location['area']) == 'CZ88.NET') {
            $location['area'] = '';
        }
        
        return $location;
    }
314276
public static function checkIp(string $ip, array $Ips = null): bool {
		// 内网ip列表
		$ruleIps = $Ips ?? [
				['10.0.0.0', '10.255.255.255'],
				['172.16.0.0', '172.31.255.255'],
				['192.168.0.0', '192.168.255.255'],
				['127.0.0.0', '127.255.255.255']
			];
		$ipInt   = ip2long(trim($ip));
		if ($ipInt === false)
			throw new InvalidArgumentException("Invalid IP[$ip].");
		foreach ($ruleIps as $rule) {
			if ($ipInt >= ip2long(reset($rule)) && $ipInt <= ip2long(end($rule))) {
				return true;
			}
		}
		return false;
	}
740516
private function logsQuery(ServerRequestInterface $request): Builder
    {
        $from     = $request->get('from');
        $to       = $request->get('to');
        $type     = $request->get('type', '');
        $text     = $request->get('text', '');
        $ip       = $request->get('ip', '');
        $username = $request->get('username', '');
        $gedc     = $request->get('gedc');

        $query = DB::table('log')
            ->leftJoin('user', 'user.user_id', '=', 'log.user_id')
            ->leftJoin('gedcom', 'gedcom.gedcom_id', '=', 'log.gedcom_id')
            ->select(['log.*', DB::raw("COALESCE(user_name, '<none>') AS user_name"), DB::raw("COALESCE(gedcom_name, '<none>') AS gedcom_name")]);

        if ($from !== '') {
            $query->where('log_time', '>=', $from);
        }

        if ($to !== '') {
            // before end of the day
            $query->where('log_time', '<', Carbon::make($to)->addDay());
        }

        if ($type !== '') {
            $query->where('log_type', '=', $type);
        }

        if ($text) {
            $query->whereContains('log_message', $text);
        }

        if ($ip) {
            $query->whereContains('ip_address', $ip);
        }

        if ($username) {
            $query->whereContains('user_name', $ip);
        }

        if ($gedc) {
            $query->where('gedcom_name', '=', $gedc);
        }

        return $query;
    }
1261439
public function send($request)
    {
        $this->request = $request;
        if([] !== ($queryParams = $this->request->getQueryParams()))
        {
            $this->request = $this->request->withUri($this->request->getUri()->withQuery(http_build_query($queryParams, '', '&')));
        }
        $uri = $this->request->getUri();
        $isLocation = false;
        $count = 0;
        do{
            $retry = $this->request->getAttribute('retry', 0);
            for($i = 0; $i <= $retry; ++$i)
            {
                $this->settings = $this->request->getAttribute('options', []);
                // 解析IP
                $ip = Coroutine::gethostbyname($uri->getHost());
                // 实例化
                $this->handler = new Client($ip, $uri->getPort(), 'https' === $uri->getScheme());
                $this->handler->setDefer();
                // method
                if($isLocation)
                {
                    $this->handler->setMethod('GET');
                }
                else
                {
                    $this->handler->setMethod($this->request->getMethod());
                }
                // cookie
                $this->handler->setCookies($this->request->getCookieParams());
                // body
                if(!$isLocation)
                {
                    $files = $this->request->getUploadedFiles();
                    $body = (string)$this->request->getBody();
                    if(isset($files[0]))
                    {
                        foreach($files as $file)
                        {
                            $this->handler->addFile($file->getTempFileName(), basename($file->getClientFilename()), $file->getClientMediaType());
                        }
                        parse_str($body, $body);
                    }
                    $this->handler->setData($body);
                }
                // headers
                $this->request = $this->request->withAddedHeader('Host', $uri->getHost());
                if(!$this->request->hasHeader('Content-Type'))
                {
                    $this->request = $this->request->withAddedHeader('Content-Type', MediaType::APPLICATION_FORM_URLENCODED);
                }
                $headers = [];
                foreach($this->request->getHeaders() as $name => $value)
                {
                    $headers[$name] = implode(',', $value);
                }
                $this->handler->setHeaders($headers);
                // 其它处理
                $this->parseSSL();
                $this->parseProxy();
                $this->parseNetwork();
                // 设置客户端参数
                if(!empty($this->settings))
                {
                    $this->settings['timeout'] = 30;
                    $this->handler->set($this->settings);
                }
                // 发送
                $path = $uri->getPath();
                if('' === $path)
                {
                    $path = '/';
                }
                $query = $uri->getQuery();
                if('' !== $query)
                {
                    $path .= '?' . $query;
                }
                if(null === ($saveFilePath = $this->request->getAttribute('saveFilePath')))
                {
                    $this->handler->execute($path);
                }
                else
                {
                    $this->handler->download($path, $saveFilePath);
                }
                $this->getResponse();
                $statusCode = $this->result->getStatusCode();
                // 状态码为5XX或者0才需要重试
                if(!(0 === $statusCode || (5 === (int)($statusCode/100))))
                {
                    break;
                }
            }
            if((301 === $statusCode || 302 === $statusCode) && ++$count <= $this->request->getAttribute('maxRedirects', 10))
            {
                // 自己实现重定向
                $uri = new Uri($this->result->getHeaderLine('location'));
                $isLocation = true;
            }
            else
            {
                break;
            }
        }while(true);
    }
1320384
public static function getIp(ServerRequestInterface $request)
    {
        $ips = self::getIps($request);

        return isset($ips[0]) ? $ips[0] : null;
    }
1291925
public function parse(Request $request) {
		$len = strlen($this->prefix);
		//路由解析
		$uri = $request->server['request_uri'];
		if (strpos('?', $uri) !== false) {
			$uri = substr($uri, 0, strpos($uri, '?'));
		}
		//去除开头的prefix
		if ($len > 0 && strpos($uri, $this->prefix) === 0) {
			$uri = substr($uri, $len);
		}
		$request->uri = $uri;
		$res = false;
		if (isset($this->routes[$request->server['request_method']])) {
			$res = $this->parseBy($this->routes[$request->server['request_method']], $request);
		}
		if ($res === false && isset($this->routes['any'])) {
			$res = $this->parseBy($this->routes['any'], $request);
		}
		if ($res === false) {
			if ($this->enable_map) {
				//为空则读取默认设置
				if (empty($uri) || $uri === '/') {
					$request->module = $this->module;
					$request->controller = 'index';
					$request->action = 'index';
				} else {
					if ($this->enable_extension) {
						$hasPoint = strrpos($uri, '.');
						if ($hasPoint !== false) {
							$request->extension = substr($uri, $hasPoint + 1);
							$uri = substr($uri, 0, $hasPoint);
							$request->uri = $uri;
						}
					}
					$this->parseMap($request);
				}
			}
		}
	}
118358
public function getFlash(Request $request)
    {
        if (!$this->has($request, self::FLASH_KEY)) {
            return null;
        }

        $data = $this->get($request, self::FLASH_KEY);
        $this->remove($request, self::FLASH_KEY);

        return new FlashMessage($data[FlashMessage::JSON_KEY_TYPE], $data[FlashMessage::JSON_KEY_MESSAGE]);
    }
458003
private function getProxiedIp(ServerRequestInterface $request): ?string
    {
        foreach ($this->proxyHeaders as $name) {
            if ($request->hasHeader($name)) {
                $ip = self::getHeaderIp($request->getHeaderLine($name));
                if ($ip !== null) {
                    return $ip;
                }
            }
        }

        return null;
    }
659244
public function indexAction(Request $request)
    {

        /** @var \Networking\InitCmsBundle\Lib\PhpCacheInterface $phpCache */
        $phpCache = $this->get('networking_init_cms.lib.php_cache');

        /** @var PageSnapshotInterface $page */
        $page = $request->get('_content');

        $template = $request->get('_template');
        if ($template instanceof \Sensio\Bundle\FrameworkExtraBundle\Configuration\Template) {
            $template = $template->getTemplate();
        }
        $user = $this->getUser();

        if ($phpCache->isCacheable($request, $user) && $page instanceof PageSnapshotInterface) {
            if (!$this->isSnapshotActive($page)) {
                throw new NotFoundHttpException();
            }

            if ($this->getSnapshotVisibility($page) != PageInterface::VISIBILITY_PUBLIC) {
                if (false === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
                    throw new AccessDeniedException();
                }
            }

            $updatedAt = $phpCache->get(sprintf('page_%s_created_at', $page->getId()));
            $cacheKey = $request->getLocale().$request->getPathInfo();

            if ($updatedAt != $page->getSnapshotDate()) {
                $phpCache->delete($cacheKey);
            }

            $response = $phpCache->get($request->getLocale().$request->getPathInfo());

            if (!$response || !$response instanceof Response) {
                $params = $this->getPageParameters($request);

                if ($params instanceof RedirectResponse) {
                    return $params;
                }
                $html = $this->renderView(
                    $template,
                    $params
                );
                $response = new Response($html);

                $phpCache->set($cacheKey, $response);
                $phpCache->set(sprintf('page_%s_created_at', $page->getId()), $page->getSnapshotDate());
            } else {
                $phpCache->touch($cacheKey);
                $phpCache->touch(sprintf('page_%s_created_at', $page->getId()));
            }
        } else {
            $params = $this->getPageParameters($request);

            if ($params instanceof RedirectResponse) {
                return $params;
            }
            $html = $this->renderView(
                $template,
                $params
            );
            $response = new Response($html);
        }

        if ($this->getPageHelper()->isAllowLocaleCookie() && !$this->getPageHelper()->isSingleLanguage()) {
            $response->headers->setCookie(new Cookie('_locale', $request->getLocale()));
        }

        return $response;
    }
1092727
public static function passRequestToSocket($port = 8080, Request $request = null)
    {
        if (empty($request)) {
            $request = Request::createFromGlobals();
        }

        $client = stream_socket_client('tcp://127.0.0.1:'.$port);
        fwrite($client, json_encode([
            'attributes' => $request->attributes->all(),
            'query' => $request->query->all(),
            'request' => $request->request->all(),
            'content' => $request->getContent(),
        ]));
        fclose($client);
    }
1251752
public function show(ServerRequestInterface $request, Tree $tree, ClipboardService $clipboard_service): ResponseInterface
    {
        $xref       = $request->get('xref', '');
        $individual = Individual::getInstance($xref, $tree);

        Auth::checkIndividualAccess($individual, false);

        // What is (was) the age of the individual
        $bdate = $individual->getBirthDate();
        $ddate = $individual->getDeathDate();
        if ($bdate->isOK() && !$individual->isDead()) {
            // If living display age
            $age = ' (' . I18N::translate('age') . ' ' . FunctionsDate::getAgeAtEvent(Date::getAgeGedcom($bdate, new Date(strtoupper(date('d M Y'))))) . ')';
        } elseif ($bdate->isOK() && $ddate->isOK()) {
            // If dead, show age at death
            $age = ' (' . I18N::translate('age') . ' ' . FunctionsDate::getAgeAtEvent(Date::getAgeGedcom($bdate, $ddate)) . ')';
        } else {
            $age = '';
        }

        // What images are linked to this individual
        $individual_media = [];
        foreach ($individual->facts(['OBJE']) as $fact) {
            $media_object = $fact->target();
            if ($media_object instanceof Media) {
                $individual_media[] = $media_object->firstImageFile();
            }
        }
        $individual_media = array_filter($individual_media);

        $name_records = [];
        foreach ($individual->facts(['NAME']) as $n => $name_fact) {
            $name_records[] = $this->formatNameRecord($tree, $n, $name_fact);
        }

        $sex_records = [];
        foreach ($individual->facts(['SEX']) as $n => $sex_fact) {
            $sex_records[] = $this->formatSexRecord($sex_fact);
        }

        // If this individual is linked to a user account, show the link
        $user_link = '';
        if (Auth::isAdmin()) {
            $users = $this->user_service->findByIndividual($individual);
            foreach ($users as $user) {
                $user_link = ' —  <a href="' . e(route('admin-users', ['filter' => $user->email()])) . '">' . e($user->userName()) . '</a>';
            }
        }

        return $this->viewResponse('individual-page', [
            'age'              => $age,
            'clipboard_facts'  => $clipboard_service->pastableFacts($individual, new Collection()),
            'count_media'      => $this->countFacts($individual, ['OBJE']),
            'count_names'      => $this->countFacts($individual, ['NAME']),
            'count_sex'        => $this->countFacts($individual, ['SEX']),
            'individual'       => $individual,
            'individual_media' => $individual_media,
            'meta_robots'      => 'index,follow',
            'name_records'     => $name_records,
            'sex_records'      => $sex_records,
            'sidebars'         => $this->getSidebars($individual),
            'tabs'             => $this->getTabs($individual),
            'significant'      => $this->significant($individual),
            'title'            => $individual->fullName() . ' ' . $individual->getLifeSpan(),
            'user_link'        => $user_link,
        ]);
    }
70922
function onReceive($serv, $client_id, $from_id, $data)
    {
        //检测request data完整性
        $ret = $this->checkData($client_id, $data);
        switch($ret)
        {
            //错误的请求
            case self::ST_ERROR;
                $this->server->close($client_id);
                return;
            //请求不完整，继续等待
            case self::ST_WAIT:
                return;
            default:
                break;
        }
        //完整的请求
        //开始处理

        /**
         * @var $request Swoole\Request
         */
        $request = $this->requests[$client_id];

        $request->fd = $client_id;
        $request->time = time();

        /**
         * Socket连接信息
         */
	    $info = $serv->connection_info($client_id);
        $request->server['SWOOLE_CONNECTION_INFO'] = $info;
        $request->remote_ip = $info['remote_ip'];
        $request->remote_port = $info['remote_port'];
        /**
         * Server变量
         */
        $request->server['REQUEST_URI'] = $request->meta['uri'];
        $request->server['REMOTE_ADDR'] = $request->remote_ip;
        $request->server['REMOTE_PORT'] = $request->remote_port;
        $request->server['REQUEST_METHOD'] = $request->meta['method'];
        $request->server['REQUEST_TIME'] = $request->time;
        $request->server['SERVER_PROTOCOL'] = $request->meta['protocol'];
        if (!empty($request->meta['query']))
        {
            $_SERVER['QUERY_STRING'] = $request->meta['query'];
        }
        $request->setGlobal();
        $this->parseRequest($request);
        $this->currentRequest = $request;
        //处理请求，产生response对象
        $response = $this->onRequest($request);
        if ($response and $response instanceof Swoole\Response)
        {
            //发送response
            $this->response($request, $response);
        }
    }
1086915
public function create(ServerRequestInterface $request): ResponseInterface
    {
        $tree_name  = $request->get('tree_name', '');
        $tree_title = $request->get('tree_title', '');

        // We use the tree name as a file name, so no directory separators allowed.
        $tree_name = basename($tree_name);

        if (Tree::findByName($tree_name)) {
            FlashMessages::addMessage(I18N::translate('The family tree “%s” already exists.', e($tree_name)), 'danger');

            $url = route('admin-trees');
        } else {
            $tree = Tree::create($tree_name, $tree_title);
            FlashMessages::addMessage(I18N::translate('The family tree “%s” has been created.', e($tree->name())), 'success');

            $url = route('admin-trees', ['ged' => $tree->name()]);
        }

        return redirect($url);
    }
585018
public function handle(ServerRequestInterface $request, DelegateInterface $next)
    {
        $_SessionKey = $request->getParam('_SessionKey');
        if (empty($_SessionKey)) {
            $_data = array(
                'status' => 0,
                'msg' => '参数错误',
            );

            return json($_data);
        }

        return $next->process($request);
    }
1152398
public function handle(ServerRequestInterface $request)
    {
        $clientIpAddress = $request->getClientIpAddress();
        $debugIpAddresses = config('ipAddresses')->offsetGet('debug');

        if (in_array($clientIpAddress, $debugIpAddresses)) {
            $_ENV[ 'DEBUG_STAGE' ] = 'DEVELOPER';

            error_reporting(-1);
            ini_set('display_errors', 1);

            if (isset($_REQUEST[ 'PHP_INFO' ])) {
                phpinfo();
                exit(EXIT_SUCCESS);
            }
        } else {
            ini_set('display_errors', 0);
            error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
        }
    }
351951
public function onManagerStart(SwServer $server)
    {
        // {{
        $this->setRunUser();
        $this->setProcessName('manager');
        // }}

        // {{ log
        $this->get('logger')->info('启动 Manager 进程', [
            'pid' => $server->manager_pid
        ]);
        // }}
    }