Handle a publish from a client.

@param ConnectionInterface $from
@param string $msg
@param array $data
543155
private function handlePublish(ConnectionInterface $from, $msg, $data) {
    if (isset($data['guid'])
        && (
          $data['event'] === 'delete'
          || (
            isset($data['entity'])
            && ($data['event'] === 'create' || $data['event'] === 'update')
          )
        )
      ) {
      // Publish is an entity.

      // Relay the publish to other servers.
      $this->relay($msg);

      $this->handlePublishEntity($from, $data);
    }

    if ((
          isset($data['name'])
          || (isset($data['oldName']) && isset($data['newName']))
        )
        && in_array(
            $data['event'],
            ['newUID', 'setUID', 'renameUID', 'deleteUID']
        )
      ) {
      // Publish is a UID.

      // Relay the publish to other servers.
      $this->relay($msg);

      $this->handlePublishUid($from, $data);
    }
  }
957493
final protected function publishDirectory($from, $to)
    {
        // Load mount manager
        $manager = new MountManager([
            'from' => new Flysystem(new LocalAdapter($from)),
            'to'   => new Flysystem(new LocalAdapter($to)),
        ]);

        // Copy directory to application
        foreach ($manager->listContents('from://', true) as $file) {
            if ($file['type'] !== 'file') {
                continue;
            }
            $manager->put(sprintf('to://%s', $file['path']), $manager->read(sprintf('from://%s', $file['path'])));
        }

        // Output status message
        $this->getCommand()->line(
            sprintf('<info>Copied %s</info> <comment>[%s]</comment> <info>To</info> <comment>[%s]</comment>',
                'Directory', str_replace(base_path(), '', realpath($from)), str_replace(base_path(), '', realpath($to)))
        );
    }
1164455
protected function publishDirectory($from, $to)
    {
        $manager = new MountManager([
            'from' => new Flysystem(new LocalAdapter($from)),
            'to' => new Flysystem(new LocalAdapter($to)),
        ]);

        foreach ($manager->listContents('from://', true) as $file) {
            if ($file['type'] === 'file' && (!$manager->has('to://' . $file['path']) || $this->option('force'))) {
                $manager->put('to://' . $file['path'], $manager->read('from://' . $file['path']));
            }
        }

        $this->status($from, $to, 'Directory');
    }
704189
private function handlePublishEntity(ConnectionInterface $from, $data) {
    $this->logger->notice(
        "Received an entity publish! ".
          "({$data['guid']}, {$data['event']}, {$from->resourceId})"
    );

    $etype = $data['etype'];

    if (!key_exists($etype, $this->querySubs)) {
      return;
    }

    foreach ($this->querySubs[$etype] as $curQuery => $curClients) {
      $updatedClients = new \SplObjectStorage();

      if ($data['event'] === 'delete' || $data['event'] === 'update') {
        // Check if it is in any client's currents.
        foreach ($curClients as $curClient) {
          $curData = $curClients[$curClient];
          if (in_array($data['guid'], $curData['current'])) {
            // Update currents list.
            $queryArgs = unserialize($curQuery);
            $this->prepareSelectors($queryArgs);
            $queryArgs[0]['source'] = 'client';
            $queryArgs[] = ['&', 'guid' => $data['guid']];
            $token = null;
            if ($this->sessions->contains($curClient)) {
              $token = $this->sessions[$curClient];
            }
            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              $user = \Tilmeld\Tilmeld::extractToken($token);
              if ($user) {
                // Log in the user for access controls.
                \Tilmeld\Tilmeld::fillSession($user);
              }
            }
            $current = call_user_func_array(
                "\Nymph\Nymph::getEntity",
                $queryArgs
            );

            if (isset($current)) {
              // Notify subscriber.
              $this->logger->notice(
                  "Notifying client of update! ".
                    "({$curClient->resourceId})"
              );
              if (is_callable([$current, 'updateDataProtection'])) {
                $current->updateDataProtection();
              }
              $curClient->send(json_encode([
                'query' => $curData['query'],
                'updated' => $data['guid'],
                'data' => $current
              ]));
            } else {
              $curData['current'] = array_diff(
                  $curData['current'],
                  [$data['guid']]
              );
              $curClients[$curClient] = $curData;

              // Notify subscriber.
              $this->logger->notice(
                  "Notifying client of removal! ".
                    "({$curClient->resourceId})"
              );
              $curClient->send(json_encode([
                'query' => $curData['query'],
                'removed' => $data['guid']
              ]));
            }

            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              // Clear the user that was temporarily logged in.
              \Tilmeld\Tilmeld::clearSession();
            }

            $updatedClients->attach($curClient);
          }
        }
      }

      if ($data['event'] === 'create' || $data['event'] === 'update') {
        // Check if it matches the query.
        $selectors = unserialize($curQuery);
        $this->prepareSelectors($selectors);
        $options = $selectors[0];
        unset($selectors[0]);
        $entityData = $data['entity']['data'];
        $entityData['cdate'] = $data['entity']['cdate'];
        $entityData['mdate'] = $data['entity']['mdate'];
        $entitySData = [];

        if (class_exists($options['class'])
            && class_exists($data['entity']['class'])
            && $options['class']::ETYPE === $data['entity']['class']::ETYPE
            && \Nymph\Nymph::checkData(
                $entityData,
                $entitySData,
                $selectors,
                $data['guid'],
                $data['entity']['tags']
            )
          ) {
          // It does match the query.
          foreach ($curClients as $curClient) {
            if ($updatedClients->contains($curClient)) {
              // The user was already notified. (Of an update.)
              continue;
            }

            // Check that the user can access the entity.
            $queryArgs = unserialize($curQuery);
            $this->prepareSelectors($queryArgs);
            $queryArgs[0]['source'] = 'client';
            $queryArgs[] = ['&', 'guid' => $data['guid']];
            $token = null;
            if ($this->sessions->contains($curClient)) {
              $token = $this->sessions[$curClient];
            }
            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              $user = \Tilmeld\Tilmeld::extractToken($token);
              if ($user) {
                // Log in the user for access controls.
                \Tilmeld\Tilmeld::fillSession($user);
              }
            }
            $current = call_user_func_array(
                "\Nymph\Nymph::getEntity",
                $queryArgs
            );

            if (isset($current)) {
              // Update the currents list.
              $curData = $curClients[$curClient];
              $curData['current'][] = $data['guid'];
              $curClients[$curClient] = $curData;

              // Notify client.
              $this->logger->notice(
                  "Notifying client of new match! ".
                    "({$curClient->resourceId})"
              );
              if (is_callable([$current, 'updateDataProtection'])) {
                $current->updateDataProtection();
              }
              $curClient->send(json_encode([
                'query' => $curData['query'],
                'added' => $data['guid'],
                'data' => $current
              ]));
            }

            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              // Clear the user that was temporarily logged in.
              \Tilmeld\Tilmeld::clearSession();
            }
          }
        }
      }
    }
  }
115780
protected function commandStop(array $data, ConnectionInterface $conn)
    {
        if ($this->output->isVeryVerbose()) {
            $conn->on('close', function () {
                $this->output->writeln('Stop command requested');
            });
        }

        $conn->end(json_encode([]));

        $this->shutdown();
    }
399347
public function processMessage(ConnectionInterface $conn, $data)
    {
        $array = json_decode($data, true);

        $method = 'command' . ucfirst($array['cmd']);
        if (is_callable([$this, $method])) {
            $this->$method($array, $conn);
        } else {
            throw new \Exception(sprintf('Command %s not found. Got %s', $method, $data));
        }
    }
120550
public static function sendToUDP(string $data, $addr, $port = 0, $from = -1) {
		self::$server->sendto($addr, $port, $data);
	}
604403
public function handleStart(ConnectionInterface $conn, array $data)
    {
        try {
            $payload = array_get($data, 'payload');
            $query = array_get($payload, 'query');

            if (is_null($query)) {
                throw new Exception('Missing query parameter from payload');
            }

            $variables = array_get($payload, 'variables');

            $document = Parser::parse($query);
            // @phan-suppress-next-line PhanUndeclaredProperty
            $operation = $document->definitions[0]->operation;
            $result = $this->execute($query, $payload, $variables);

            $response = [
                'type' => GQL_DATA,
                'id' => $data['id'],
                'payload' => $result
            ];

            $response = json_encode($response);

            if (false === $response) {
                throw new UnexpectedValueException('Could not encode response');
            }

            $conn->send($response);

            if ($operation == 'subscription') {
                $data['name'] = $this->getSubscriptionName($document);
                $data['conn'] = $conn;

                $this->subscriptions[$data['name']][] = $data;
                end($this->subscriptions[$data['name']]);
                $data['index'] = key($this->subscriptions[$data['name']]);

                $connSubscriptions = $this->connStorage->offsetExists($conn)
                    ? $this->connStorage->offsetGet($conn)
                    : [];
                $connSubscriptions[$data['id']] = $data;
                $this->connStorage->offsetSet($conn, $connSubscriptions);

                $this->callListener(ON_OPERATION, [$data, $this->rootValue, $this->context]);
            } else {
                $response = [
                    'type' => GQL_COMPLETE,
                    'id' => $data['id']
                ];

                $response = json_encode($response);

                if (false === $response) {
                    throw new UnexpectedValueException('Could not encode response');
                }

                $conn->send($response);
                $this->callListener(ON_OPERATION_COMPLETE, [$data, $this->rootValue, $this->context]);
            } //end if
        } catch (Exception $e) {
            $response = [
                'type' => GQL_ERROR,
                'id' => $data['id'],
                'payload' => $e->getMessage()
            ];

            $response = json_encode($response);

            if (false === $response) {
                throw new UnexpectedValueException('Could not encode response');
            }

            $conn->send($response);

            $response = [
                'type' => GQL_COMPLETE,
                'id' => $data['id']
            ];

            $response = json_encode($response);

            if (false === $response) {
                throw new UnexpectedValueException('Could not encode response');
            }

            $conn->send($response);
        } //end try
    }
257026
public function send($from, $fromName, $to, $toName, $subject, $content)
    {
        $transport = Swift_SmtpTransport::newInstance($this->smtp, $this->port)
            ->setUsername($this->username)
            ->setPassword($this->password);
        $mailer = Swift_Mailer::newInstance($transport);
//        $logger = new Swift_Plugins_Loggers_EchoLogger();
//        $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
        $message = Swift_Message::newInstance();
        $message->setEncoder(Swift_Encoding::get8BitEncoding())
            ->setSubject($subject)
            ->setFrom(array($from => $fromName))
            ->setTo(array($to => $toName))
            ->setBody($content, 'text/html');
//        $message->toString();
//        $logger->dump();
        $result = $mailer->send($message);
        return $result;
    }
199729
public function onSubscribe(ConnectionInterface $conn, $topic)
    {
        $this->console->info("onSubscribe: {$conn->WAMP->sessionId} topic: $topic {$topic->count()}");

        if (!array_key_exists($topic->getId(), $this->subscribedTopics)) {
            $this->subscribedTopics[$topic->getId()] = $topic;
            $this->console->info("subscribed to topic $topic");
        }
    }
976300
protected function publishDirectory($from, $to)
    {
        $this->moveManagedFiles(new MountManager([
            'from' => new Flysystem(new LocalAdapter($from)),
            'to' => new Flysystem(new LocalAdapter($to)),
        ]));
    }
658725
public function send($message, $from, $color = null)
    {
        $data = [
            'room_id' => $this->name,
            'message' => $message,
            'from' => $from
        ];

        if ($color) {
            $data['color'] = $color;
        }

        $this->connection->write('/v1/rooms/message', $data);
    }
121349
protected function commandReload(array $data, ConnectionInterface $conn)
    {
        // remove nasty info about worker's bootstrap fail
        $conn->removeAllListeners('close');

        if ($this->output->isVeryVerbose()) {
            $conn->on('close', function () {
                $this->output->writeln('Reload command requested');
            });
        }

        $conn->end(json_encode([]));

        $this->reloadSlaves();
    }
1101709
public function insert(string $from, array $data, array $options = [])
    {
        if (!$data) {
            throw new \RuntimeException('The data inserted into the database cannot be empty');
        }

        list($statement, $bindings) = $this->compileInsert($from, $data);

        if (isset($options['dumpSql'])) {
            return [$statement, $bindings];
        }

        $this->fetchAffected($statement, $bindings);

        // 'sequence' For special driver, like PgSQL
        return isset($options['sequence']) ? $this->lastInsertId($options['sequence']) : $this->lastInsertId();
    }
669124
public function handleData($socket, $data)
    {
        try
        {
            $this->component->handleMessage($socket->conn, new NetworkMessage($data));
        }
        catch (Error $ex)
        {
            $this->handleError($socket, $ex);
        }
        catch (Exception $ex)
        {
            $this->handleError($socket, $ex);
        }
    }
1181775
final protected function publishFile($from, $to)
    {
        // If destination directory doesn't exist,
        // we'll create before copying the config files
        $directoryDestination = dirname($to);
        if (!$this->files->isDirectory($directoryDestination)) {
            $this->files->makeDirectory($directoryDestination, 0755, true);
        }

        // Copy file to application
        $this->files->copy($from, $to);

        // Output status message
        $this->getCommand()->line(
            sprintf('<info>Copied %s</info> <comment>[%s]</comment> <info>To</info> <comment>[%s]</comment>',
                'File', str_replace(base_path(), '', realpath($from)), str_replace(base_path(), '', realpath($to)))
        );
    }
777073
public function onPipeMessage($serv, $fromWorkerId, $message)
    {
        parent::onPipeMessage($serv, $fromWorkerId, $message);
        $data = unserialize($message);
        switch ($data['type']) {
            case Macro::MSG_TYPR_ASYN:
                $this->asynPoolManager->distribute($data['message']);
                break;
        }
    }