Function vnmSendInviteRegister

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 2019-01-15 15:18

@param string $msisdn
@param string $package
@param string $channel
@param string $dataOptional

@return bool|null
186609
public function vnmSendInviteRegister($msisdn = '', $package = '', $channel = 'WAP', $dataOptional = '')
    {
        try {
            $telcoName = self::VIETNAMOBILE;
            $vnm       = new Vietnamobile($this->vendorDebug);
            $vnm->setHostname($this->providerServices[$telcoName]['hostname']);
            $vnm->setConfig($this->providerServices[$telcoName]);
            $serviceId = $this->providerServices[$telcoName]['serviceId'];
            $packageId = $this->providerServices[$telcoName]['package'][$package]['packageId'];
            $commandId = $this->providerServices[$telcoName]['package'][$package]['commandId'];
            $handle    = $vnm->sendInviteRegister($msisdn, $serviceId, $packageId, $commandId, $channel, $dataOptional);
            $this->logger->info(__FUNCTION__, 'Send OTP Result: ' . json_encode($handle));
            if (isset($handle->notify) && !empty($handle->notify)) {
                // Gửi lời mời đăng ký thành công
                $dataToSession = [
                    self::SESSION_ID_VNM_INVITE_REGISTER_NOTIFY_IS_OK => TRUE,
                    self::SESSION_ID_VNM_INVITE_REGISTER_NOTIFY       => isset($handle->notify) ? $handle->notify : NULL
                ];
                if (isset($this->objectSession) && $this->objectSession != NULL && is_object($this->objectSession)) {
                    $this->logger->info(__FUNCTION__, 'Session with CI Session Class');
                    $this->objectSession->set_userdata($dataToSession);
                } else {
                    $this->logger->info(__FUNCTION__, 'Session with The Http Foundation Component');
                    foreach ($dataToSession as $name => $value) {
                        $this->session->set($name, $value);
                    }
                }
                $this->logger->info(__FUNCTION__, 'Data to Session: ' . json_encode($dataToSession));

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

            return NULL;
        }
    }
540399
public function packageExists($namespace, $package)
    {
        $folder = $this->vendorFolder . $namespace;
        $folderExists = file_exists($folder);

        if (!$folderExists) {
            return false;
        }

        $packageFolder = $folder . '/' . $package;
        $packageFolderExists = file_exists($packageFolder);

        return $packageFolderExists;
    }
1342051
public function mpsRedirect($data = [], $resultIsUrl = FALSE)
    {
        try {
            $this->debug->info(__FUNCTION__, 'Input Params: ' . json_encode($data));
            $movitelMps = new MovitelMps\MovitelMps($this->options);
            $movitelMps->setMovitelPublicKey($this->movitelPublicKey);
            $movitelMps->setMovitelPrivateKey($this->movitelPrivateKey);
            $movitelMps->setCpPublicKey($this->cpPublicKey);
            $movitelMps->setCpPrivateKey($this->cpPrivateKey);
            $dataToRequest = "SUB=" . $data['sub'] . "&REQ=" . $data['req'] . "&SOURCE=" . $data['source'] . "&SESS=" . $data['session_id'];
            $dataLink      = "PRO=" . $data['provider'] . "&CMD=" . $data['cmd_msisdn'] . "&SER=" . $data['service'] . "&SUB=" . $data['sub'] . "&DATA=";
            $this->debug->info(__FUNCTION__, '$dataToRequest: ' . json_encode($dataToRequest));
            $this->debug->info(__FUNCTION__, '$dataLink: ' . json_encode($dataLink));
            $dataRequest = $movitelMps->createDataRequestToMps($data, $dataToRequest);
            $this->debug->info(__FUNCTION__, '$dataRequest: ' . json_encode($dataRequest));
            if ($dataRequest !== NULL && is_array($dataRequest)) {
                $dataEncrypted = $dataRequest[0];
                $dataSignature = $dataRequest[1];
                // Link
                $movitelRedirectUrl = $data['link'] . self::MSISDN_METHOD . '?' . $dataLink . urlencode($dataEncrypted) . '&SIG=' . $dataSignature;
                $this->debug->info(__FUNCTION__, '$movitelRedirectUrl: ' . json_encode($movitelRedirectUrl));
                if ($resultIsUrl === TRUE) {
                    $this->debug->info(__FUNCTION__, 'Result is URL');

                    return [
                        'status' => 'url',
                        'link'   => $movitelRedirectUrl
                    ];
                } else {
                    $this->debug->info(__FUNCTION__, 'Result is Redirect');
                    // Redirect url
                    Utils::redirect($movitelRedirectUrl);
                }
            }
            $this->debug->info(__FUNCTION__, 'Invalid Redirect URL');
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->debug->error(__FUNCTION__, $message);

            return NULL;
        }

        return NULL;
    }
699615
public function getRegistry($package = null)
    {
        if (isset($package)) {
            if ($this->registered($package)) {
                return $this->registry[ $package ];
            }

            return false;
        }

        return $this->registry;
    }
934356
public function signIn($msisdn = '', $password = '')
    {
        try {
            $inputParams = [
                'msisdn'   => $msisdn,
                'password' => $password
            ];
            $this->debug->info(__FUNCTION__, 'Input Params: ' . json_encode($inputParams));
            // Sử dụng API: /api/v1/utils/user/signin.html
            $loginUrl       = $this->hostname . $this->config[self::API_LOGIN]['path'];
            $loginToken     = $this->config[self::API_LOGIN]['token'];
            $loginPrefix    = $this->config[self::API_LOGIN]['prefix'];
            $loginSignature = md5($msisdn . $loginPrefix . $password . $loginPrefix . $loginToken);
            $loginParams    = [
                'msisdn'    => $msisdn,
                'password'  => $password,
                'signature' => $loginSignature
            ];
            $this->debug->debug(__FUNCTION__, '$loginUrl: ' . json_encode($loginUrl));
            $this->debug->debug(__FUNCTION__, '$loginToken: ' . json_encode($loginToken));
            $this->debug->debug(__FUNCTION__, '$loginPrefix: ' . json_encode($loginPrefix));
            $this->debug->debug(__FUNCTION__, '$loginSignature: ' . json_encode($loginSignature));
            $this->debug->debug(__FUNCTION__, '$loginParams: ' . json_encode($loginParams));
            $loginRequest = $this->requests->sendRequest($loginUrl, $loginParams, 'GET');
            $this->debug->info(__FUNCTION__, '$loginRequest: ' . json_encode($loginRequest));
            if ($loginRequest !== NULL) {
                if ($this->nativeSession === TRUE) {
                    $this->debug->info(__FUNCTION__, 'set native Session');
                    $phone_number = new Phone_number();
                    $phone_number->setDebugStatus($this->options['debugStatus']);
                    $phone_number->setLoggerPath($this->options['debugLoggerPath']);
                    $phone_number->__construct();
                    $this->debug->info(__FUNCTION__, '$phone_number: ' . json_encode($phone_number));
                    $isMsisdn = $phone_number->format($msisdn);
                    $this->debug->info(__FUNCTION__, '$isMsisdn: ' . json_encode($isMsisdn));
                    Session::setUserdata(self::SESSION_MSISDN_DEFAULT, $isMsisdn);
                }

                return json_decode(trim($loginRequest));
            } else {
                $this->debug->warning(__FUNCTION__, 'Request Response is Empty');

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

            return NULL;
        }
    }
526856
function setDN($dn, $merge = false, $type = 'utf8String')
    {
        if (!$merge) {
            $this->dn = null;
        }

        if (is_array($dn)) {
            if (isset($dn['rdnSequence'])) {
                $this->dn = $dn; // No merge here.
                return true;
            }

            // handles stuff generated by openssl_x509_parse()
            foreach ($dn as $prop => $value) {
                if (!$this->setDNProp($prop, $value, $type)) {
                    return false;
                }
            }
            return true;
        }

        // handles everything else
        $results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=|postalAddress=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE);
        for ($i = 1; $i < count($results); $i+=2) {
            $prop = trim($results[$i], ', =/');
            $value = $results[$i + 1];
            if (!$this->setDNProp($prop, $value, $type)) {
                return false;
            }
        }

        return true;
    }
976932
private function processMessage($msg, $qos)
    {
        // Package starts with topic
        $tlen = (ord($msg{0})<<8) + ord($msg{1});
        $msg_topic = substr($msg,2,$tlen);

        // QoS 1 and 2 packets also contain identifier
        $msg_id = null;
        if($qos == 0) {
            $msg = substr($msg,$tlen+2);
        } else {
            $msg_id = substr($msg,$tlen+2,2);
            $msg = substr($msg,$tlen+4);
        }

        // Then comes the message itself
        $found = false;
        foreach($this->topics as $topic=>$data) {

            $t_topic = str_replace("+","[^/]*", $topic);
            $t_topic = str_replace("/","\/",$t_topic);
            $t_topic = str_replace("$","\$",$t_topic);
            $t_topic = str_replace("#",".*",$t_topic);

            if(!preg_match("/^".$t_topic."$/", $msg_topic)) {
                continue;
            }

            $found = true;

            $this->debugMessage("Packet received (QoS: ".$qos." ; topic: ".$msg_topic." ; msg: ".$msg.")",2);

            // Is callback for this topic set?
            if(isset($data["function"]) && is_callable($data["function"])) {
                call_user_func($data["function"], $msg_topic, $msg, $qos);
            }
        }

        //
        if(!$found) {
            $this->debugMessage("Package received, but it doesn't match subscriptions");
        }

        // QoS 1 package requires PUBACK packet
        if($qos==1) {
            $this->debugMessage("Packet with QoS 1 received, sending PUBACK");
            $payload = chr(0x40).chr(0x02).$msg_id;
            fwrite($this->socket, $payload, 4);
        }

        // QoS 2 package requires PUBRECT packet, but we won't give it :)
        if($qos==2) {
            // FIXME
            $this->debugMessage("Packet with QoS 2 received, but feature is not implemented");
        }
    }
1090438
public function simpleUnsubscribe($msisdn = '', $packageId = '')
    {
        $inputParams = [
            'msisdn'    => $msisdn,
            'packageId' => $packageId
        ];
        $this->debug->info(__FUNCTION__, 'Input Params: ' . json_encode($inputParams));
        $callUnsub = self::_requestWsdlServer($msisdn, $packageId, Carbon::now(self::DEFAULT_TIMEZONE)->format('YmdHis'), 1, 0, 'HUY');
        $this->debug->info(__FUNCTION__, 'Final Result: ' . json_encode($callUnsub));

        return $callUnsub;
    }
1347431
@Override
    public void registerDestination(boolean hasLocal,
                                    boolean isDeleted)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc,
                        "registerDestination",
                        new Object[] {
                                      Boolean.valueOf(hasLocal),
                                      Boolean.valueOf(isDeleted),
                                      this });
        // Dont register temporary destinations or system destinations.
        if (!_baseDestinationHandler.isTemporary() && !_baseDestinationHandler.isSystem())
        {
            if (_pToPLocalMsgsItemStream != null && !(_pToPLocalMsgsItemStream instanceof MQLinkMessageItemStream))
                _localisationManager.registerDestination();
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "registerDestination");
    }
488715
public function ModerationController_MergeDiscussions_Create($Sender) {
      $Session = Gdn::Session();
      $Sender->Form = new Gdn_Form();
      $Sender->Title(T('Merge Discussions'));

      $DiscussionModel = new DiscussionModel();
      $CheckedDiscussions = Gdn::UserModel()->GetAttribute($Session->User->UserID, 'CheckedDiscussions', array());
      if (!is_array($CheckedDiscussions))
         $CheckedDiscussions = array();
       
      $DiscussionIDs = $CheckedDiscussions;
      $Sender->SetData('DiscussionIDs', $DiscussionIDs);
      $CountCheckedDiscussions = count($DiscussionIDs);
      $Sender->SetData('CountCheckedDiscussions', $CountCheckedDiscussions);
      $Discussions = $DiscussionModel->SQL->WhereIn('DiscussionID', $DiscussionIDs)->Get('Discussion')->ResultArray();
      $Sender->SetData('Discussions', $Discussions);
      
      // Perform the merge
      if ($Sender->Form->AuthenticatedPostBack()) {
         // Create a new discussion record
         $MergeDiscussion = FALSE;
         $MergeDiscussionID = $Sender->Form->GetFormValue('MergeDiscussionID');
         foreach ($Discussions as $Discussion) {
            if ($Discussion['DiscussionID'] == $MergeDiscussionID) {
               $MergeDiscussion = $Discussion;
               break;
            }
         }
         if ($MergeDiscussion) {
            $ErrorCount = 0;
            
            // Verify that the user has permission to perform the merge.
            $Category = CategoryModel::Categories($MergeDiscussion['CategoryID']);
            if ($Category && !$Category['PermsDiscussionsEdit'])
               throw PermissionException('Vanilla.Discussions.Edit');
            
            // Assign the comments to the new discussion record
            $DiscussionModel->SQL
               ->Update('Comment')
               ->Set('DiscussionID', $MergeDiscussionID)
               ->WhereIn('DiscussionID', $DiscussionIDs)
               ->Put();
               
            $CommentModel = new CommentModel();
            foreach ($Discussions as $Discussion) {
               if ($Discussion['DiscussionID'] == $MergeDiscussionID)
                  continue;
               
               // Create a comment out of the discussion.
               $Comment = ArrayTranslate($Discussion, array('Body', 'Format', 'DateInserted', 'InsertUserID', 'InsertIPAddress', 'DateUpdated', 'UpdateUserID', 'UpdateIPAddress', 'Attributes', 'Spam', 'Likes', 'Abuse'));
               $Comment['DiscussionID'] = $MergeDiscussionID;
               
               $CommentModel->Validation->Results(TRUE);
               $CommentID = $CommentModel->Save($Comment);
               if ($CommentID) {
                  // Move any attachments (FileUpload plugin awareness)
                  if (class_exists('MediaModel')) {
                     $MediaModel = new MediaModel();
                     $MediaModel->Reassign($Discussion['DiscussionID'], 'discussion', $CommentID, 'comment');
                  }
                  
                  // Delete discussion that was merged
                  $DiscussionModel->Delete($Discussion['DiscussionID']);                  
               } else {
                  $Sender->InformMessage($CommentModel->Validation->ResultsText());
                  $ErrorCount++;
               }
            }
            // Update counts on all affected discussions.
            $CommentModel->UpdateCommentCount($MergeDiscussionID);
            $CommentModel->RemovePageCache($MergeDiscussionID);
   
            // Clear selections
            Gdn::UserModel()->SaveAttribute($Session->UserID, 'CheckedDiscussions', FALSE);
            ModerationController::InformCheckedDiscussions($Sender);
            if ($ErrorCount == 0)
               $Sender->RedirectUrl = Url("/discussion/$MergeDiscussionID/".Gdn_Format::Url($MergeDiscussion['Name']));
         }
      }
      
      $Sender->Render('MergeDiscussions', '', 'plugins/SplitMerge');
   }
1223644
protected function traceInternal($msg = null, $data = [], $function = null, $file = null, $line = null)
        {
            // Don't incur the overhead if not in debug mode
            if (!static::$debug) {
                return false;
            }

            // Log with last parameter as 'true' - last param will always be internal marker
            return $this->trace($msg, $data, $function, $file, $line, true);
        }
193856
private function sendEventMessage(Session $session, PublishMessage $msg, Subscription $subscription)
    {
        $sessionId             = $subscription->getSession()->getSessionId();
        $authroles             = [];
        $authid                = '';
        $authenticationDetails = $subscription->getSession()->getAuthenticationDetails();
        if ($authenticationDetails) {
            $authroles = $authenticationDetails->getAuthRoles();
            $authid    = $authenticationDetails->getAuthId();
        }

        if ((!$msg->excludeMe() || $subscription->getSession() != $session)
            && !$msg->isExcluded($sessionId)
            && $msg->isWhiteListed($sessionId)
            && $msg->hasEligibleAuthrole($authroles)
            && $msg->hasEligibleAuthid($authid)
        ) {
            $eventMsg = EventMessage::createFromPublishMessage($msg, $subscription->getId());
            if ($subscription->isDisclosePublisher() === true) {
                $eventMsg->disclosePublisher($session);
            }
            if ($this->getMatchType() !== 'exact') {
                $eventMsg->getDetails()->topic = $msg->getUri();
            }
            $subscription->sendEventMessage($eventMsg);
        }
    }
627111
private function checkMsgSignature($msg_signature, $timestamp, $nonce, $encrypt) {
		return \Yii::$app->security->compareString($this->sign([$this->manager->app->token, $timestamp, $nonce, $encrypt]), $msg_signature);
	}
1295634
public function addEntry($dn, $data)
    {
        $data = $this->normalizeData($data);

        if (! (@ldap_add($this->connection, $dn, $data))) {
            $code = @ldap_errno($this->connection);
            throw new PersistenceException(
                sprintf(
                    'Could not add entry %s: Ldap Error Code=%s - %s',
                    $dn,
                    $code,
                    ldap_err2str($code)
                )
            );
        }
    }
241426
private function checkDestination($package)
    {
        $question_helper = $this->getHelper('question');

        Installer::isValidDestination($this->destination . DS . $package->install_path);

        if (Installer::lastErrorCode() == Installer::IS_LINK) {
            $this->output->write("\x0D");
            $this->output->writeln('  |- Checking destination...  <yellow>symbolic link</yellow>');

            if ($this->all_yes) {
                $this->output->writeln("  |     '- <yellow>Skipped automatically.</yellow>");

                return false;
            }

            $question = new ConfirmationQuestion("  |  '- Destination has been detected as symlink, delete symbolic link first? [y|N] ",
                false);
            $answer = $question_helper->ask($this->input, $this->output, $question);

            if (!$answer) {
                $this->output->writeln("  |     '- <red>You decided to not delete the symlink automatically.</red>");

                return false;
            }

            unlink($this->destination . DS . $package->install_path);
        }

        $this->output->write("\x0D");
        $this->output->writeln('  |- Checking destination...  <green>ok</green>');

        return true;
    }
1208634
public function msend(Message $msg)
    {
        if (ZMQ::SOCKET_ROUTER === $this->getSocketType()) {
            $msg->prepend($msg->getRoutingInformation());
        }

        if ($this->verbose) {
            $this->getLogger()->debug('SEND: '.$this->id);
            $this->getLogger()->debug($msg);
        }
        $parts = $msg->toArray();
        $iMax = count($parts)-1;
        if ($iMax < 0) {
            throw new RuntimeException('No parts to send.');
        }
        for ($i = 0; $i < $iMax; $i++) {
            $this->send($parts[$i], ZMQ::MODE_SNDMORE);
        }
        $this->send($parts[$iMax]);
        if ($this->verbose) {
            $this->getLogger()->debug('Message sent.');
        }

        return $this;
    }
1255128
public function processRegister(Session $session, RegisterMessage $msg)
    {
        $registration = Registration::createRegistrationFromRegisterMessage($session, $msg);

        if (count($this->registrations) > 0) {
            // we already have something registered
            if ($this->getAllowMultipleRegistrations()) {
                return $this->addRegistration($registration, $msg);
            } else {
                // we are not allowed multiple registrations, but we may want
                // to replace an orphaned session
                $errorMsg = ErrorMessage::createErrorMessageFromMessage($msg, 'wamp.error.procedure_already_exists');

                $options = $msg->getOptions();
                // get the existing registration
                /** @var Registration $oldRegistration */
                $oldRegistration = $this->registrations[0];
                if (isset($options->replace_orphaned_session) && ($options->replace_orphaned_session === 'yes' || $options->replace_orphaned_session === true)) {
                    try {
                        $oldRegistration->getSession()->ping(5)
                            ->then(function ($res) use ($session, $errorMsg) {
                                // the ping came back - send procedure_already_exists
                                $session->sendMessage($errorMsg);
                            }, function ($r) use ($oldRegistration, $session, $registration, $msg) {
                                // bring down the exiting session because the
                                // ping timed out
                                $deadSession = $oldRegistration->getSession();

                                // this should do all the cleanup needed and remove the
                                // registration from this procedure also
                                $deadSession->shutdown();

                                // complete this registration now
                                return $this->addRegistration($registration, $msg);
                            });
                    } catch (\Exception $e) {
                        $session->sendMessage($errorMsg);
                    }
                } else {
                    $session->sendMessage($errorMsg);
                }
            }
        } else {
            // this is the first registration
            // setup the procedure to match the options
            $this->setDiscloseCaller($registration->getDiscloseCaller());
            $this->setAllowMultipleRegistrations($registration->getAllowMultipleRegistrations());
            $this->setInvokeType($registration->getInvokeType());

            return $this->addRegistration($registration, $msg);
        }
    }