Hàm gán MSISDN vào Session

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 10/18/18 14:27

@param string $msisdn MSISDN người dùng

@return bool TRUE nếu thành công, FALSE nếu có lỗi xảy ra
972398
public function setMsisdnToSession($msisdn = '')
    {
        try {
            if (isset($this->objectSession) && $this->objectSession != NULL && is_object($this->objectSession)) {
                $this->logger->info(__FUNCTION__, 'Session with CI Session Class');
                if ($this->objectSession->has_userdata(self::SESSION_ID_CURRENT_USER_MSISDN)) {
                    $this->objectSession->unset_userdata(self::SESSION_ID_CURRENT_USER_MSISDN);
                }
                $this->objectSession->set_userdata(self::SESSION_ID_CURRENT_USER_MSISDN, $this->formatMsisdn($msisdn));
            } else {
                $this->logger->info(__FUNCTION__, 'Session with The Http Foundation Component');
                $this->session->replace([self::SESSION_ID_CURRENT_USER_MSISDN => $this->formatMsisdn($msisdn)]);
            }

            return TRUE;
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->logger->error(__FUNCTION__, $message);

            return FALSE;
        }
    }
575490
public static function checkEcn($ecn)
    {
        $ecn = trim(StringUtils::removeHyphen($ecn));
        /*
         * ECN을 더이상 사용하지 않고, 그 대안으로 UCI를 사용하도록 하였다.
         * 기존에 ECN을 발급받은 도서들의 경우
         * UCI를 발급받지 않고,
         * ECN 번호 앞에 I410을 붙여 UCI 번호로 하기로 하였다.
         */
        $ecn = str_replace('I410', '', $ecn);

        if (mb_strlen($ecn) !== 23 || preg_match('/0{23}/', $ecn)) {
            throw new MsgException('ECN 형식에 맞지 않습니다.');
        }
    }
907743
function parseDSN($dsn) {
	 	if (is_array($dsn)) {
			return $dsn;
		} else {
		 	$dsn_match = "|^(?P<phptype>.*?)://(?P<parameters>.*?)/(?P<db>.*?)$|i";
		 	$parameter_match = "|^(?P<username>.*?):(?P<password>.*?)@(?P<hostspec>.*?)$|i";
		 	$args_match = '|^(?P<database>.*?)\?(?P<args>.*?)$|';

		 	/* First, pick out the phptype, database, and gunk in the middle */
			preg_match($dsn_match,$dsn,$matches['base']);
			/* Next, parse the gunk in the middle into username, host, and password */
			if (!empty($matches['base']['parameters'])) { preg_match($parameter_match,$matches['base']['parameters'],$matches['parameters']); }
			/* Then, parse the database to see if any commandline parameters were passed */
			if (substr_count($matches['base']['db'],"?") > 0) { preg_match($args_match,$matches['base']['db'],$matches['args']); }

			$retn = array();
			$retn['phptype'] = $matches['base']['phptype'];
			if (!empty($matches['base']['parameters']) && is_array($matches['parameters'])) {
			 	$retn['username'] = $matches['parameters']['username'];
			 	$retn['password'] = $matches['parameters']['password'];
			 	$retn['hostspec'] = $matches['parameters']['hostspec'];
			}
			if (!empty($matches['args']) && is_array($matches['args'])) {
			 	$retn['database'] = $matches['args']['database'];
			 	$retn['args'] = $this->parseDSN_args($matches['args']['args']);
			} else {
			 	$retn['database'] = $matches['base']['db'];
			}
			return $retn;
		}
    }
240993
public function send($msg)
    {
        if (!$this->url) {
            return false;
        }
        $data = ["msgtype" => "text", "text" => ["content" => $msg], "at" => ["isAtAll" => true]];
        $curl = new LCurl(LCurl::POST_JSON, 3);
        $result = $curl->post(
            $this->url,
            $data
        );
        if (!$result || (int)Arrays::get($result, 'errcode') != 0) {
            return false;
        }
        return true;
    }
119877
public function user_is_guest()
    {
        try {
            $data_to_session = [
                self::SESSION_ID_CURRENT_USER_MSISDN    => self::SESSION_CURRENT_MSISDN_IS_GUEST,
                self::SESSION_ID_CURRENT_MSISDN         => self::SESSION_CURRENT_MSISDN_IS_GUEST,
                self::SESSION_ID_CURRENT_MSISDN_CHANNEL => self::CHANNEL_IS_DETECT,
                self::SESSION_ID_CURRENT_TELCO_NAME     => self::SESSION_CURRENT_MSISDN_IS_GUEST,
                self::SESSION_ID_CURRENT_TELCO_ID       => 0,
                self::SESSION_ID_CURRENT_USER_IP        => $this->Ip->getIpByHaProxy(),
                self::SESSION_ID_MSISDN_HAS_DETECT      => TRUE,
                self::SESSION_ID_USER_LOGIN_STATUS      => FALSE
            ];
            $this->logger->info(__FUNCTION__, 'Save Guest Data: ', $data_to_session);
            if (isset($this->objectSession) && $this->objectSession != NULL && is_object($this->objectSession)) {
                $this->logger->info(__FUNCTION__, 'Session with CI Session Class');
                $this->objectSession->set_userdata($data_to_session);
            } else {
                $this->logger->info(__FUNCTION__, 'Session with The Http Foundation Component');
                foreach ($data_to_session as $name => $value) {
                    $this->session->set($name, $value);
                }
            }

            return TRUE;
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();

            return $message;
        }
    }
1343225
public function parseServerFirstMessage($msg)
    {
        $i = $r = $s = false;

        foreach (explode(',', $msg) as $val) {
            list($attr, $aval) = array_map('trim', explode('=', $val, 2));

            switch ($attr) {
            case 'i':
                $this->_iterations = intval($aval);
                $i = true;
                break;

            case 'r':
                /* Beginning of server-provided nonce MUST be the same as the
                 * nonce we provided. */
                if (strpos($aval, $this->_nonce) !== 0) {
                    return false;
                }
                $this->_nonce = $aval;
                $r = true;
                break;

            case 's':
                $this->_salt = base64_decode($aval);
                $s = true;
                break;
            }
        }

        if ($i && $r && $s) {
            $this->_authmsg .= ',' . $msg;
            return true;
        }

        return false;
    }
154011
public static function is_in_group($string, $usr = null) {
        if (!$usr) {
            $usr = Auth::userId();
        }
        if (!$usr) return false;
        $my_groups = Group::getMySkupinyNames($usr);
        if (is_array($string)) {
            foreach ($string as $str) {
                if (Group::is_in_group($str, $usr)) return true;
            }
            return false;
        }
        if (in_array($string, $my_groups)) {
            return true;
        } else {
            return false;
        }
    }
490655
public function send($msg): bool
    {
        // JSON encode message if supplied in array or object form
        if (is_array($msg) || is_object($msg)) {
            $msg = json_encode($msg);
        }

        // Ensure message is a string
        $msg = (string) $msg;

        // Check the message fits within the buffer
        if (strlen($msg) > $this->buffer) {
            throw new SocketCommunicationException('Tried to send data larger than buffer size of '.$this->buffer.' bytes. Recreate channel with a larger buffer to send this data');
        }

        // Pad the message to the buffer size
        $msg = str_pad($msg, $this->buffer, ' ');

        // Write the message to the socket
        return socket_write($this->socket, $msg, $this->buffer);
    }
49114
public function pass(CommitMessage $msg) : bool
    {
        $subjectLength = strlen($msg->getSubject());
        if ($subjectLength > $this->maxLength) {
            $this->hint .= ' (' . $subjectLength . ')';
            return false;
        }
        return true;
    }
391116
private function error($msg)
    {
        if (class_exists('\sasco\LibreDTE\Estado') and class_exists('\sasco\LibreDTE\Log')) {
            $msg = \sasco\LibreDTE\Estado::get(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg);
            \sasco\LibreDTE\Log::write(\sasco\LibreDTE\Estado::FIRMA_ERROR, $msg);
            return false;
        } else {
            throw new \Exception($msg);
        }
    }
173513
public function gc_session($max)
    {
        $old = time() - $max;
        $this->where('access', '<', $old)->trash();

        return true;
    }
1319126
public function isEsiDown(): bool
    {

        // Check if we may have hit an error threshold
        if ($this->isEsiRateLimited()) return true;

        // Get the latest ESI status.
        $status = Cache::remember('esi_db_status', 1, function () {

            return EsiStatus::latest()->first();
        });

        // If we don't have a status yet, assume everything is ok.
        if (! $status) return false;

        // If the data is too old, return false by default.
        // Not being able to ping ESI could be indicative
        // of many other problems.
        if ($status->created_at->lte(carbon('now')->subHours(2)))
            return true;

        // If the status is OK, yay.
        if ($status->status == 'ok')
            return false;

        return true;
    }
620893
public function ask($msg = '', $default = null)
	{
		$value = parent::ask($msg, $default);

		if (is_null($value))
		{
			return $value;
		}

		$value = strtolower($value);

		if (in_array($value, $this->trueAlias))
		{
			return true;
		}
		elseif (in_array($value, $this->falseAlias))
		{
			return false;
		}

		return $default;
	}
315809
public function dnExists($dn)
    {
        if (PEAR::isError($dn)) {
            return $dn;
        }
        if ($dn instanceof Net_LDAP2_Entry) {
             $dn = $dn->dn();
        }
        if (false === is_string($dn)) {
            return PEAR::raiseError('Parameter $dn is not a string nor an entry object!');
        }

        // search LDAP for that DN by performing a baselevel search for any
        // object. We can only find the DN in question this way, or nothing.
        $s_opts = array(
            'scope'      => 'base',
            'sizelimit'  => 1,
            'attributes' => '1.1' // select no attrs
        );
        $search = $this->search($dn, '(objectClass=*)', $s_opts);

        if (self::isError($search)) {
            return $search;
        }

        // retun wehter the DN exists; that is, we found an entry
        return ($search->count() == 0)? false : true;
    }
198091
public function requestMsisdn()
    {
        // Khởi tạo cấu hình Csp Config
        $cspConfig = $this->config[self::CSP_CONFIG];
        // Khởi tạo link callback Get Msisdn
        $linkCallbackGetMsisdn = trim($cspConfig['domainUrl']) . trim($cspConfig['callbackGetMsisdn']);
        // Redirect Params
        $params         = [
            'sp'   => $cspConfig['spNumber'],
            'link' => $this->encrypt($linkCallbackGetMsisdn)
        ];
        $cspRedirectUrl = $cspConfig['addressConnectGetMsisdn'] . '?' . http_build_query($params);
        // Debug
        $this->debug->debug(__FUNCTION__, '$cspConfig: ' . json_encode($cspConfig));
        $this->debug->debug(__FUNCTION__, '$linkCallbackGetMsisdn: ' . json_encode($linkCallbackGetMsisdn));
        $this->debug->debug(__FUNCTION__, '$params: ' . json_encode($params));
        $this->debug->info(__FUNCTION__, '$cspRedirectUrl: ' . json_encode($cspRedirectUrl));
        $this->debug->debug(__FUNCTION__, 'Request from IP: ' . json_encode($this->IP->getIpAddress()));
        // Chuyển hướng tới Csp MobiFone
        Utils::redirect($cspRedirectUrl);
    }
644750
private function checkForEnvironmentAccess(Node $node)
    {
        if ($this->isEnvironmentVariable($node)) {
            return true;
        }
        if ($node instanceof FunctionNode) {
            if ($node->getObject()) {
                return $this->checkForEnvironmentObject($node->getObject());
            }

            $function = $node;
        } elseif ($this->isFilterOperator($node)) {
            $function = $node->getChild(OperatorNode::OPERAND_RIGHT);
        } else {
            return false;
        }

        return $this->functionNeedsEnvironment($function);
    }
716687
public function addServer(string $dsn) : bool
    {
        try {
            $context = new \ZMQContext;
            $this->socket = $context->getSocket(\ZMQ::SOCKET_REQ);
            $this->socket->connect($dsn);
            $this->dsn = $dsn;
            return true;
        } catch (\ZMQException $e) {
            throw new ClientException($e->getMessage());
        }
    }