Process publish messages sent by server

@param string $msg Message
@param int $qos QoS of message
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");
        }
    }
315582
protected function publish(AMQPMessage $message, $exchangeQueue, $routingKey, $publishChannels)
    {
        foreach ($publishChannels as $channel) {
            $channel->basic_publish($message, $exchangeQueue, $routingKey);
        }
    }
146726
public static function log($msg){
        Timer::add(1, function() use ($msg) {
            Worker::log($msg);
        }, null, false);
    }
413673
public function msgOk ($data = null, $groups = "", $message = "", $httpStatusCode = Response::HTTP_ACCEPTED)
    {
        return $this->responseOk ($data, $groups, $message, $httpStatusCode);
    }
774142
public function onWorkerHandlerMessage(ClientHandlerJobResponse $msg)
    {
        $this->workerHandlerReady = true;

        $requestId = $msg->getRequestId();
        if (isset($this->workerHandlerQueue[$requestId])) {
            unset($this->workerHandlerQueue[$requestId]);
        }

        $workerHandler = $msg->getWorkerHandlerId();
        $request       = $this->getRequest($requestId);

        if ($request === null) {
            $this->getLogger()->info(
                sprintf(
                    'WorkerHandler %s accepted request %s, but request is unknown.',
                    $workerHandler,
                    $requestId
                )
            );

            return;
        }

        $this->getLogger()->debug(
            sprintf(
                'Worker-handler %s accepted request: %s.',
                $workerHandler,
                $requestId
            )
        );

        $request->setWorkerHandlerId($workerHandler);
    }
335981
private function onMessage($msg, $socket) {
        try {
            $payload = @json_decode($msg, true);
            if (!$payload) {
                $this->response($socket, ['error' => 403, 'message' => 'error request']);

                return;
            }
            $command = isset($payload['command']) ? $payload['command'] : 'status';
            $service = isset($payload['args']['service']) ? $payload['args']['service'] : '';
            switch ($command) {
                case 'stop':
                    if ($service) {
                        $rst = $this->stopService($service);
                        $this->response($socket, ['status' => $rst ? 'done' : 'fail']);
                    } else {
                        $this->response($socket, ['status' => 'done']);
                        $this->shutdown = true;
                        $this->rSignal  = SIGTERM;
                    }
                    break;
                case 'start':
                    if ($service) {
                        $rst = $this->startService($service);
                        $this->response($socket, ['status' => $rst ? 'done' : 'fail']);
                    } else {
                        $this->response($socket, ['status' => 'fail']);
                    }
                    break;
                case 'reload':
                    $rst = $this->reloadConfig(null, $service);
                    $this->response($socket, ['status' => $rst ? 'done' : 'fail']);
                    break;
                case 'ps':
                    if ($service) {
                        if (isset($this->services[ $service ])) {
                            $pids = isset($this->services[ $service ]['pids']) ? $this->services[ $service ]['pids'] : [];
                            $this->response($socket, [
                                'ps'   => [$service => $pids],
                                'ssid' => posix_getpid()
                            ]);
                        } else {
                            $this->response($socket, ['ps' => [], 'ssid' => posix_getpid()]);
                        }
                    } else {
                        $ps = [];
                        foreach ($this->services as $s => $ser) {
                            $ps[ $s ] = isset($ser['pids']) ? $ser['pids'] : [];
                        }
                        $this->response($socket, ['ps' => $ps, 'ssid' => posix_getpid()]);
                    }
                    break;
                case 'status':
                default:
                    if ($service) {
                        if (isset($this->services[ $service ])) {
                            $this->response($socket, [
                                'status' => $this->services[ $service ]['status'],
                                'detail' => $this->services[ $service ]
                            ]);
                        } else {
                            $this->response($socket, ['status' => 'unknown', 'detail' => []]);
                        }
                    } else {
                        $this->response($socket, ['status' => 'running', 'services' => $this->services]);
                    }
            }
        } catch (\Exception $e) {
            $this->response($socket, ['error' => 500, 'msg' => $e->getMessage()]);
        }
    }
28108
public static function fromMessage(Message $msg)
    {
        $queueStatus = array();
        while ($msg->peek() !== null) {
            $action = $msg->shift();
            $queueStatus[$action] = array(
                'action'    => $action,
                'queue'     => $msg->shift(),
                'busy'      => $msg->shift(),
                'available' => $msg->shift()
            );
        }

        return new self($queueStatus);
    }
532917
public function msg($msg)
    {
        $this->log .= date('Y-m-d H:i:s') . ' ' . $msg . "\n";

        if (php_sapi_name() === 'cli') {
            $this->cli->line($msg);
        } else {
            echo $msg . "<br/>\n";
        }
    }
1016871
public function serverStopProcess($msg = null)
  {
    TeamSpeak3_Helper_Signal::getInstance()->emit("notifyServershutdown", $this);

    $this->execute("serverprocessstop", array("reasonmsg" => $msg));
  }
1145362
public function sendCustomServiceMessage(WxSendMsg $msg)
    {
        $url    = sprintf(self::CS_SEND_MESSAGE_URL, $this->getAccessTokenString());
        $client = $this->getHttpClient();
        $client->setUrl($url);
        $client->setHeaderArray(['Content-Type: application/json']);
        $client->setMethod(Client::METHOD_POST);
        $client->setPostFields($this->getFormatter()->toJsonString($msg));
        if (!$client->exec()) {
            throw new Exception("call send custom service message fail");
        }

        $result = json_decode($client->getResponse(), true);
        if (isset($result['errcode']) && isset($result['errmsg'])) {
            return (0 == $result['errcode']);
        }

        throw new Exception("error response for sending custom service message");
    }
86002
private static function addSSLValidator(Message $msg, $context) : void
    {
        $options = stream_context_get_options($context);
        if (!isset($options['ssl']['peer_certificate'])) {
            return;
        }

        $container = ContainerSingleton::getInstance();
        $key = openssl_pkey_get_public($options['ssl']['peer_certificate']);
        if ($key === false) {
            $container->getLogger()->warning('Unable to get public key from peer certificate.');

            return;
        }

        $keyInfo = openssl_pkey_get_details($key);
        if ($keyInfo === false) {
            $container->getLogger()->warning('Unable to get key details from public key.');

            return;
        }

        if (!isset($keyInfo['key'])) {
            $container->getLogger()->warning('Missing key in public key details.');

            return;
        }

        $msg->addValidator([SOAPClient::class, 'validateSSL'], $keyInfo['key']);
    }
949189
def _publish(self, msg):
        
        connection = self._connection.clone()
        publish = connection.ensure(self.producer, self.producer.publish,
                                    errback=self.__error_callback,
                                    max_retries=MQ_PRODUCER_MAX_RETRIES)
        publish(json.dumps(msg), exchange=self._exchange,
                routing_key=self._routing_key, declare=[self._queue])
        logging.debug('Publisher: message sent: %s', msg)
853570
public function publish($message)
    {
        /* @var Connection $conn */
        list($conn) = (yield $this->take());

        $conn->writeCmd(Command::publish($this->topic, $message));
        $this->stats["messagesPublished"]++;

        $timeout = NsqConfig::getPublishTimeout();
        $onTimeout = $this->onPublishTimeout($conn);
        $timerId = $this->getPublishTimeoutTimerId($conn);

        Timer::after($timeout, $onTimeout, $timerId);

        yield setContext("conn", $conn);
        yield $this;
    }
1149272
public function handle($msg)
    {
        if (!$msg instanceof JobMessage) {
            if ($this->logger) {
                $this->logger->info('No more message');
            }

            return false;
        }

        return $this->handleMsg($msg);
    }
1036167
public function pack($msg)
    {
        if (!$msg instanceof Message) {
            trigger_error("Given parameter is not a message instance.",
                          E_USER_ERROR);
            return;
        }

        // Set value using serialzed message.
        $this->value = $msg->serializeToString();

        // Set type url.
        $pool = \Google\Protobuf\Internal\DescriptorPool::getGeneratedPool();
        $desc = $pool->getDescriptorByClassName(get_class($msg));
        $fully_qualifed_name = $desc->getFullName();
        $this->type_url = GPBUtil::TYPE_URL_PREFIX.substr(
            $fully_qualifed_name, 1, strlen($fully_qualifed_name));
    }
1295866
public function sendByUserId(int $userId, string $msg, ?string $dest = null, bool $flush = false) : void
    {
        $msg = $this->composeMsg($msg, $dest);

        foreach ($this->subscriptionTable->findActive()->where('user_id', $userId) as $row)
        {
            $this->sendNotification($row, $msg, false);
        }

        if ($flush)
        {
            $this->flush();
        }
    }
595145
private function _log($resources, $msg = 'Disabled following resources:')
    {
        if ($this->enableLog) {
            $this->writeLog($msg . "\n" . var_export($resources, true));
        }
    }