Exemple #1
0
 public function __construct($config = [])
 {
     self::configure($config);
     $config = \SciActive\RequirePHP::_('NymphPubSubConfig');
     $this->loop = \React\EventLoop\Factory::create();
     // Create a logger which writes everything to the STDOUT
     $this->logger = new \Zend\Log\Logger();
     $this->writer = new \Zend\Log\Writer\Stream("php://output");
     $this->logger->addWriter($this->writer);
     // Create a WebSocket server using SSL
     try {
         $this->logger->notice("Nymph-PubSub server starting on {$config['host']}:{$config['port']}.");
     } catch (\Exception $e) {
         if (strpos($e->getMessage(), 'date.timezone')) {
             echo "It looks like you haven't set a default timezone. In order to avoid constant complaints from Zend's logger, I'm just going to kill myself now.\n\n";
             echo $e->getMessage() . "\n";
             exit;
         }
         throw $e;
     }
     $this->server = new WebSocketServer("tcp://{$config['host']}:{$config['port']}", $this->loop, $this->logger);
     // Create a router which transfers all /chat connections to the MessageHandler class
     $this->router = new \Devristo\Phpws\Server\UriHandler\ClientRouter($this->server, $this->logger);
     // route / url
     $this->router->addRoute('#^/#i', new MessageHandler($this->logger));
     // route unmatched urls
     $this->router->addRoute('#^(.*)$#i', new MessageHandlerForUnroutedUrls($this->logger));
     // Bind the server
     $this->server->bind();
 }
 public function setUp()
 {
     include __DIR__ . '/../bootstrapPostgreSQL.php';
     \SciActive\RequirePHP::_('Nymph', ['NymphConfig'], function ($NymphConfig) {
         $class = '\\Nymph\\Drivers\\' . $NymphConfig['driver'] . 'Driver';
         $Nymph = new $class($NymphConfig);
         return $Nymph;
     });
 }
 public static function sendMessage($message)
 {
     try {
         $config = \SciActive\RequirePHP::_('NymphPubSubConfig');
         $loop = \React\EventLoop\Factory::create();
         $logger = new \Zend\Log\Logger();
         $writer = new \Zend\Log\Writer\Stream("php://stderr");
         $logger->addWriter($writer);
         foreach ($config['entries'] as $host) {
             $client = new \Devristo\Phpws\Client\WebSocket($host, $loop, $logger);
             $client->on("connect", function () use($message, $client) {
                 $client->send($message);
                 $client->close();
             });
             $client->open();
         }
         $loop->run();
     } catch (\React\SocketClient\ConnectionException $e) {
         // Ignore a failed connection.
     }
 }
Exemple #4
0
<?php

error_reporting(E_ALL);
require '../vendor/autoload.php';
require '../src/autoload.php';
date_default_timezone_set('America/Los_Angeles');
\SciActive\RequirePHP::_('NymphConfig', [], function () {
    $nymph_config = (include __DIR__ . DIRECTORY_SEPARATOR . '../vendor/sciactive/nymph/conf/defaults.php');
    $nymph_config->MySQL->database['value'] = 'nymph_test';
    $nymph_config->MySQL->user['value'] = 'nymph_test';
    $nymph_config->MySQL->password['value'] = 'omgomg';
    return $nymph_config;
});
$NymphREST = new \Nymph\REST();
try {
    if (in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'DELETE'])) {
        parse_str(file_get_contents("php://input"), $args);
        $NymphREST->run($_SERVER['REQUEST_METHOD'], $args['action'], $args['data']);
    } else {
        $NymphREST->run($_SERVER['REQUEST_METHOD'], $_REQUEST['action'], $_REQUEST['data']);
    }
} catch (\Nymph\Exceptions\QueryFailedException $e) {
    echo $e->getMessage() . "\n\n" . $e->getQuery();
}
Exemple #5
0
<?php

// Get definitions.
$classes = get_declared_classes();
$definitions = [];
foreach ($classes as $key => $cur_class) {
    if (is_subclass_of($cur_class, '\\µMailPHP\\Definition')) {
        $definitions[$cur_class] = ['cname' => $cur_class::$cname, 'description' => $cur_class::$description, 'expectsRecipient' => $cur_class::$expectsRecipient, 'macros' => $cur_class::$macros, 'subject' => $cur_class::getSubject(), 'html' => $cur_class::getHTML()];
    }
}
$config = \SciActive\RequirePHP::_('µMailPHPConfig');
$examples = ['site_name' => $config->site_name['value'], 'site_link' => $config->site_link['value'], 'datetime_sort' => \µMailPHP\Mail::formatDate(time(), 'full_sort'), 'datetime_short' => \µMailPHP\Mail::formatDate(time(), 'full_short'), 'datetime_med' => \µMailPHP\Mail::formatDate(time(), 'full_med'), 'datetime_long' => \µMailPHP\Mail::formatDate(time(), 'full_long'), 'date_sort' => \µMailPHP\Mail::formatDate(time(), 'date_sort'), 'date_short' => \µMailPHP\Mail::formatDate(time(), 'date_short'), 'date_med' => \µMailPHP\Mail::formatDate(time(), 'date_med'), 'date_long' => \µMailPHP\Mail::formatDate(time(), 'date_long'), 'time_sort' => \µMailPHP\Mail::formatDate(time(), 'time_sort'), 'time_short' => \µMailPHP\Mail::formatDate(time(), 'time_short'), 'time_med' => \µMailPHP\Mail::formatDate(time(), 'time_med'), 'time_long' => \µMailPHP\Mail::formatDate(time(), 'time_long')];
?>
<!DOCTYPE html>
<html ng-app="setupApp">
  <head>
    <title>µMailPHP Setup App</title>
    <meta charset="utf-8">
    <script type="text/javascript">
      (function(){
        var s = document.createElement("script"); s.setAttribute("src", "https://www.promisejs.org/polyfills/promise-5.0.0.min.js");
        (typeof Promise !== "undefined" && typeof Promise.all === "function") || document.getElementsByTagName('head')[0].appendChild(s);
      })();
      NymphOptions = {
        restURL: <?php 
echo json_encode($restEndpoint);
?>
      };
      baseURL = <?php 
echo json_encode($baseURL);
?>
<?php

error_reporting(E_ALL);
require file_exists(__DIR__ . '/../vendor/autoload.php') ? __DIR__ . '/../vendor/autoload.php' : __DIR__ . '/../../autoload-dev.php';
use SciActive\RequirePHP;
RequirePHP::undef('NymphConfig');
RequirePHP::undef('Nymph');
$nymph_config = ['driver' => 'PostgreSQL'];
if (getenv('DATABASE_PGSQL')) {
    $dbopts = parse_url(getenv('DATABASE_PGSQL'));
    $nymph_config['PostgreSQL'] = ['database' => ltrim($dbopts["path"], '/'), 'host' => $dbopts["host"], 'port' => $dbopts["port"], 'user' => $dbopts["user"], 'password' => key_exists("pass", $dbopts) ? $dbopts["pass"] : ''];
} else {
    $nymph_config['PostgreSQL'] = ['database' => 'nymph_testing', 'user' => 'nymph_testing', 'password' => 'password'];
}
$nymph_config['pubsub'] = false;
\Nymph\Nymph::configure($nymph_config);
require_once 'TestModel.php';
Exemple #7
0
<?php

error_reporting(E_ALL);
// Composer autoloader would be fine in an outside project.
include '../vendor/autoload.php';
include '../src/autoload.php';
date_default_timezone_set('America/Los_Angeles');
// µMailPHP's config.
\SciActive\RequirePHP::_('µMailPHPConfig', [], function () {
    $config = (include '../conf/defaults.php');
    $config->site_name['value'] = 'µMailPHP Example Site';
    $config->site_link['value'] = 'http://localhost/umailphp/';
    $config->master_address['value'] = '*****@*****.**';
    $config->testing_mode['value'] = true;
    $config->testing_email['value'] = '*****@*****.**';
    return $config;
});
// This is how you enter the setup app.
include 'UserVerifyMail.php';
// Make sure all of your definition classes are loaded.
$baseURL = '../';
// This is the URL of the µMailPHP root.
$sciactiveBaseURL = '../bower_components/';
// This is the URL of the SciActive libraries.
$restEndpoint = 'rest.php';
// This is the URL of the Nymph endpoint.
include '../src/setup.php';
// And this will load the µMailPHP setup app.
Exemple #8
0
 protected function GET($action = '', $data = '')
 {
     if (!in_array($action, ['entity', 'entities', 'uid'])) {
         return $this->httpError(400, 'Bad Request');
     }
     $actionMap = ['entity' => 'getEntity', 'entities' => 'getEntities', 'uid' => 'getUID'];
     $method = $actionMap[$action];
     if (in_array($action, ['entity', 'entities'])) {
         $args = json_decode($data, true);
         if (is_int($args)) {
             try {
                 $result = Nymph::$method($args);
             } catch (\Exception $e) {
                 return $this->httpError(500, 'Internal Server Error', $e);
             }
         } else {
             $count = count($args);
             if ($count > 1) {
                 for ($i = 1; $i < $count; $i++) {
                     $newArg = self::translateSelector($args[$i]);
                     if ($newArg === false) {
                         return $this->httpError(400, 'Bad Request');
                     }
                     $args[$i] = $newArg;
                 }
             }
             try {
                 $result = call_user_func_array("\\Nymph\\Nymph::{$method}", $args);
             } catch (\Exception $e) {
                 return $this->httpError(500, 'Internal Server Error', $e);
             }
         }
         if (empty($result)) {
             if ($action === 'entity' || RequirePHP::_('NymphConfig')['empty_list_error']) {
                 return $this->httpError(404, 'Not Found');
             }
         }
         header('Content-Type: application/json');
         echo json_encode($result);
         return true;
     } else {
         try {
             $result = Nymph::$method("{$data}");
         } catch (\Exception $e) {
             return $this->httpError(500, 'Internal Server Error', $e);
         }
         if ($result === null) {
             return $this->httpError(404, 'Not Found');
         } elseif (!is_int($result)) {
             return $this->httpError(500, 'Internal Server Error');
         }
         header('Content-Type: text/plain');
         echo $result;
         return true;
     }
 }
Exemple #9
0
 /**
  * Send email.
  *
  * @return bool True on success, false on failure.
  */
 public function send()
 {
     // First verify values.
     if (!preg_match('/^.+@.+$/', $this->sender)) {
         return false;
     }
     if (!preg_match('/^.+@.+$/', $this->recipient)) {
         return false;
     }
     if (!$this->subject || strlen($this->subject) > 255) {
         return false;
     }
     $config = \SciActive\RequirePHP::_('µMailPHPConfig');
     // Headers that must be in the sent message.
     $required_headers = [];
     // Are we in testing mode?
     if ($config->testing_mode['value']) {
         // If the testing email is empty, just return true.
         if (empty($config->testing_email['value'])) {
             return true;
         }
         // The testing email isn't empty, so replace stuff now.
         // Save the original to, cc, and bcc in additional headers.
         $required_headers['X-Testing-Original-To'] = $this->recipient;
         foreach ($this->headers as $name => $value) {
             switch (strtolower($name)) {
                 case 'cc':
                     $this->headers['X-Testing-Original-Cc'] = $value;
                     $required_headers[$name] = '';
                     break;
                 case 'bcc':
                     $this->headers['X-Testing-Original-Bcc'] = $value;
                     $required_headers[$name] = '';
                     break;
             }
         }
         $to = $config->testing_email['value'];
         $subject = '*Test* ' . $this->subject;
     } else {
         $to = $this->recipient;
         $subject = $this->subject;
     }
     // Add from headers.
     $required_headers['From'] = $this->sender;
     $required_headers['Return-Path'] = $this->sender;
     $required_headers['Reply-To'] = $this->sender;
     $required_headers['X-Sender'] = $this->sender;
     $headers = $this->buildHeaders($required_headers);
     $message = $this->buildTextPart() . $this->buildAttachmentPart() . "--MIME_BOUNDRY--\n";
     // Now send the mail.
     return mail($to, $subject, $message, $headers, $config->additional_parameters['value']);
 }
 public function testInstantiate()
 {
     $nymph = \SciActive\RequirePHP::_('Nymph');
     $this->assertInstanceOf('\\Nymph\\Drivers\\DriverInterface', $nymph);
 }
Exemple #11
0
 /**
  * Make all selectors in the format:
  *
  * [
  *   0 => '&',
  *   'crit' => [
  *     ['value']
  *   ],
  *   'crit2' => [
  *     ['var', 'value']
  *   ],
  *   [
  *     0 => '|',
  *     'crit' => [
  *       ['value2']
  *     ]
  *   ]
  * ]
  *
  * @param array $selectors
  */
 public static function formatSelectors(&$selectors)
 {
     return RequirePHP::_('Nymph')->formatSelectors($selectors);
 }
 /**
  * Relay publish data to other servers.
  *
  * @param string $message The publish data to relay.
  */
 private function relay($message)
 {
     $config = \SciActive\RequirePHP::_('NymphPubSubConfig');
     if (!$config['relays']) {
         return;
     }
     $loop = \React\EventLoop\Factory::create();
     $logger = new \Zend\Log\Logger();
     $writer = new \Zend\Log\Writer\Stream("php://stderr");
     $logger->addWriter($writer);
     foreach ($config['relays'] as $host) {
         $client = new \Devristo\Phpws\Client\WebSocket($host, $loop, $logger);
         $client->on("connect", function () use($message, $client) {
             $client->send($message);
             $client->close();
         });
         $client->open();
     }
     $loop->run();
 }