Removed unrelated code base

This commit is contained in:
Romaric Mourgues
2023-03-24 16:04:47 +01:00
parent 10fe6f78d1
commit 8f4c059cb9
541 changed files with 16536 additions and 91302 deletions
-138
View File
@@ -1,138 +0,0 @@
### PhpStorm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
*.DS_Store
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
.idea/
# CMake
cmake-build-debug/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Ruby plugin and RubyMine
/.rakeTasks
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### PhpStorm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
.idea/sonarlint
### Symfony ###
# Cache and logs (Symfony2)
/app/cache/*
/app/logs/*
!app/cache/.gitkeep
!app/logs/.gitkeep
# Email spool folder
/app/spool/*
# Cache, session files and logs (Symfony3)
/var/cache/*
/var/logs/*
/var/sessions/*
!var/cache/.gitkeep
!var/logs/.gitkeep
!var/sessions/.gitkeep
# Parameters
/app/config/parameters.yml
/app/config/parameters.ini
# Managed by Composer
/app/bootstrap.php.cache
/var/bootstrap.php.cache
/bin/*
!bin/console
!bin/symfony_requirements
# Assets and user uploads
/web/bundles/
/web/uploads/
/web/upload/
/web/public/
# PHPUnit
/app/phpunit.xml
/phpunit.xml
# Build data
/build/
# Backup entities generated with doctrine:generate:entities command
**/Entity/*~
### Symfony Patch ###
/web/css/
/web/js/
docker-compose.yml
### Twake specific ###
/build/
/vendor/
### AWS ###
/app/config/aws_config.yml
### Test ###
/tests/code_coverage/
/web/detached/*
/drive/*
/web/medias/public/uploads/*
/app/Configuration/Parameters.php
/app/Configuration/certs/apns_prod.pem
/app/Configuration/certs/apns_dev.pem
/cache/
/backend/core/vendor/
cassandra.log
-148
View File
@@ -1,148 +0,0 @@
<?php
namespace App;
require_once __DIR__ . "/Common/BaseController.php";
require_once __DIR__ . "/Common/BaseBundles.php";
require_once __DIR__ . "/Common/BaseBundle.php";
require_once __DIR__ . "/Common/BaseRouting.php";
require_once __DIR__ . "/Common/BaseServices.php";
require_once __DIR__ . "/Common/Routing.php";
require_once __DIR__ . "/Common/Container.php";
require_once __DIR__ . "/Common/Services.php";
require_once __DIR__ . "/Common/Configuration.php";
require_once __DIR__ . "/Common/Providers.php";
require_once __DIR__ . "/Common/CommandsManager.php";
require_once __DIR__ . "/Common/Counter.php";
require_once __DIR__ . "/Configuration/Bundles.php";
require_once __DIR__ . "/Configuration/Configuration.php";
require_once __DIR__ . "/Configuration/Parameters.php";
require_once __DIR__ . "/Configuration/Providers.php";
require_once __DIR__ . "/Configuration/Commands.php";
use Common\CommandsManager;
use Common\Counter;
use Common\Routing;
use Common\Container;
use Common\Services;
use Common\Providers;
use Configuration\Bundles;
use Configuration\Commands;
use Configuration\Configuration;
use Configuration\Parameters;
use Pecee\SimpleRouter\SimpleRouter;
use Twake\Core\Services\DoctrineAdapter\CassandraSessionHandler;
class App
{
private $app_root_dir = "";
/** @var Routing */
private $routing_service = null;
/** @var Container */
private $container_service = null;
/** @var Services */
private $services_service = null;
/** @var Providers */
private $providers_service = null;
/** @var Counter */
private $counter = null;
public function __construct()
{
$bundles = (new Bundles())->getBundles();
$bundles_instances = [];
$this->app_root_dir = realpath(__DIR__ . "/../");
$this->routing_service = new Routing($this);
$this->container_service = new Container($this);
$this->services_service = new Services($this);
$this->providers_service = new Providers($this, new \Configuration\Providers());
// Import configuration
$this->container_service->import(new Configuration($this), "configuration");
$this->container_service->import(new Parameters($this), "parameters");
$this->counter = new Counter($this);
// Require and instanciate all defined bundles
foreach ($bundles as $bundle) {
if (file_exists(__DIR__ . "/../src/" . $bundle . "/Bundle.php")) {
require_once __DIR__ . "/../src/" . $bundle . "/Bundle.php";
$class_name = str_replace("/", "\\", $bundle) . "\\Bundle";
$bundles_instances[] = new $class_name($this);
} else {
error_log("No such bundle " . $bundle);
}
}
// Init routing for all bundles
foreach ($bundles_instances as $bundle_instance) {
$bundle_instance->init();
}
}
public function getRouting()
{
return $this->routing_service;
}
public function getContainer()
{
return $this->container_service;
}
public function getServices()
{
return $this->services_service;
}
public function getProviders()
{
return $this->providers_service;
}
public function getAppRootDir()
{
return $this->app_root_dir;
}
public function getCommands()
{
return $this->commands;
}
public function getCounter()
{
return $this->counter;
}
public function runCli()
{
if (php_sapi_name() == "cli") {
$this->commands = new CommandsManager($this, (new Commands())->commands);
($this->commands)->run();
}
}
public function run()
{
try{
SimpleRouter::start();
}catch(\Exception $err){
error_log($err);
http_response_code(500);
echo '{"error": "'.$err->getMessage().'"}';
}
}
}
-160
View File
@@ -1,160 +0,0 @@
<?php
namespace App;
require_once __DIR__ . "/Common/BaseController.php";
require_once __DIR__ . "/Common/BaseBundles.php";
require_once __DIR__ . "/Common/BaseBundle.php";
require_once __DIR__ . "/Common/BaseRouting.php";
require_once __DIR__ . "/Common/BaseServices.php";
require_once __DIR__ . "/Common/Routing.php";
require_once __DIR__ . "/Common/Container.php";
require_once __DIR__ . "/Common/Services.php";
require_once __DIR__ . "/Common/Configuration.php";
require_once __DIR__ . "/Common/Providers.php";
require_once __DIR__ . "/Common/CommandsManager.php";
require_once __DIR__ . "/Common/Counter.php";
require_once __DIR__ . "/Configuration/Bundles.php";
require_once __DIR__ . "/Configuration/Configuration.php";
require_once __DIR__ . "/Configuration/Parameters.php";
require_once __DIR__ . "/Configuration/Providers.php";
require_once __DIR__ . "/Configuration/Commands.php";
use Common\CommandsManager;
use Common\Counter;
use Common\Routing;
use Common\Container;
use Common\Services;
use Common\Providers;
use Configuration\Bundles;
use Configuration\Commands;
use Configuration\Configuration;
use Configuration\Parameters;
use Pecee\SimpleRouter\SimpleRouter;
use Twake\Core\Services\DoctrineAdapter\CassandraSessionHandler;
class App
{
private $app_root_dir = "";
/** @var Routing */
private $routing_service = null;
/** @var Container */
private $container_service = null;
/** @var Services */
private $services_service = null;
/** @var Providers */
private $providers_service = null;
/** @var Counter */
private $counter = null;
public function __construct()
{
$bundles = (new Bundles())->getBundles();
$bundles_instances = [];
$this->app_root_dir = realpath(__DIR__ . "/../");
$this->routing_service = new Routing($this);
$this->container_service = new Container($this);
$this->services_service = new Services($this);
$this->providers_service = new Providers($this, new \Configuration\Providers());
// Import configuration
$this->container_service->import(new Configuration($this), "configuration");
$this->container_service->import(new Parameters($this), "parameters");
$dsn = $this->getContainer()->getParameter("env.sentry");
if($dsn){
\Sentry\init(['dsn' => $dsn, 'error_types' => (E_ERROR | E_WARNING | E_PARSE)]);
}
$segment = $this->getContainer()->getParameter("env.segment");
$GLOBALS["segment_enabled"] = false;
if($segment){
$GLOBALS["segment_enabled"] = true;
\Segment::init($segment);
}
$this->counter = new Counter($this);
// Require and instanciate all defined bundles
foreach ($bundles as $bundle) {
if (file_exists(__DIR__ . "/../src/" . $bundle . "/Bundle.php")) {
require_once __DIR__ . "/../src/" . $bundle . "/Bundle.php";
$class_name = str_replace("/", "\\", $bundle) . "\\Bundle";
$bundles_instances[] = new $class_name($this);
} else {
error_log("No such bundle " . $bundle);
}
}
// Init routing for all bundles
foreach ($bundles_instances as $bundle_instance) {
$bundle_instance->init();
}
}
public function getRouting()
{
return $this->routing_service;
}
public function getContainer()
{
return $this->container_service;
}
public function getServices()
{
return $this->services_service;
}
public function getProviders()
{
return $this->providers_service;
}
public function getAppRootDir()
{
return $this->app_root_dir;
}
public function getCommands()
{
return $this->commands;
}
public function getCounter()
{
return $this->counter;
}
public function runCli()
{
if (php_sapi_name() == "cli") {
$this->commands = new CommandsManager($this, (new Commands())->commands);
($this->commands)->run();
}
}
public function run()
{
try{
SimpleRouter::start();
}catch(\Exception $err){
error_log($err);
http_response_code(500);
echo '{"error": "'.$err->getMessage().'"}';
}
}
}
@@ -1,132 +0,0 @@
<?php
namespace Common;
use App\App;
use Common\Http\Request;
use Common\Http\Response;
/**
* Bundles root file super class
*/
abstract class BaseBundle
{
/** @var App */
protected $app = null;
protected $routing_prefix = "";
protected $bundle_root = "";
protected $bundle_namespace = "";
protected $routes = [];
protected $services = [];
public function __construct(App $app)
{
$this->app = $app;
}
public function init()
{
}
/**
* Load routes from Bundle php configuration
*/
protected function initRoutes()
{
// For all defined route, create routing + connect lasy controller loader
$routing_service = $this->app->getRouting();
foreach ($this->routes as $route => $data) {
$final_route = preg_replace("/\\/+/", "/", $this->routing_prefix . "/" . $route);
$handler = null;
$methods = ["POST"];
if (is_string($data)) {
$handler = $data;
} else {
$handler = $data["handler"];
if (isset($data["methods"])) $methods = $data["methods"];
}
$security = [];
if (isset($data["security"])) $security = $data["security"];
$controller = explode(":", $handler);
$handler = $controller[1];
$controller = $controller[0];
foreach ($methods as $method) {
$method = strtolower($method);
if (!in_array($method, ["get", "post", "delete", "put"])) {
continue;
}
$that = $this;
$routing_service->addRoute($method, $final_route, function (Request $request = null) use ($that, $controller, $handler, $security) {
if (count($security) > 0) {
foreach ($security as $security_service) {
$service = $this->app->getServices()->get($security_service);
if ($service) {
$response = $service->applySecurity($request);
if ($response && $response !== true) {
return $response;
}
} else {
error_log("Missing security service " . $service);
}
}
}
$controller = $that->loadController($controller);
if (!$controller) {
return new Response("No controller " . $handler . " found", 500);
}
if (!method_exists($controller, $handler)) {
return new Response("No controller handler " . $handler . "->" . $handler . " found", 500);
}
return $controller->$handler($request ?: new Request());
});
}
}
}
/**
* Lasy load controller to handle request
* $controller : string
**/
private function loadController($controller)
{
$controller_file = $this->bundle_root . "/Controller/" . $controller . ".php";
if (file_exists($controller_file)) {
require_once $controller_file;
$class_name = $this->bundle_namespace . "\\Controller\\" . str_replace("/", "\\", $controller);
return new $class_name($this->app);
} else {
return null;
}
}
/**
* Load services to service manager
*/
protected function initServices()
{
$services_service = $this->app->getServices();
foreach ($this->services as $service_name => $service_relative_path) {
$service_path = preg_replace("/\\/+/", "/", $this->bundle_root . "/Services/" . $service_relative_path . ".php");
$service_class_name = preg_replace("/\\\\+/", "\\", $this->bundle_namespace . "\\Services\\" . str_replace("/", "\\", $service_relative_path));
$services_service->set($service_name, $service_path, $service_class_name);
}
}
}
@@ -1,18 +0,0 @@
<?php
namespace Common;
/**
* Bundles root file super class
*/
abstract class BaseBundles
{
protected $bundles = [];
public function getBundles()
{
return $this->bundles;
}
}
@@ -1,59 +0,0 @@
<?php
namespace Common;
use App\App;
use Common\Http\Response;
/**
* Controllers super class
*/
abstract class BaseController
{
/** @var App */
protected $app = null;
/** @var Container */
protected $container = null;
public function __construct(App $app)
{
$this->app = $app;
$this->container = $app->getContainer();
}
/* Get service */
public function get($key)
{
return $this->app->getServices()->get($key);
}
public function isConnected()
{
return $this->getUser() && !is_string($this->getUser());
}
public function getUser()
{
$request = $this->app->getRouting()->getCurrentRequest();
$user = $this->app->getServices()->get("app.session_handler")->getUser($request);
return $user ?: "anonymous"; //null is reserved to user == system
}
public function getParameter($key, $fallback = null)
{
return $this->app->getContainer()->getParameter($key) ?: $fallback;
}
public function redirect($url)
{
$response = new Response("");
$response->setHeader("Location: " . $url, true);
$response->sendHeaders();
exit();
}
}
@@ -1,22 +0,0 @@
<?php
namespace Common;
abstract class BaseRouting
{
protected $routing_prefix = "";
protected $routes = [];
public function getRoutes()
{
return $this->routes;
}
public function getRoutesPrefix()
{
return $this->routing_prefix;
}
}
@@ -1,15 +0,0 @@
<?php
namespace Common;
abstract class BaseServices
{
protected $services = [];
public function getServices()
{
return $this->services;
}
}
@@ -1,63 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: romaricmourgues
* Date: 17/02/2020
* Time: 14:19
*/
namespace Common\Commands;
use App\App;
class ContainerAwareCommand
{
/** @var App */
public $app;
public function __construct(App $app)
{
$this->configure();
$this->app = $app;
}
public function executeFromManager()
{
return $this->execute();
}
protected function getApp()
{
return $this->app;
}
protected function getContainer()
{
}
protected function setName()
{
return $this;
}
protected function setDescription()
{
return $this;
}
protected function addOption()
{
return $this;
}
protected function configure()
{
}
protected function execute()
{
}
}
@@ -1,61 +0,0 @@
<?php
namespace Common;
use App\App;
class CommandsManager
{
public $app;
public $commands = [];
public function __construct($app, $commands)
{
$this->app = $app;
$this->commands = $commands;
}
public function run()
{
array_shift($_SERVER["argv"]);
$command = array_shift($_SERVER["argv"]);
$arguments = $_SERVER["argv"];
if ($command && $this->commands[$command]) {
$this->execute($command, $arguments);
} else {
if ($command) {
error_log("Command \e[0;31;42m'" . $command . "'\e[0m was not found.");
}
$this->help();
}
}
public function execute($command, $arguments)
{
if (!isset($this->commands[$command])) {
return;
}
$command = new $this->commands[$command]($this->app);
$command->executeFromManager();
}
private function help()
{
error_log("\nAll commands:");
foreach ($this->commands as $name => $command) {
error_log("\e[0;31;42m" . $name . "\e[0m");
}
error_log("\n");
}
}
@@ -1,11 +0,0 @@
<?php
namespace Common;
/** All configuration super class */
abstract class Configuration
{
public $configuration = [];
}
@@ -1,52 +0,0 @@
<?php
namespace Common;
use App\App;
class Container
{
/** @var App */
private $app = null;
private $configuration = [];
public function __construct(App $app)
{
$this->app = $app;
}
public function import(Configuration $configuration, $name)
{
$this->configuration[$name] = $configuration->configuration;
}
public function getParameter($key)
{
return $this->get("parameters", $key);
}
public function hasParameter($key)
{
return !!$this->get("parameters", $key);
}
public function get($namespace, $key)
{
$key = explode(".", $key);
$obj = $this->configuration[$namespace];
$i = 0;
while (is_array($obj) && $i < count($key)) {
$obj = @$obj[$key[$i]];
if (is_object($obj) && is_subclass_of($obj, "Common\Configuration") && isset($obj->configuration)) {
$obj = $obj->configuration;
}
$i++;
}
return $obj;
}
}
-60
View File
@@ -1,60 +0,0 @@
<?php
namespace Common;
use App\App;
class Counter
{
private $counters = [];
private $timers_started = [];
private $timers_values = [];
private $dev_mode = false;
public function __construct(App $app)
{
$this->dev_mode = $app->getContainer()->getParameter("env.timer") == true;
}
public function incrementCounter($key)
{
if (!isset($this->counters["counter_" . $key])) {
$this->counters["counter_" . $key] = 0;
}
$this->counters["counter_" . $key]++;
}
public function readCounter($key)
{
return isset($this->counters["counter_" . $key]) ? $this->counters["counter_" . $key] : 0;
}
public function startTimer($key)
{
$this->timers_started[$key] = microtime(true);
}
public function stopTimer($key)
{
if (!isset($this->timers_values[$key])) {
$this->timers_values[$key] = 0;
}
$this->timers_values[$key] += microtime(true) - $this->timers_started[$key];
$this->counters["timer_" . $key] = $this->timers_values[$key];
}
public function readTimer($key)
{
return isset($this->counters["timer_" . $key]) ? $this->counters["timer_" . $key] : -1;
}
public function showResults()
{
if ($this->dev_mode) {
error_log(json_encode($this->counters, JSON_PRETTY_PRINT));
}
}
}
@@ -1,70 +0,0 @@
<?php
namespace Common\Http;
class Cookie
{
protected $name;
protected $value;
protected $expire;
protected $path;
private static $reservedCharsFrom = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"];
private static $reservedCharsTo = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C'];
public function __construct(string $name, string $value = null, $expire = 0, ?string $path = '/')
{
$this->name = $name;
$this->value = $value;
$this->expire = 0 < $expire ? (int)$expire : 0;
$this->path = empty($path) ? '/' : $path;
}
public function __toString()
{
$str = str_replace(self::$reservedCharsFrom, self::$reservedCharsTo, $this->name);
$str .= '=';
if ('' === (string)$this->value) {
$str .= 'deleted; expires=' . gmdate('D, d-M-Y H:i:s T', time() - 31536001) . '; Max-Age=0; SameSite=Lax; Secure';
} else {
$str .= rawurlencode($this->value);
if (0 !== $this->expire) {
$str .= '; expires=' . gmdate('D, d-M-Y H:i:s T', $this->expire) . '; Max-Age=' . $this->getMaxAge() . "; SameSite=Lax; Secure";
}
}
if ($this->path) {
$str .= '; path=' . $this->path;
}
return $str;
}
public function asArray()
{
return [str_replace(self::$reservedCharsFrom, self::$reservedCharsTo, $this->name), (string)$this->value, $this->expire];
}
public function getMaxAge()
{
$maxAge = $this->expire - time();
return 0 >= $maxAge ? 0 : $maxAge;
}
public function getName()
{
return $this->name;
}
public function getValue()
{
return $this->value;
}
}
@@ -1,44 +0,0 @@
<?php
namespace Common\Http;
class ParamBag
{
private $array = [];
public function __construct($array)
{
$this->array = $array;
}
public function all()
{
return $this->array;
}
public function get($key, $default = null)
{
return isset($this->array[$key]) ? $this->array[$key] : $default;
}
public function has($key)
{
return isset($this->array[$key]);
}
public function getBoolean($key, $default = false)
{
return isset($this->array[$key]) ? !!$this->array[$key] : $default;
}
public function getInt($key, $default = false)
{
return isset($this->array[$key]) ? intval($this->array[$key]) : $default;
}
public function reset($array)
{
$this->array = $array;
}
}
@@ -1,58 +0,0 @@
<?php
namespace Common\Http;
class Request
{
private $content = "";
/** @var ParamBag */
public $headers = [];
/** @var ParamBag */
public $query = [];
/** @var ParamBag */
public $request = [];
/** @var ParamBag */
public $cookies = [];
public $files = [];
public function __construct()
{
$this->headers = new ParamBag(getallheaders());
$this->content = file_get_contents('php://input');
$this->query = new ParamBag($_GET);
$this->request = new ParamBag($_POST);
$this->files = new ParamBag($_FILES);
//Get all cookies
$cookies = $_COOKIE;
$header_cookies = [];
try {
$all_cookies = isset(getallheaders()["All-Cookies"]) ? getallheaders()["All-Cookies"] : "[]";
$header_cookies = json_decode($all_cookies, 1);
} catch (\Exception $err) {
$header_cookies = [];
}
foreach ($header_cookies as $cookie) {
$cookies[$cookie[0]] = $cookie[1];
}
$this->cookies = new ParamBag($cookies);
if (count($this->request->all()) === 0 || 0 === strpos($this->headers->get('Content-Type'), 'application/json')) {
try{
$data = json_decode($this->getContent(), true);
$this->request = new ParamBag(is_array($data) ? $data : array());
}catch(\Exception $err){
//Nop
}
}
}
public function getContent()
{
return $this->content;
}
}
@@ -1,106 +0,0 @@
<?php
namespace Common\Http;
use WebSocket\Exception;
class Response
{
private $content = "";
private $status = 200;
private $cookies = [];
/** @var ParamBag */
public $headers = [];
public function __construct($content = "", $status = 200)
{
$this->setContent($content);
$this->httpStatus($status);
$this->headers = new ParamBag([]);
}
public function setHeader($header, $replace = true)
{
$headers = $this->headers->all();
$header = explode(":", $header);
$header_name = array_shift($header);
$header_value = join(":", $header);
$headers[$header_name] = $header_value;
$this->headers->reset($headers);
}
public function setCookie(Cookie $cookie)
{
$this->cookies[$cookie->getName()] = $cookie;
}
public function getCookiesValues()
{
$key_value = [];
foreach ($this->cookies as $name => $cookie) {
$key_value[$name] = $cookie->getValue();
}
return $key_value;
}
public function clearCookie($name)
{
$this->cookies[$name] = new Cookie($name, null, 1, "/");
}
public function getContent()
{
if (is_array($this->content)) {
$this->content["_cookies"] = $this->getCookiesValues();
return json_encode($this->content);
}
return $this->content;
}
public function setContent($content)
{
$this->content = $content;
}
public function httpStatus($code)
{
$this->status = $code;
}
public function getHttpStatus()
{
return $this->status;
}
public function sendHeaders()
{
if(headers_sent()){
return;
}
if (defined("TESTENV") && TESTENV) {
return;
}
$all_cookies = [];
foreach ($this->cookies as $cookie) {
header("Set-Cookie: " . $cookie, false);
$all_cookies[] = $cookie->asArray();
}
header("All-Cookies: " . json_encode($all_cookies), true);
foreach ($this->headers->all() as $name => $value) {
header($name . ": " . $value, true);
}
header("Access-Control-Expose-Headers: All-Cookies");
}
public function send()
{
$this->sendHeaders();
http_response_code($this->status);
if (is_array($this->content) && !headers_sent()) {
header('Content-Type: application/json; charset=utf-8');
}
echo $this->getContent();
}
}
@@ -1,95 +0,0 @@
<?php
namespace Common;
use App\App;
class Providers extends \Pimple\Container
{
/** @var App */
private $app = null;
/** @var \Configuration\Providers */
private $configuration = null;
private $services = [];
private $registered_services = [];
private $service_instances = [];
public $providers_options = [];
public function __construct(App $app, \Configuration\Providers $configuration)
{
$this->app = $app;
$this->configuration = $configuration;
foreach ($configuration->providers as $name => $provider_config) {
//Each provider expose multiple services
foreach ($provider_config["services"] as $service) {
$this->services[$service] = $provider_config;
}
}
$this->provider_config = new \Pimple\Container();
}
public function get($key)
{
if (isset($this->service_instances[$key])) {
return $this->service_instances[$key];
}
if (!isset($this->services[$key])) {
error_log($key . " service was not found");
return null;
}
$service_register_name = $this->services[$key]["register"];
if (empty($this->registered_services[$service_register_name])) {
if (isset($services[$key]["parameters"])) {
$parameters_key = $services[$key]["parameters"];
$parameters = $this->app->getContainer()->get("parameters", $parameters_key);
foreach ($parameters as $key => $parameter) {
$this->providers_options[$key] = $parameter;
}
}
if (isset($services[$key]["configuration"])) {
$parameters_key = $services[$key]["configuration"];
$parameters = $this->app->getContainer()->get("configuration", $parameters_key);
foreach ($parameters as $key => $parameter) {
$this->providers_options[$key] = $parameter;
}
}
$service = new $service_register_name();
$service->register($this->provider_config);
$this->registered_services[$service_register_name] = $service;
}
try {
$this->service_instances[$key] = $this->provider_config[$key];
} catch (\Exception $e) {
error_log($e);
}
return $this->service_instances[$key];
}
public function getContainer()
{
return $this->provider_config;
}
}
-146
View File
@@ -1,146 +0,0 @@
<?php
namespace Common;
use App\App;
use Common\Http\Request;
use Common\Http\Response;
use Pecee\SimpleRouter\SimpleRouter;
class Routing
{
/** @var App */
private $app = null;
private $routes = [];
private $routesToController = [];
private $request = null;
public function __construct(App $app)
{
$this->app = $app;
$this->request = new Request();
}
public function addRoute($method, $route, $callback)
{
$route = preg_replace("/^\//", "", $route);
$route = preg_replace("/\/$/", "", $route);
if (isset($this->routes[$route . ":" . $method])) {
error_log("Route " . $route . " was already defined.");
return;
}
$this->routes[$route . ":" . $method] = true;
$this->routesToController[$route . ":" . $method] = $callback;
if ($method == "get") {
$this->get($route, $callback);
} else if ($method == "post") {
$this->post($route, $callback);
} else if ($method == "put") {
$this->put($route, $callback);
} else if ($method == "delete") {
$this->delete($route, $callback);
} else {
error_log("Unable to register route " . $route . ": method " . $method . " is not implemented.");
}
}
public function get($route, $callback)
{
SimpleRouter::get($route, function () use ($callback) {
error_log("[Router] - GET " . $_SERVER["REQUEST_URI"]);
try {
$response = $this->beforeRender($callback($this->request));
$response->send();
} catch (\Exception $e) {
error_log($e);
}
});
}
public function post($route, $callback)
{
SimpleRouter::post($route, function () use ($callback) {
error_log("[Router] - POST " . $_SERVER["REQUEST_URI"]);
try {
$response = $this->beforeRender($callback($this->request));
$response->send();
} catch (\Exception $e) {
error_log($e);
}
});
}
public function put($route, $callback)
{
SimpleRouter::put($route, function () use ($callback) {
error_log("[Router] - PUT " . $_SERVER["REQUEST_URI"]);
try {
$response = $this->beforeRender($callback($this->request));
$response->send();
} catch (\Exception $e) {
error_log($e);
}
});
}
public function delete($route, $callback)
{
SimpleRouter::delete($route, function () use ($callback) {
error_log("[Router] - DELETE " . $_SERVER["REQUEST_URI"]);
try {
$response = $this->beforeRender($callback($this->request));
$response->send();
} catch (\Exception $e) {
error_log($e);
}
});
}
//Allow any origin
private function beforeRender(Response $response)
{
if (isset($_SERVER['HTTP_ORIGIN']) && strpos("http://localhost", $_SERVER['HTTP_ORIGIN']) == 0) {
$response->setHeader('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN'], true);
}
$response->setHeader('Access-Control-Allow-Headers: ' . 'authorization, Content-Type, *', true);
$response->setHeader('Access-Control-Allow-Credentials: ' . 'true', true);
$response->setHeader('Access-Control-Allow-Methods: ' . 'GET, POST', true);
$response->setHeader('Access-Control-Max-Age: ' . '600', true);
$length = strlen($response->getContent());
$response->setHeader('x-decompressed-content-length: ' . $length, true);
$content = $response->getContent();
return $response;
}
public function execute($method, $route, Request $request)
{
$this->request = $request;
$route = preg_replace("/^\//", "", $route);
$route = preg_replace("/\/$/", "", $route);
if (isset($this->routesToController[$route . ":" . strtolower($method)])) {
$response = $this->routesToController[$route . ":" . strtolower($method)]($request);
} else {
error_log(json_encode($route . ":" . strtolower($method)) . " does not exists.");
$response = new Response();
}
return $this->beforeRender($response);
}
public function getRoutes()
{
return array_keys($this->routes);
}
public function getCurrentRequest()
{
return $this->request;
}
}
@@ -1,58 +0,0 @@
<?php
namespace Common;
use App\App;
class Services
{
/** @var App */
private $app = null;
private $services = [];
private $services_instances = [];
public function __construct(App $app)
{
$this->app = $app;
}
public function set($key, $class_src_path, $class_name)
{
if (isset($this->services[$key])) {
error_log("The service " . $key . " is already defined.");
return;
}
$this->services[$key] = [
"src_path" => $class_src_path,
"name" => $class_name
];
}
/** Lasy instanciate service */
public function get($key)
{
if (!isset($this->services[$key])) {
error_log("The requested service " . $key . " is not defined.");
return null;
}
if (isset($this->services_instances[$key])) {
return $this->services_instances[$key];
}
require_once $this->services[$key]["src_path"];
$name = $this->services[$key]["name"];
$this->services_instances[$key] = new $name($this->app);
return $this->services_instances[$key];
}
public function isLoaded($key)
{
return isset($this->services[$key]);
}
}
@@ -1,43 +0,0 @@
<?php
namespace Configuration;
use Common\BaseBundles;
class Bundles extends BaseBundles
{
protected $bundles = [
"Twake/Core",
"Twake/Users",
"Twake/Calendar",
"Twake/Channels",
"Twake/Discussion",
"Twake/Drive",
"Twake/GlobalSearch",
"Twake/Market",
"Twake/Notifications",
"Twake/Tasks",
"Twake/Upload",
"Twake/Workspaces",
"DevelopersApiV1/Calendar",
"DevelopersApiV1/Channels",
"DevelopersApiV1/Core",
"DevelopersApiV1/Drive",
"DevelopersApiV1/General",
"DevelopersApiV1/Messages",
"DevelopersApiV1/Tasks",
"DevelopersApiV1/Users",
"AdministrationApi/Apps",
"AdministrationApi/Core",
"AdministrationApi/Counter",
"AdministrationApi/Group",
"AdministrationApi/Users",
"AdministrationApi/Workspaces",
"BuiltInConnectors/Common",
];
}
@@ -1,24 +0,0 @@
<?php
namespace Configuration;
class Commands
{
public $commands = [
"twake:schema:update" => "Twake\Core\Command\TwakeSchemaUpdateCommand",
"twake:init" => "Twake\Core\Command\InitCommand",
"twake:init_connector" => "BuiltInConnectors\Common\Command\InitConnector",
"twake:update_services_status" => "Twake\Core\Command\UpdateServicesStatusCommand",
"twake:routes" => "Twake\Core\Command\GetRoutesCommand",
"twake:tasks_check_reminders" => "Twake\Tasks\Command\TaskReminderCheckerCommand",
"twake:reindex" => "Twake\Core\Command\ReindexCommand",
"twake:mapping" => "Twake\Core\Command\MappingCommand",
"twake:calendar_check" => "Twake\Calendar\Command\ReminderCheckerCommand",
"twake:mails_queue" => "Twake\Core\Command\MailsQueueCommand",
"twake:notifications_mail" => "Twake\Notifications\Command\NotificationMailCommand",
"twake:preview_worker" => "Twake\Drive\Command\DrivePreviewCommand",
"twake:scheduled_notifications_consume_timetable" => "Twake\Core\Command\ScheduledNotificationsConsumeTimetable",
"twake:scheduled_notifications_consume_shard" => "Twake\Core\Command\ScheduledNotificationsConsumeShard",
];
}
@@ -1,22 +0,0 @@
<?php
namespace Configuration;
use App\App;
use Twake\Users\Services\UserProvider;
class Configuration extends \Common\Configuration
{
public $configuration = [];
public function __construct(App $app)
{
$this->configuration = [
"twig" => [
'cache' => '/cache/twig'
]
];
}
}
@@ -1,221 +0,0 @@
<?php
namespace Configuration;
class Parameters extends \Common\Configuration
{
public $configuration = [];
public function __construct()
{
$this->configuration = [
"env" => [
"type" => "prod",
"timer" => false,
"admin_api_token" => "",
"licence_key" => "",
"standalone" => true,
//"frontend_server_name" => "http://localhost:8000/", // define only if needed
"server_name" => "http://localhost:8000/",
"internal_server_name" => "http://nginx/"
],
"jwt" => [
"secret" => "supersecret",
"expiration" => 60*60, //1 hour
"refresh_expiration" => 60*60*24*31 //1 month
],
"node" => [
"api" => "http://node:3000/private/",
"secret" => "api_supersecret"
],
"db" => [
"driver" => "pdo_cassandra",
"host" => "scylladb",
"port" => 9042,
"dbname" => "twake",
"user" => "root",
"password" => "root",
"encryption_key" => "ab63bb3e90c0271c9a1c06651a7c0967eab8851a7a897766",
"replication" => "{'class': 'SimpleStrategy', 'replication_factor': '1'}",
"is_cassandra" => false
],
"es" => [
"host" => "elasticsearch:9200"
],
"queues" => [
"rabbitmq" => [
"use" => true,
"host" => "rabbitmq",
"port" => 5672,
"username" => "admin",
"password" => "admin",
"vhost" => false
]
],
"storage" => [
"drive_previews_tmp_folder" => "/tmp/",
"drive_tmp_folder" => "/tmp/",
"drive_salt" => "SecretPassword",
"providers" => [
[
"label" => "someOpenStack",
"type" => "openstack",
"use" => false,
"project_id" => "",
"auth_url" => "https//auth.cloud.ovh.net/v3",
"buckets_prefix" => "",
"disable_encryption" => false,
"buckets" => [
"fr" => [
"public" => "",
"private" => "",
"region" => "SBG5"
]
],
"user" => [
"id" => "",
"password" => "",
"domain_name" => "default"
]
],
[
"label" => "someS3",
"type" => "S3",
"base_url" => "http://127.0.0.1:9000",
"use" => false,
"version" => "latest",
"disable_encryption" => false,
"buckets_prefix" => "dev.",
"buckets" => [
"fr" => "eu-west-3"
],
"credentials" => [
"key" => "",
"secret" => ""
]
],
[
"label" => "someLocal",
"type" => "local",
"use" => true,
"disable_encryption" => false,
"location" => "../drive/",
"preview_location" => "../web/medias/",
"preview_public_path" => "/medias/"
],
],
],
"mail" => [
"sender" => [
"host" => "",
"port" => "",
"username" => "",
"password" => "",
"auth_mode" => "plain"
],
"template_dir" => "/src/Twake/Core/Resources/views/",
"twake_domain_url" => "https://twakeapp.com/",
"from" => "noreply@twakeapp.com",
"from_name" => "Twake",
"twake_address" => "Twake, 54000 Nancy, France",
"dkim" => [
"private_key" => "",
"domain_name" => '',
"selector" => ''
],
"mailjet"=> [
"contact_list_subscribe"=> false,
"contact_list_newsletter"=> false
]
],
"push_notifications" => [
"apns_certificate" => __DIR__ . "/certs/apns_prod.pem",
"firebase_api_key" => "KEY",
],
//Defaults values for all clients but editable in database
"defaults" => [
"applications" => [
"twake_drive" => [ "default" => true ], //False to not install
"twake_calendar" => [ "default" => true ],
"twake_tasks" => [ "default" => true ],
"connectors" => [
"jitsi" => [ "default" => true ],
]
],
"connectors" => [
],
"branding" => [
"name" => "Twake",
"enable_newsletter" => false,
/*
"header" => [
"logo" => 'https://openpaas.linagora.com/images/white-logo.svg',
"apps" => [
[
"name"=> 'Accueil',
"url"=> 'https://openpaas.linagora.com/',
"icon"=> 'https://openpaas.linagora.com/images/application-menu/home-icon.svg',
],
[
"name"=> 'Inbox',
"url"=> 'https://openpaas.linagora.com/#/unifiedinbox/inbox',
"icon"=> 'https://openpaas.linagora.com/unifiedinbox/images/inbox-icon.svg',
],
[
"name"=> 'Calendrier',
"url"=> 'https://openpaas.linagora.com/#/calendar',
"icon"=> 'https://openpaas.linagora.com/calendar/images/calendar-icon.svg',
],
[
"name"=> 'Contacts',
"url"=> 'https://openpaas.linagora.com/#/contact/addressbooks/',
"icon"=> 'https://openpaas.linagora.com/contact/images/contacts-icon.svg',
],
],
],
"style" => [
"color" => '#2196F3',
"default_border_radius" => '2',
],
"link" => "https://open-paas.org/",
"logo" => "https://open-paas.org/wp-content/uploads/2019/10/openpaas.png"
*/
],
"auth" => [
"internal" => [
"use" => true,
"disable_account_creation" => false,
"disable_email_verification" => true
],
"openid" => [
"use" => false,
"provider_uri" => 'https://auth0.com',
"client_id" => '',
"client_secret" => '',
//"disable_logout_redirect" => false
"provider_config" => [
//token_endpoint
//token_endpoint_auth_methods_supported
//userinfo_endpoint
//end_session_endpoint
//authorization_endpoint
]
],
"cas" => [
"use" => false,
"base_url" => '',
"email_key" => '',
"lastname_key" => '',
"firstname_key" => ''
],
"console" => [
"use" => false
]
]
],
];
}
}
@@ -1,16 +0,0 @@
<?php
namespace Configuration;
class Providers
{
public $providers = [
"doctrine" => [
"services" => [
"db"
],
"register" => "Twake\Core\Services\DoctrineAdapter\DoctrineServiceProvider",
]
];
}
-9
View File
@@ -1,9 +0,0 @@
#!/usr/bin/env php
<?php
require_once __DIR__.'/../vendor/autoload.php';
use App\App;
$app = new App();
$app->runCli();
-47
View File
@@ -1,47 +0,0 @@
{
"name": "twake/twake-core",
"authors": [
{
"name": "Romaric Mourgues",
"email": "romaric.mourgues@twakeapp.com"
}
],
"repositories": [
{
"type": "vcs",
"url": "https://github.com/Twake/Pusher"
}
],
"require": {
"php": ">=7.1",
"doctrine/orm": "^2.5",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/doctrine-cache-bundle": "^1.2",
"phpunit/phpunit": "5.7",
"aws/aws-sdk-php-symfony": "~2.0",
"php-opencloud/openstack": "^3.0",
"emojione/emojione": "3.1",
"swiftmailer/swiftmailer": "^6.0",
"twig/twig": "^2.12",
"doctrine/dbal": "~2.2",
"ramsey/uuid-doctrine": "^1.5",
"spatie/pdf-to-text": "*",
"soleon/sc-php": "^1.0",
"pecee/simple-router": "4.2.0.6",
"pimple/pimple": "~3.0",
"mxp100/pusher": "dev-twake-1.0 as 1.0",
"eluceo/ical": "^0.16.0",
"php-amqplib/php-amqplib": "^2.11",
"phpseclib/phpseclib": "^2.0",
"sentry/sdk": "^2.1",
"firebase/php-jwt": "^5.2",
"segmentio/analytics-php": "^1.5"
},
"autoload": {
"psr-4": {
"": "src/",
"Common\\": "app/Common",
"App\\": "app/"
}
}
}
-7547
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.
@@ -1,198 +0,0 @@
<?php
echo "Please confirm your action, it cannot be undone. IMPORTANT : this action should be done on a just cloned directory from git repository !!";
$line = readline("Press any key then press enter");
if(!$line){
die();
}
$exludedPathContaining = ["/.", "/src/Administration/", "/src/DevelopersApi/", "/tests", "/web/angular", "/web/app_dev.php", "/websocket_supervisor.sh", "/composer.lock", "/Ressources/Apis"];
$exludedLinesContaining = [" Administration\\", " DevelopersApi\\"];
function remove($path){
if (is_dir($path)) {
$objects = scandir($path);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($path."/".$object))
remove($path."/".$object);
else
unlink($path."/".$object);
}
}
rmdir($path);
}else{
unlink($path);
}
}
function getDirContents($dir){
global $exludedPathContaining, $exludedLinesContaining;
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(strpos($path."/", "generate_onpremise_version.php") !== false
|| strpos($path."/", "/drive/") !== false
|| strpos($path."/", "/vendor/") !== false){
continue;
}
$removed = false;
foreach ($exludedPathContaining as $filter) {
if(strpos($path."/", $filter) !== false){
remove($path);
$removed = true;
break;
}
}
if(!$removed){
if(!is_dir($path)) {
$extension = explode(".", $path);
$extension = end($extension);
if($extension!="phar") {
$content = file_get_contents($path);
$lines = explode("\n", $content);
$exclude = array();
$removing = false;
foreach ($lines as $line) {
$found = false;
foreach ($exludedLinesContaining as $contain) {
if (strpos($line, $contain) !== false) {
$found = true;
}
}
if (strpos($line, "[REMOVE_ONPREMISE]") !== false) {
$removing = true;
}
if (!$found && !$removing) {
if ($extension == "php") {
$line = str_replace(", $", ",$", $line);
$line = str_replace(") {", "){", $line);
$line = str_replace("if (", "if(", $line);
$line = str_replace("else {", "else{", $line);
$line = str_replace(" =", "=", $line);
$line = str_replace("= ", "=", $line);
$line = str_replace(" ? ", "?", $line);
$line = str_replace(" : ", ":", $line);
//Remove one line comments
$line = preg_replace_callback('/\/\/.*|\/\*[\s\S]*?\*\/|("(\\.|[^"])*")/m',
function ($matches) {
if (\is_array($matches) && (\count($matches) > 1)) {
return $matches[1];
} else {
return '';
}
}, $line);
if (strpos($line, "if") !== false || strpos($line, "else") !== false) {
$line .= "[ONPREMISE_LINE_BREAK]";
}
if (trim($line) != '') {
$exclude[] = trim($line);
}
} elseif ($extension == "yml") {
$splited = explode("#", $line);
if (count($splited) > 1 && trim($splited[0]) == "") {
array_pop($splited);
$line = implode("#", $splited);
}
if (trim($line) != '') {
$exclude[] = $line;
}
} else {
if (trim($line) != '') {
$exclude[] = $line;
}
}
}
if (strpos($line, "[/REMOVE_ONPREMISE]") !== false) {
$removing = false;
}
}
if ($extension == "php" && strpos($path . "/", "/src/") !== false) {
if (strpos($path . "/", "/Entity/") !== false) {
$content = implode("\n", $exclude);
} else {
$content = implode("", $exclude);
}
$content = str_replace("<?php ", "<?php", $content);
$content = str_replace("<?php", "<?php ", $content);
if (strpos($path . "/", "/Entity/") === false && strpos($path . "/", "/Controller/") === false) {
preg_match_all("/\\$[a-zA-Z_][a-zA-Z_0-9]+/", $content, $variables);
$variables = array_unique($variables[0]);
$replaceA = [];
$replaceB = [];
foreach ($variables as $variable) {
$variable = explode("$", $variable);
$variable = $variable[1];
if ($variable != 'this') {
$replaceA[] = '/\\$' . $variable . "([^a-zA-Z0-9_])/";
$replaceB[] = '$v' . md5($variable) . "$1";
if (!preg_match('/function +' . $variable . '\\(/', $content)) {
$replaceA[] = '/\\$this->' . $variable . "([^a-zA-Z0-9_])/";
$replaceB[] = '$this->v' . md5($variable) . "$1";
}
}
}
$content = preg_replace($replaceA, $replaceB, $content);
//Re replace class vars
preg_match_all("/var +\\$[a-zA-Z_][a-zA-Z_0-9]+/", $content, $variables);
$variables = array_unique($variables[0]);
$replaceA = [];
$replaceB = [];
foreach ($variables as $variable) {
$variable = explode(" ", $variable);
$variable = $variable[1];
$replaceA[] = '/\\$v' . md5($variable) . "([^a-zA-Z0-9_])/";
$replaceB[] = $variable . "$1";
}
$content = preg_replace($replaceA, $replaceB, $content);
}
if (strpos($path . "/", "/Entity/") === false) {
$content = preg_replace('!/\*.*?\*/!s', '', $content);
}
} else {
$content = implode("\n", $exclude);
}
$content = str_replace("[ONPREMISE_LINE_BREAK]", "\n", $content);
file_put_contents($path, $content);
}
} else if($value != "." && $value != "..") {
getDirContents($path);
}
}
}
}
getDirContents('./')
?>
-21
View File
@@ -1,21 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.8/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="tests/autoload.php"
convertNoticesToExceptions="false"
convertWarningsToExceptions="false"
>
<php>
<ini name="error_reporting" value="-1"/>
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
@@ -1,30 +0,0 @@
<?php
namespace AdministrationApi\Apps;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
use AdministrationApi\Apps\Resources\Routing;
use AdministrationApi\Apps\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
}
@@ -1,107 +0,0 @@
<?php
namespace AdministrationApi\Apps\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Apps extends BaseController
{
public function getAllApps(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$offset = $request->request->get("offset");
$limit = $request->request->get("limit");
$validate_struct = $validation->validateStructure(Array(), Array(), $limit, $offset);
if ($validate_struct) {
$apps = $this->get("administration.apps")->getAllApps($limit, $offset);
$data["data"] = $apps;
} else {
$data["errors"][] = "invalid_request_structure";
}
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
public function getOneApp(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$app_id = $request->request->get("id");
$app_service = $this->get("administration.apps");
$app = $app_service->getOneApp($app_id);
if ($app) {
$data["data"] = $app->getAsArray();
} else {
$data["errors"][] = "app_not_found";
}
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
public function toggleValidation(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$app_id = $request->request->get("id");
$app_service = $this->get("administration.apps");
$app = $app_service->toggleAppValidation($app_id);
if ($app) {
$data["data"] = "";
} else {
$data["errors"][] = "app_not_validated";
}
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
}
@@ -1,18 +0,0 @@
<?php
namespace AdministrationApi\Apps\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/backend/apps/";
protected $routes = [
"getApps" => ["handler" => "Apps:getAllApps", "methods" => ["POST"]],
"getOneApp" => ["handler" => "Apps:getOneApp", "methods" => ["POST"]],
"toggleValidation" => ["handler" => "Apps:toggleValidation", "methods" => ["POST"]],
];
}
@@ -1,14 +0,0 @@
<?php
namespace AdministrationApi\Apps\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"administration.apps" => "AdministrationApps",
// arguments: [ "@app.twake_doctrine" ]
];
}
@@ -1,72 +0,0 @@
<?php
namespace AdministrationApi\Apps\Services;
use App\App;
class AdministrationApps
{
private $em;
public function __construct(App $app)
{
$this->em = $app->getServices()->get("app.twake_doctrine");
}
public function getAllApps($limit, $offset)
{
$appsRepository = $this->em->getRepository("Twake\Market:Application");
$apps_entities = $appsRepository->findBy(array(), array(), $limit, $offset/*, "__TOKEN__id"*/);
$apps = array();
foreach ($apps_entities as $app) {
$apps[] = $app->getAsArray();
}
return $apps;
}
public function getOneApp($id)
{
$appsRepository = $this->em->getRepository("Twake\Market:Application");
$app_tab = $appsRepository->findBy(array("id" => $id));
$app = false;
if (count($app_tab) == 1) {
$app = $app_tab[0];
}
return $app;
}
public function toggleAppValidation($id)
{
$appsRepository = $this->em->getRepository("Twake\Market:Application");
$app_tab = $appsRepository->findBy(array("id" => $id));
$rep = false;
if (count($app_tab) == 1) {
if ($app_tab[0]->getPublic()) {
$app_tab[0]->setIsAvailableToPublic(!$app_tab[0]->getIsAvailableToPublic());
$this->em->persist($app_tab[0]);
$rep = true;
}
}
$this->em->flush();
return $rep;
}
}
@@ -1,24 +0,0 @@
<?php
namespace AdministrationApi\Core;
require_once __DIR__ . "/Resources/Services.php";
use AdministrationApi\Core\Resources\Routing;
use AdministrationApi\Core\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$this->services = (new Services())->getServices();
$this->initServices();
}
}
@@ -1,12 +0,0 @@
<?php
namespace AdministrationApi\Core\Controller;
use Common\BaseController;
class Base extends BaseController
{
}
@@ -1,14 +0,0 @@
<?php
namespace AdministrationApi\Core\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"administration.validation" => "ValidationService",
// arguments: [ %administration_token% ]
];
}
@@ -1,52 +0,0 @@
<?php
namespace AdministrationApi\Core\Services;
use App\App;
/**
* Class ValidationService
* @package AdministrationApi\Core\Services
*/
class ValidationService
{
/**
* @var string
*/
private $token;
/**
* ValidationService constructor.
* @param $token
*/
public function __construct(App $app)
{
$this->token = $app->getContainer()->getParameter('env.admin_api_token');
}
/**
* @param $token
* @return bool
*/
public function validateAuthentication($token)
{
return $token == $this->token;
}
/**
* @return bool
*/
public function validateStructure($filter, $sort, $limit, $page)
{
if ($limit <= 0) {
return false;
}
if ($page < 0) {
return false;
}
return true;
}
}
@@ -1,30 +0,0 @@
<?php
namespace AdministrationApi\Counter;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
use AdministrationApi\Counter\Resources\Routing;
use AdministrationApi\Counter\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
}
@@ -1,67 +0,0 @@
<?php
namespace AdministrationApi\Counter\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Counter extends BaseController
{
public function getCounter(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$keys = $request->request->get("key");
$begin_date = $request->request->get("begin");
$end_date = $request->request->get("end");
$counter_service = $this->get("administration.counter");
$counter_data = array();
if (is_array($keys)) {
foreach ($keys as $key) {
$counter_tab = $counter_service->getCounter($key, $begin_date, $end_date);
if ($counter_tab) {
$counter_data[$key] = $counter_tab;
}
}
if (count($counter_data) == 0) {
$data['errors'][] = "key_not_found";
}
} elseif ($keys) {
$counter_tab = $counter_service->getCounter($keys, $begin_date, $end_date);
if ($counter_tab) {
$counter_data[$keys] = $counter_tab;
} else {
$data['errors'][] = "counter_not_found";
}
} else {
$data['errors'][] = "key_not_found";
}
$data['data'] = $counter_data;
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
}
@@ -1,84 +0,0 @@
<?php
namespace AdministrationApi\Counter\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Counter
*
* @ORM\Table(name="stats_counter",options={"engine":"MyISAM", "scylladb_keys": {{"counter_key":"ASC", "date":"DESC"}} })
* @ORM\Entity()
*/
class StatsCounter
{
/**
* @ORM\Column(name="counter_key", type="string", length=50)
* @ORM\Id
*/
protected $counter_key;
/**
* @ORM\Column(name="date", type="integer")
* @ORM\Id
*/
protected $date;
/**
* @ORM\Column(name="value", type="twake_counter")
*/
protected $value;
public function __construct($counter_key, $date)
{
$this->counter_key = $counter_key;
$this->date = $date;
$this->value = 0;
}
/**
* @return mixed
*/
public function getCounterKey()
{
return $this->counter_key;
}
/**
* @return mixed
*/
public function getDate()
{
return $this->date;
}
/**
* @return mixed
*/
public function getValue()
{
return $this->value;
}
/**
* @param mixed $value BE CAREFUL THIS IS A COUNTER ! SO IT WILL BE AN ADD NOT A SET
*/
public function setIncrementValue($value)
{
$this->value = $value;
}
public function getAsArray()
{
$date = \DateTime::createFromFormat("d-m-Y", "01-01-" . intdiv($this->getDate(), 1000));
$days = $this->getDate() % 1000;
$date->add(new \DateInterval("P" . $days . "D"));
$date_string = date("d/m/Y", $date->getTimestamp());
return array(
"date" => $date_string,
"value" => $this->getValue()
);
}
}
@@ -1,16 +0,0 @@
<?php
namespace AdministrationApi\Counter\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/backend/counter/";
protected $routes = [
"getCounter" => ["handler" => "Counter:getCounter", "methods" => ["POST"]],
];
}
@@ -1,14 +0,0 @@
<?php
namespace AdministrationApi\Counter\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"administration.counter" => "CounterService",
// arguments: [ "@app.twake_doctrine" ]
];
}
@@ -1,79 +0,0 @@
<?php
namespace AdministrationApi\Counter\Services;
use AdministrationApi\Counter\Entity\StatsCounter;
use App\App;
class CounterService
{
private $em;
public function __construct(App $app)
{
$this->em = $app->getServices()->get("app.twake_doctrine");
}
public function incrementCounter($key, $increment = 1)
{
$counter_repository = $this->em->getRepository("AdministrationApi\Counter:StatsCounter");
$counter_tab = $counter_repository->findBy(Array('counter_key' => $key), array(), 1, null, 'date', 'DESC');
$last_counter = $counter_tab[0];
$date_int = intval(date("Y")) * 1000 + intval(date("z"));
if (!$counter_tab || $last_counter->getDate() != $date_int) {
$counter = new StatsCounter($key, $date_int);
if ($last_counter) {
$increment = $increment + $last_counter->getValue();
}
} else {
$counter = $last_counter;
}
if (!$increment) {
return;
}
$counter->setIncrementValue($increment);
$this->em->merge($counter);
$this->em->flush();
}
public function getCounter($key, $beginDate = null, $endDate = null)
{
$counter_repository = $this->em->getRepository("AdministrationApi\Counter:StatsCounter");
$counter_tab = $counter_repository->findBy(Array('counter_key' => $key), array(), 20, null, 'date', 'DESC');
$rep = false;
if ($beginDate) {
$beginValue = strtotime($beginDate);
$begin = intval(date('Y', $beginValue)) * 1000 + intval(date('z', $beginValue));
}
if ($endDate) {
$endValue = strtotime($endDate);
$end = intval(date('Y', $endValue)) * 1000 + intval(date('z', $endValue));
}
if ($counter_tab) {
$rep = array();
foreach ($counter_tab as $counter_entity) {
$afterBegin = !isset($begin) || $counter_entity->getDate() >= $begin;
$beforeEnd = !isset($end) || $counter_entity->getDate() <= $end;
if ($afterBegin && $beforeEnd) {
$rep[] = $counter_entity->getAsArray();
}
}
}
return $rep;
}
}
@@ -1,30 +0,0 @@
<?php
namespace AdministrationApi\Group;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
use AdministrationApi\Group\Resources\Routing;
use AdministrationApi\Group\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
}
@@ -1,248 +0,0 @@
<?php
namespace AdministrationApi\Group\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Group extends BaseController
{
public function getAllGroup(Request $request)
{
// $data = Array(
// "data" => Array(),
// "errors" => Array()
// );
//
// $validation = $this->get("administration.validation");
// $token = $request->request->get("token");
// $validate_token = $validation->validateAuthentication($token);
//
// if ($validate_token) {
//
// $offset = $request->request->get("offset");
// $limit = $request->request->get("limit");
//
// $validate_struct = $validation->validateStructure(Array(), Array(), $limit, $offset);
//
// if ($validate_struct) {
// $users = $this->get("administration.users")->getAllUsers($limit, $offset);
//
// $data["data"] = $users;
// } else {
// $data["errors"][] = "invalid_request_structure";
// }
// } else {
// $data["errors"][] = "invalid_authentication_token";
// }
//
// return new Response($data);
$scroll_id = $request->request->get("scroll_id");
// $scroll_id = "DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAezFnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtBZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FRAAAAAAAAB7UWeFZ5Z1FkT0VScXV4VVFzMWhyWWNRUQAAAAAAAAe2FnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtxZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FR";
// $repository = "Twake\Workspaces:Group";
if (isset($scroll_id) && isset($repository)) {
$globalresult = $this->get('globalsearch.pagination')->getnextelement($scroll_id, $repository);
} else {
$globalresult = $this->get('administration.group')->getAllGroups();
}
$data = Array("data" => $globalresult);
//return new Response("Hello !");
return new Response($data);
}
public function getAllWorkspace(Request $request)
{
$scroll_id = $request->request->get("scroll_id");
// $scroll_id = "DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAezFnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtBZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FRAAAAAAAAB7UWeFZ5Z1FkT0VScXV4VVFzMWhyWWNRUQAAAAAAAAe2FnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtxZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FR";
// $repository = "Twake\Workspaces:Group";
if (isset($scroll_id) && isset($repository)) {
$globalresult = $this->get('globalsearch.pagination')->getnextelement($scroll_id, $repository);
} else {
$globalresult = $this->get('administration.group')->getAllWorkspace();
}
$data = Array("data" => $globalresult);
//return new Response("Hello !");
return new Response($data);
}
public function getGroupbyname(Request $request)
{
$scroll_id = $request->request->get("scroll_id");
// $scroll_id = "DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAezFnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtBZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FRAAAAAAAAB7UWeFZ5Z1FkT0VScXV4VVFzMWhyWWNRUQAAAAAAAAe2FnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtxZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FR";
// $repository = "Twake\Workspaces:Group";
if (isset($scroll_id) && isset($repository)) {
$globalresult = $this->get('globalsearch.pagination')->getnextelement($scroll_id, $repository);
} else {
$options = Array(
"name" => "test"
);
$globalresult = $this->get('administration.group')->getGroupbyName($options);
}
$data = Array("data" => $globalresult);
//return new Response("Hello !");
return new Response($data);
}
public function getWpbyname(Request $request)
{
$scroll_id = $request->request->get("scroll_id");
// $scroll_id = "DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAezFnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtBZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FRAAAAAAAAB7UWeFZ5Z1FkT0VScXV4VVFzMWhyWWNRUQAAAAAAAAe2FnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtxZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FR";
// $repository = "Twake\Workspaces:Group";
if (isset($scroll_id) && isset($repository)) {
$globalresult = $this->get('globalsearch.pagination')->getnextelement($scroll_id, $repository);
} else {
$options = Array(
"name" => "test"
);
$globalresult = $this->get('administration.group')->getWpbyName($options);
}
$data = Array("data" => $globalresult);
//return new Response("Hello !");
return new Response($data);
}
public function getUserbyMail(Request $request)
{
$scroll_id = $request->request->get("scroll_id");
// $scroll_id = "DnF1ZXJ5VGhlbkZldGNoBQAAAAAAAAezFnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtBZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FRAAAAAAAAB7UWeFZ5Z1FkT0VScXV4VVFzMWhyWWNRUQAAAAAAAAe2FnhWeWdRZE9FUnF1eFVRczFoclljUVEAAAAAAAAHtxZ4VnlnUWRPRVJxdXhVUXMxaHJZY1FR";
// $repository = "Twake\Workspaces:Group";
if (isset($scroll_id) && isset($repository)) {
$globalresult = $this->get('globalsearch.pagination')->getnextelement($scroll_id, $repository);
} else {
$options = Array(
"mail" => "romar"
);
$globalresult = $this->get('administration.group')->getUserbyMail($options);
}
$data = Array("data" => $globalresult);
//return new Response("Hello !");
return new Response($data);
}
public function getOneGroup(Request $request)
{
// $data = Array(
// "data" => Array(),
// "errors" => Array()
// );
//
// $validation = $this->get("administration.validation");
// $token = $request->request->get("token");
// $validate_token = $validation->validateAuthentication($token);
//
// if ($validate_token) {
//
// $user_id = $request->request->get("id");
//
// $user_service = $this->get("administration.users");
//
// $user = $user_service->getOneUser($user_id);
//
// if ($user) {
//
// if ($user == "Error") {
// $data["errors"][] = "unknown_error";
// } else {
//
// $devices = $user_service->getUserDevices($user);
// $mails = $user_service->getUserMails($user);
// $workspaces = $user_service->getUserWorkspaces($user);
// $groups = $user_service->getUserGroups($user);
//
// $data["data"]["user"] = $user->getAsArray();
// $data["data"]["user"]["creation_date"] = $user->getCreationDate();
// $data["data"]["user"]["last_login"] = $user->getLastLogin();
// $data["data"]["devices"] = $devices;
// $data["data"]["mails"] = $mails;
// $data["data"]["workspaces"] = $workspaces;
// $data["data"]["groups"] = $groups;
// }
// } else {
// $data["errors"][] = "user_not_found";
// }
// } else {
// $data["errors"][] = "invalid_authentication_token";
// }
//
// return new Response($data);
}
public function findGroup(Request $request)
{
// $data = array(
// "data" => Array(),
// "errors" => Array()
// );
//
// $validation = $this->get("administration.validation");
// $token = $request->request->get("token");
// $validate_token = $validation->validateAuthentication($token);
//
// if ($validate_token) {
// $search_string = $request->request->get("search");
//
// $users_service = $this->get("administration.users");
//
// $users = $users_service->findUserByUsername($search_string);
//
// if (!$users) {
// $users = $users_service->findUserByEmail($search_string);
// }
//
// if (!$users) {
// $users = $users_service->findUserById($search_string);
// }
//
// if (!$users) {
//
// $advanced_search = $this->get("app.users");
//
// $search_words = explode(" ", $search_string);
//
// $users = $advanced_search->search($search_words, Array("allow_email" => true));
//
// }
//
// if (count($users) == 0) {
// $data['errors'][] = "user_not_found";
// } else {
// $data['data'] = $users;
// }
//
// } else {
// $data["errors"][] = "invalid_authentication_token";
// }
//
// return new Response($data);
}
}
@@ -1,21 +0,0 @@
<?php
namespace AdministrationApi\Group\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/backend/group/";
protected $routes = [
"getgroup" => ["handler" => "Group:getAllGroup", "methods" => ["POST"]],
"getwp" => ["handler" => "Group:getAllWorkspace", "methods" => ["POST"]],
"getgroupbyname" => ["handler" => "Group:getGroupbyname", "methods" => ["POST"]],
"getwpbyname" => ["handler" => "Group:getWpbyname", "methods" => ["POST"]],
"getuserbymail" => ["handler" => "Group:getUserbyMail", "methods" => ["POST"]],
];
}
@@ -1,14 +0,0 @@
<?php
namespace AdministrationApi\Group\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"administration.group" => "AdministrationGroup",
// arguments: [ "@app.twake_doctrine" ]
];
}
@@ -1,307 +0,0 @@
<?php
namespace AdministrationApi\Group\Services;
use App\App;
class AdministrationGroup
{
private $em;
private $list_group = Array("group" => Array(), "scroll_id" => "");
public function __construct(App $app)
{
$this->em = $app->getServices()->get("app.twake_doctrine");
}
public function getGroupbyName($options)
{
if (isset($options["name"])) {
$name = $options["name"];
$options = Array(
"repository" => "Twake\Workspaces:Group",
"index" => "group",
"size" => 10,
"query" => Array(
"bool" => Array(
"should" => Array(
"bool" => Array(
"filter" => Array(
"regexp" => Array(
"name" => ".*" . $name . ".*"
)
)
)
)
)
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
}
// search in ES
$result = $this->em->es_search($options);
//var_dump(json_encode($options,JSON_PRETTY_PRINT));
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $group) {
if($group && $group[0]){
$this->list_group["group"][] = Array($group[0]->getAsArray(), $group[1][0]);
}
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
public function getAllUsers()
{
$options = Array(
"repository" => "Twake\Users:User",
"index" => "users",
"size" => 10,
"query" => Array(
"match_all" => (object)[]
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $user) {
//var_dump($file->getAsArray());
$this->list_group["users"][] = Array($user[0]->getAsArray(), $user[1][0]);;
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
public function getWpbyName($options)
{
if (isset($options["name"])) {
$name = $options["name"];
$options = Array(
"repository" => "Twake\Workspaces:Workspace",
"index" => "workspace",
"size" => 10,
"query" => Array(
"bool" => Array(
"should" => Array(
"bool" => Array(
"filter" => Array(
"regexp" => Array(
"name" => ".*" . $name . ".*"
)
)
)
)
)
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
}
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $group) {
//var_dump($file->getAsArray());
$this->list_group["group"][] = Array($group[0]->getAsArray(), $group[1][0]);;
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
public function getAllGroup()
{
// $group = new Group("group_admin_test_2");
// $this->em->persist($group);
// $this->em->flush();
$options = Array(
"repository" => "Twake\Workspaces:Group",
"index" => "group",
"size" => 10,
"query" => Array(
"match_all" => (object)[]
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
//var_dump(json_encode($options,JSON_PRETTY_PRINT));
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $group) {
//var_dump($file->getAsArray());
$this->list_group["group"][] = Array($group[0]->getAsArray(), $group[1][0]);;
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
public function getAllWorkspace()
{
// $group = new Group("group_for_workspace_1");
// $this->em->persist($group);
// $this->em->flush();
//
// $wp = new Workspace("workspace_admin_test_1");
// $wp->setGroup($group);
// $this->em->persist($wp);
// $this->em->flush();
$options = Array(
"repository" => "Twake\Workspaces:Workspace",
"index" => "workspace",
"size" => 10,
"query" => Array(
"match_all" => (object)[]
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
//var_dump(json_encode($options,JSON_PRETTY_PRINT));
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $wp) {
$this->list_group["group"][] = Array($wp[0]->getAsArray(), $wp[1][0]);;
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
public function getUserbyMail($options)
{
if (isset($options["mail"])) {
$mail = $options["mail"];
//var_dump("passage");
$options = Array(
"repository" => "Twake\Users:Mail",
"index" => "mail",
"size" => 10,
"query" => Array(
"bool" => Array(
"should" => Array(
"bool" => Array(
"filter" => Array(
"regexp" => Array(
"mail" => ".*" . $mail . ".*"
)
)
)
)
)
),
);
}
// $mail = new Mail();
// $mail->setMail("romaric@twakemail.fr");
// $this->em->persist($mail);
// $this->em->flush();
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $mail) {
//var_dump($file->getAsArray());
$this->list_group["group"][] = $mail[0]->getUser()
->getId() . "";
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
}
@@ -1,30 +0,0 @@
<?php
namespace AdministrationApi\Users;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
use AdministrationApi\Users\Resources\Routing;
use AdministrationApi\Users\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
}
@@ -1,143 +0,0 @@
<?php
namespace AdministrationApi\Users\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Users extends BaseController
{
public function getAllUsers(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$repository = "Twake\Users:User";
$scroll_id = $request->request->get("scroll_id");
$options = Array();
if (isset($scroll_id) && isset($repository)) {
$options["scroll_id"] = $scroll_id;
}
$users = $this->get("administration.users")->getAllUsers($options);
$data["data"] = $users;
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
public function getOneUser(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$user_id = $request->request->get("id");
$user_service = $this->get("administration.users");
$user = $user_service->getOneUser($user_id);
if ($user) {
if ($user == "Error") {
$data["errors"][] = "unknown_error";
} else {
$devices = $user_service->getUserDevices($user);
$mails = $user_service->getUserMails($user);
$workspaces = $user_service->getUserWorkspaces($user);
$groups = $user_service->getUserGroups($user);
$data["data"]["user"] = $user->getAsArray();
$data["data"]["user"]["creation_date"] = $user->getCreationDate();
$data["data"]["user"]["last_login"] = $user->getLastLogin();
$data["data"]["devices"] = $devices;
$data["data"]["mails"] = $mails;
$data["data"]["workspaces"] = $workspaces;
$data["data"]["groups"] = $groups;
}
} else {
$data["errors"][] = "user_not_found";
}
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
public function findUser(Request $request)
{
$data = array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$search_string = $request->request->get("search");
$users_service = $this->get("administration.users");
$users = $users_service->findUserById($search_string);
if (count($users["users"]) == 0) {
$options = Array(
"mail" => $search_string
);
$users = $this->get('administration.users')->getUserbyMail($options);
}
if (count($users["users"]) == 0) {
$advanced_search = $this->get("app.users");
$options = array(
"name" => $search_string
);
$users = $advanced_search->search($options);
}
$data['data'] = $users;
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
}
@@ -1,18 +0,0 @@
<?php
namespace AdministrationApi\Users\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/backend/users/";
protected $routes = [
"getUsers" => ["handler" => "Users:getAllUsers", "methods" => ["POST"]],
"getOne" => ["handler" => "Users:getOneUser", "methods" => ["POST"]],
"findUser" => ["handler" => "Users:findUser", "methods" => ["POST"]],
];
}
@@ -1,14 +0,0 @@
<?php
namespace AdministrationApi\Users\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"administration.users" => "AdministrationUsers",
// arguments: [ "@app.twake_doctrine" ]
];
}
@@ -1,219 +0,0 @@
<?php
namespace AdministrationApi\Users\Services;
use App\App;
class AdministrationUsers
{
private $em;
private $list_user = Array("users" => Array(), "scroll_id" => "");
public function __construct(App $app)
{
$this->em = $app->getServices()->get("app.twake_doctrine");
}
public function getAllUsers($options)
{
$options = Array(
"repository" => "Twake\Users:User",
"index" => "users",
"scroll_id" => $options["scroll_id"],
"size" => 10,
"query" => Array(
"match_all" => (object)[]
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
foreach ($result["result"] as $user) {
if($user && $user[0]){
$user_tab = $user[0]->getAsArray();
$user_tab['mail'] = $this->getUserMails($user[0])[0];
$user_tab['phone_number'] = $user[0]->getPhone();
$user_tab['creation_date'] = $user[0]->getCreationDate();
$this->list_user["users"][] = Array($user_tab, $user[1][0]);
}
}
$this->list_user["scroll_id"] = $scroll_id;
return $this->list_user ?: null;
}
public function getUserMails($user)
{
if(is_string($user)){
$usersRepository = $this->em->getRepository("Twake\Users:User");
$user = $usersRepository->findBy(Array("user_id" => $user));
}
$mailsRepository = $this->em->getRepository("Twake\Users:Mail");
$mails_tab = $mailsRepository->findBy(Array("user_id" => $user));
$mails = array();
foreach ($mails_tab as $mail) {
$mails[] = $mail->getMail();
}
$mails[] = $user->getEmail()." (not verified)";
return $mails;
}
public function getOneUser($user_id)
{
try {
$usersRepository = $this->em->getRepository("Twake\Users:User");
$user = $usersRepository->find($user_id);
return $user;
} catch (\Exception $e) {
return "Error";
}
}
public function getUserDevices($user)
{
$devicesRepository = $this->em->getRepository("Twake\Users:Device");
$devices_tab = $devicesRepository->findBy(Array("user_id" => $user));
$devices = array();
foreach ($devices_tab as $device) {
$devices[] = $device->getAsArray();
}
return $devices;
}
public function getUserWorkspaces($user)
{
$workspacesLinkRepository = $this->em->getRepository("Twake\Workspaces:WorkspaceUser");
$workspacesRepository = $this->em->getRepository("Twake\Workspaces:Workspace");
$workspaces_tab = $workspacesLinkRepository->findBy(Array("user_id" => $user->getId()));
$workspaces = array();
foreach ($workspaces_tab as $workspace) {
$ws = $workspacesRepository->findOneBy(["id"=>$workspace->getWorkspaceId()]);
if($ws){
$workspaces[] = $ws->getAsArray($this->em);
}
}
return $workspaces;
}
public function getUserGroups($user)
{
$groupsRepository = $this->em->getRepository("Twake\Workspaces:GroupUser");
$groups_tab = $groupsRepository->findBy(Array("user_id" => $user->getId()));
$groups = array();
foreach ($groups_tab as $group) {
$groups[] = $group->getGroup()->getAsArray();
}
return $groups;
}
public function findUserById($id)
{
$usersRepository = $this->em->getRepository("Twake\Users:User");
$users = $usersRepository->findBy(Array("id" => $id));
$rep = array("users" => array(), "scroll_id" => "");
if (count($users) >= 1) {
foreach ($users as $user) {
$user_tab = $user->getAsArray();
$user_tab['mail'] = $user->getEmail();
$rep["users"][] = array($user_tab, null);
}
}
return $rep;
}
public function getUserbyMail($options)
{
if (isset($options["mail"])) {
$mail = $options["mail"];
//var_dump("passage");
$options = Array(
"repository" => "Twake\Users:Mail",
"index" => "mail",
"size" => 10,
"query" => Array(
"bool" => Array(
"should" => Array(
"bool" => Array(
"filter" => Array(
"regexp" => Array(
"mail" => ".*" . $mail . ".*"
)
)
)
)
)
),
);
}
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
foreach ($result["result"] as $mail) {
$mail = $mail[0];
$user_id = $mail->getUserId();
$user_tab = $user->getAsArray();
$user_tab['mail'] = $this->getUserMails($user_id)[0];
$user_tab['phone_number'] = $user->getPhone();
$user_tab['creation_date'] = $user->getCreationDate();
$this->list_user["users"][] = array($user_tab, null);
}
$this->list_user["scroll_id"] = $scroll_id;
return $this->list_user ?: null;
}
}
@@ -1,30 +0,0 @@
<?php
namespace AdministrationApi\Workspaces;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
use AdministrationApi\Workspaces\Resources\Routing;
use AdministrationApi\Workspaces\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
}
@@ -1,190 +0,0 @@
<?php
namespace AdministrationApi\Workspaces\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Groups extends BaseController
{
public function getAllGroups(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
// $page = $request->request->get("page");
// $limit = $request->request->get("limit");
// $offset = $page * $limit;
//
// $validate_struct = $validation->validateStructure(Array(), Array(), $limit, $offset);
//
// if ($validate_struct) {
// $groups = $this->get("administration.groups")->getAllGroups($limit,$offset);
//
// $data["data"] = $groups;
// } else {
// $data["errors"][] = "invalid_request_structure";
// }
$scroll_id = $request->request->get("scroll_id");
$repository = "Twake\Workspaces:Group";
$options = Array();
if (isset($scroll_id) && isset($repository)) {
$options["scroll_id"] = $scroll_id;
}
$globalresult = $this->get('administration.groups')->getAllGroups($options);
$data["data"] = $globalresult;
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
public function getOneGroup(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$id = $request->request->get("id");
$group_service = $this->get("administration.groups");
$group = $group_service->getOneGroup($id);
if ($group) {
$workspaces = $group_service->getGroupWorkspaces($group);
$members = $group_service->getGroupMembers($group);
$apps = $group_service->getGroupApps($group);
//TODO Get group Drive size
$data["data"]["group"] = $group->getAsArray();
$data["data"]["group"]["creation_data"] = $group->getOnCreationData();
$data["data"]["workspaces"] = $workspaces;
$data["data"]["members"] = $members;
$data["data"]["apps"] = $apps;
} else {
$data["errors"][] = "group_not_found";
}
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
public function findGroups(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$group_scroll_id = $request->request->get("group_scroll_id");
$repository = "Twake\Workspaces:Group";
$search_string = $request->request->get("search");
$data['data']['group'] = array();
$data['data']['workspaces'] = array();
$options = Array(
"name" => $search_string
);
if (isset($group_scroll_id) && isset($repository)) {
$options["scroll_id"] = $group_scroll_id;
}
$globalresult = $this->get('administration.groups')->getGroupbyName($options);
$group_service = $this->get("administration.groups");
foreach ($globalresult['group'] as $group) {
$id = $group[0]['id'];
$workspaces = $group_service->getGroupWorkspaces($id);
$data['data']['group'][] = $group[0];
$data['data']['workspaces'] = array_merge($data['data']['workspaces'], $workspaces);
}
$data['data']['group_scroll_id'] = $globalresult['scroll_id'];
$group = $group_service->getOneGroup($search_string);
if ($group) {
$data['data']['group'][] = $group->getAsArray();
}
$workspace_scroll_id = $request->request->get("workspace_scroll_id");
$repository = "Twake\Workspaces:Group";
if (isset($workspace_scroll_id) && isset($repository)) {
$globalresult = $this->get('globalsearch.pagination')->getnextelement($workspace_scroll_id, $repository);
} else {
$options = Array(
"name" => $search_string
);
$globalresult = $this->get('administration.workspaces')->getWpbyName($options);
}
foreach ($globalresult['workspace'] as $workspace) {
$data['data']['workspaces'][] = $workspace[0];
}
$data['data']['workspaces_scroll_id'] = $globalresult['scroll_id'];
$workspace_service = $this->get("administration.workspaces");
$workspace = $workspace_service->getOneWorkspace($search_string);
if ($workspace) {
$data['data']['workspaces'][] = $workspace->getAsArray($this->get("app.twake_doctrine"));
}
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
}
@@ -1,83 +0,0 @@
<?php
namespace AdministrationApi\Workspaces\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Workspaces extends BaseController
{
public function getOneWorkspace(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$id = $request->request->get("id");
$workspace_service = $this->get("administration.workspaces");
$workspace = $workspace_service->getOneWorkspace($id);
if ($workspace) {
$members = $workspace_service->getWorkspaceMembers($workspace);
$apps = $workspace_service->getWorkspaceApps($workspace);
$invited_mails = $workspace_service->getInvitedUsers($workspace);
$data["data"]["workspace"] = $workspace->getAsArray($this->get("app.twake_doctrine"));
$data["data"]["members"] = $members;
$data["data"]["apps"] = $apps;
$data["data"]["invited"] = $invited_mails;
//TODO Infos du workspace a recuperer : taille du Drive
} else {
$data["errors"][] = "workspace_not_found";
}
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
public function getAllWorkspaces(Request $request)
{
$data = Array(
"data" => Array(),
"errors" => Array()
);
$validation = $this->get("administration.validation");
$token = $request->request->get("token");
$validate_token = $validation->validateAuthentication($token);
if ($validate_token) {
$scroll_id = $request->request->get("scroll_id");
$repository = "Twake\Workspaces:Group";
$options = Array();
if (isset($scroll_id) && isset($repository)) {
$options["scroll_id"] = $scroll_id;
}
$globalresult = $this->get('administration.workspaces')->getAllWorkspace($options);
$data = Array("data" => $globalresult);
} else {
$data["errors"][] = "invalid_authentication_token";
}
return new Response($data);
}
}
@@ -1,20 +0,0 @@
<?php
namespace AdministrationApi\Workspaces\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/backend/workspaces/";
protected $routes = [
"getGroups" => ["handler" => "Groups:getAllGroups", "methods" => ["POST"]],
"getOneGroup" => ["handler" => "Groups:getOneGroup", "methods" => ["POST"]],
"getAllWorkspaces" => ["handler" => "Workspaces:getAllWorkspaces", "methods" => ["POST"]],
"getWorkspace" => ["handler" => "Workspaces:getOneWorkspace", "methods" => ["POST"]],
"searchGroups" => ["handler" => "Groups:findGroups", "methods" => ["POST"]],
];
}
@@ -1,16 +0,0 @@
<?php
namespace AdministrationApi\Workspaces\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"administration.groups" => "AdministrationGroups",
// arguments: [ "@app.twake_doctrine" ]
"administration.workspaces" => "AdministrationWorkspaces",
// arguments: [ "@app.twake_doctrine" ]
];
}
@@ -1,194 +0,0 @@
<?php
namespace AdministrationApi\Workspaces\Services;
use App\App;
class AdministrationGroups
{
private $em;
private $list_group = Array("group" => Array(), "scroll_id" => "");
public function __construct(App $app)
{
$this->em = $app->getServices()->get("app.twake_doctrine");
}
public function getAllGroups($options)
{
$options = Array(
"repository" => "Twake\Workspaces:Group",
"index" => "group",
"size" => 10,
"scroll_id" => $options["scroll_id"],
"query" => Array(
"match_all" => (object)[]
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
//var_dump(json_encode($options,JSON_PRETTY_PRINT));
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $group) {
//var_dump($file->getAsArray());
$group_tab = $group[0]->getAsArray();
$group_tab["nb_workspaces"] = count($group[0]->getWorkspaces());
$group_tab["nb_members"] = count($this->getGroupMembers($group[0]));
$group_tab["creation_data"] = $group[0]->getOnCreationData();
$this->list_group["group"][] = Array($group_tab, $group[1][0]);
}
//var_dump("nombre de resultat : " . count($this->list_files));
//var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
public function getGroupMembers($group)
{
$membersRepository = $this->em->getRepository("Twake\Workspaces:GroupUser");
$members_tab = $membersRepository->findBy(Array("group" => $group));
$members = Array();
foreach ($members_tab as $member) {
try{
$members[] = $member->getUser()->getAsArray();
}catch(\Exception $err){
}
}
return $members;
}
public function getOneGroup($group_id)
{
$groupsRepository = $this->em->getRepository("Twake\Workspaces:Group");
$group = $groupsRepository->find($group_id);
return $group;
}
public function getGroupWorkspaces($group_id)
{
$groupsRepository = $this->em->getRepository("Twake\Workspaces:Group");
$group = $groupsRepository->find($group_id);
$rep = false;
if ($group) {
$rep = array();
$workspaces_tab = $group->getWorkspaces();
foreach ($workspaces_tab as $workspace) {
$rep[] = $workspace->getAsArray($this->em);
}
}
return $rep;
}
public function getGroupApps($group)
{
$groupAppRepository = $this->em->getRepository("Twake\Workspaces:GroupApp");
$apps_tab = $groupAppRepository->findBy(array("group" => $group));
$apps = array();
$appsRepository = $this->em->getRepository("Twake\Market:Application");
foreach ($apps_tab as $grpApp) {
$app_id = $grpApp->getAppId();
$app = $appsRepository->findby(array('id' => $app_id));
if (count($app) == 1) {
$apps[] = $app[0]->getAsArray();
}
}
return $apps;
}
public function getGroupbyName($options)
{
if (isset($options["name"])) {
$name = $options["name"];
$options = Array(
"repository" => "Twake\Workspaces:Group",
"index" => "group",
"size" => 10,
"query" => Array(
"bool" => Array(
"should" => Array(
"bool" => Array(
"filter" => Array(
"regexp" => Array(
"name" => ".*" . strtolower($name) . ".*"
)
)
)
)
)
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
}
// search in ES
$result = $this->em->es_search($options);
//var_dump(json_encode($options,JSON_PRETTY_PRINT));
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $group) {
//var_dump($file->getAsArray());
$group_tab = $group[0]->getAsArray();
$group_tab["nb_workspaces"] = count($group[0]->getWorkspaces());
$group_tab["nb_members"] = count($this->getGroupMembers($group[0]));
$group_tab["creation_data"] = $group[0]->getOnCreationData();
$this->list_group["group"][] = Array($group_tab, $group[1][0]);
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
}
@@ -1,180 +0,0 @@
<?php
namespace AdministrationApi\Workspaces\Services;
use App\App;
class AdministrationWorkspaces
{
private $em;
private $list_workspace = Array("workspace" => Array(), "scroll_id" => "");
public function __construct(App $app)
{
$this->em = $app->getServices()->get("app.twake_doctrine");
}
public function getOneWorkspace($workspace_id)
{
$workspacesRepository = $this->em->getRepository("Twake\Workspaces:Workspace");
$workspace = $workspacesRepository->findOneBy(["id"=>$workspace_id]);
return $workspace;
}
public function getWorkspaceMembers($workspace)
{
$membersRepository = $this->em->getRepository("Twake\Workspaces:WorkspaceUser");
$members_tab = $membersRepository->findBy(array("workspace_id" => $workspace->getId()));
$members = array();
foreach ($members_tab as $member) {
$members[] = $member->getUser($this->em)->getAsArray();
}
return $members;
}
public function getWorkspaceApps($workspace)
{
$workspaceAppsRepository = $this->em->getrepository("Twake\Workspaces:WorkspaceApp");
$apps_tab = $workspaceAppsRepository->findBy(array("workspace_id" => $workspace));
$apps = array();
$appsRepository = $this->em->getRepository("Twake\Market:Application");
foreach ($apps_tab as $appWksp) {
$app_id = $appWksp->getAppId();
$app = $appsRepository->findBy(array('id' => $app_id));
if (count($app) == 1) {
$apps[] = $app[0]->getAsArray();
}
}
return $apps;
}
public function getInvitedUsers($workspace)
{
$workspaceMailRepository = $this->em->getrepository("Twake\Workspaces:WorkspaceUserByMail");
$mails_tab = $workspaceMailRepository->findBy(array('workspace' => $workspace));
$mails = array();
foreach ($mails_tab as $ws_mail) {
$mails[] = $ws_mail->getMail();
}
return $mails;
}
public function getWpbyName($options)
{
if (isset($options["name"])) {
$name = $options["name"];
$options = Array(
"repository" => "Twake\Workspaces:Workspace",
"index" => "workspace",
"size" => 10,
"query" => Array(
"bool" => Array(
"should" => Array(
"bool" => Array(
"filter" => Array(
"regexp" => Array(
"name" => ".*" . strtolower($name) . ".*"
)
)
)
)
)
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
}
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $workspace) {
//var_dump($file->getAsArray());
$this->list_workspace["workspace"][] = Array($workspace[0]->getAsArray(), $workspace[1][0]);;
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_workspace["scroll_id"] = $scroll_id;
return $this->list_workspace ?: null;
}
public function getAllWorkspace($options)
{
// $group = new Group("group_for_workspace_1");
// $this->em->persist($group);
// $this->em->flush();
//
// $wp = new Workspace("workspace_admin_test_1");
// $wp->setGroup($group);
// $this->em->persist($wp);
// $this->em->flush();
$options = Array(
"repository" => "Twake\Workspaces:Workspace",
"index" => "workspace",
"scroll_id" => $options["scroll_id"],
"size" => 10,
"query" => Array(
"match_all" => (object)[]
),
"sort" => Array(
"creation_date" => Array(
"order" => "desc"
)
)
);
//var_dump(json_encode($options,JSON_PRETTY_PRINT));
// search in ES
$result = $this->em->es_search($options);
array_slice($result["result"], 0, 5);
$scroll_id = $result["scroll_id"];
//on traite les données recu d'Elasticsearch
//var_dump(json_encode($options));
foreach ($result["result"] as $wp) {
$this->list_group["group"][] = Array($wp[0]->getAsArray(), $wp[1][0]);;
}
// var_dump("nombre de resultat : " . count($this->list_files));
// var_dump($this->list_group);
$this->list_group["scroll_id"] = $scroll_id;
return $this->list_group ?: null;
}
}
@@ -1,58 +0,0 @@
<?php
namespace BuiltInConnectors\Common;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
use BuiltInConnectors\Common\Resources\Routing;
use BuiltInConnectors\Common\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
$path = __DIR__ . "/../Connectors/";
$dir = new \DirectoryIterator($path);
$connectors_bundles_instances = [];
// Require and instanciate all defined connectors
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
try{
$bundle = "BuiltInConnectors/Connectors/" . $fileinfo->getFilename();
if (file_exists(__DIR__ . "/../../" . $bundle . "/Bundle.php")) {
require_once __DIR__ . "/../../" . $bundle . "/Bundle.php";
$class_name = str_replace("/", "\\", $bundle) . "\\Bundle";
$connectors_bundles_instances[] = new $class_name($this->app);
} else {
error_log("No such connector bundle " . $bundle);
}
}catch(\Exception $err){
error_log("No such connector bundle " . $fileinfo->getFilename());
error_log($err->getMessage());
}
}
}
// Init routing for all bundles
foreach ($connectors_bundles_instances as $bundle_instance) {
$bundle_instance->init();
}
}
}
@@ -1,143 +0,0 @@
<?php
namespace BuiltInConnectors\Common\Command;
use Common\Commands\ContainerAwareCommand;
class InitConnector extends ContainerAwareCommand
{
protected function configure()
{
$this->setName("twake:init_connector");
}
protected function execute()
{
$arg_list = $_SERVER['argv'];
$connector_name = isset($arg_list[0]) ? $arg_list[0] : false;
if(!$connector_name){
error_log("⚙️ Installing default connectors defined in configuration");
$connectors = $this->getApp()->getContainer()->getParameter("defaults.applications.connectors");
if($connectors){
foreach($connectors as $name => $configuration){
$this->toggleConnector($name, !!$configuration, isset($configuration["default"]) && $configuration["default"]);
}
}
die;
}
$action_name = isset($arg_list[1]) ? $arg_list[1] : "enable";
$enable = $action_name != "disable";
$second_action_name = isset($arg_list[2]) ? $arg_list[2] : "";
$is_default = $second_action_name == "default";
$this->toggleConnector($connector_name, $enable, $is_default);
}
public function toggleConnector($connector_name, $enable, $is_default){
error_log(($enable?"Enabling" : "Disabling") . " " . $connector_name. ($is_default?" and default for future workspaces":"") . "!");
$path = __DIR__ . "/../../Connectors/";
$dir = new \DirectoryIterator($path);
$connectors_bundles_instances = [];
// Require and instanciate all defined connectors
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
try{
$bundle = "BuiltInConnectors/Connectors/" . $fileinfo->getFilename();
if (file_exists(__DIR__ . "/../../../" . $bundle . "/Bundle.php")) {
$class_name = str_replace("/", "\\", $bundle) . "\\Bundle";
$connectors_bundles_instances[] = new $class_name($this->app);
} else {
error_log("No such connector bundle " . $bundle);
}
}catch(\Exception $err){
error_log("No such connector bundle " . $fileinfo->getFilename());
error_log($err->getMessage());
}
}
}
$found = false;
// Init routing for all bundles
foreach ($connectors_bundles_instances as $bundle_instance) {
if(method_exists($bundle_instance, "getDefinition")){
$definition = $bundle_instance->getDefinition();
if($definition["simple_name"] == $connector_name){
$found = true;
$server_route = rtrim($this->app->getContainer()->getParameter("env.internal_server_name")?:$this->app->getContainer()->getParameter("env.server_name"), "/");
$simple_name = $definition["simple_name"];
$icon = $definition['icon_url'];
if(!(strpos("http://", $icon) === 0 || strpos("https://", $icon) === 0)){
$icon = rtrim($this->app->getContainer()->getParameter("env.server_name"), "/") . "/bundle/connectors/" . $definition["simple_name"] . "/icon";
}
$app_exists = $this->app->getServices()->get("app.applications")->findAppBySimpleName($simple_name, true);
$application = [
'simple_name' => $simple_name,
'name' => $definition['name'],
'description' => $definition['description'],
'icon_url' => $icon,
'website' => $definition['website'],
'categories' => $definition['categories'],
'privileges' => $definition['privileges'],
'capabilities' => $definition['capabilities'],
'hooks' => $definition['hooks'],
'display' => $definition['display'],
'api_allowed_ips' => $definition['api_allowed_ips'],
'api_event_url' => $server_route . "/bundle/connectors/" . $definition["simple_name"] . "/" . ltrim($definition['api_event_url'], "/"),
'public' => true
];
if($enable){
//Update database with this app
if(!$app_exists){
$new_app = $this->app->getServices()->get("app.applications")->createApp(null, $definition["name"], $simple_name, $definition["app_group_name"], null);
$application["id"] = $new_app["id"];
}else{
$application["id"] = $app_exists["id"];
}
$this->app->getServices()->get("app.applications")->update($application, null);
$this->app->getServices()->get("app.applications")->toggleAppValidation($application["id"], true);
if($is_default){
$this->app->getServices()->get("app.applications")->toggleAppDefault($application["id"], true);
}
error_log("The connector is now available to the public.");
}else{
//If in database, set to non public
if($app_exists){
$application["public"] = false;
$application["id"] = $app_exists["id"];
$this->app->getServices()->get("app.applications")->toggleAppValidation($application["id"], false);
$this->app->getServices()->get("app.applications")->toggleAppDefault($application["id"], false);
}
error_log("The connector is now unavailable to the public.");
}
}
}
}
if(!$found){
error_log("This connector was not found.");
}
}
}
@@ -1,12 +0,0 @@
<?php
namespace BuiltInConnectors\Common\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Index extends BaseController
{
}
@@ -1,78 +0,0 @@
<?php
namespace BuiltInConnectors\Common\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BuiltInConnectorsEntity
*
* @ORM\Table(name="built_in_connectors_entity",options={"engine":"MyISAM",
* "scylladb_keys": {{"connector_id":"ASC", "document_id":"ASC"}}
* })
* @ORM\Entity
*/
class BuiltInConnectorsEntity
{
/**
* @ORM\Column(type="twake_timeuuid")
* @ORM\Id
*/
private $connector_id;
/**
* @ORM\Column(type="twake_no_salt_text")
* @ORM\Id
*/
private $document_id;
/**
* @ORM\Column(type="twake_text")
*/
private $value;
/**
* BuiltInConnectorsEntity constructor.
* @param $connector_id
*/
public function __construct($connector_id, $document_id)
{
$this->connector_id = $connector_id;
$this->document_id = $document_id;
}
/**
* @return mixed
*/
public function getConnectorId()
{
return $this->connector_id;
}
/**
* @return mixed
*/
public function getDocumentId()
{
return $this->document_id;
}
/**
* @return mixed
*/
public function getValue()
{
return json_decode($this->value, 1);
}
/**
* @param mixed $value
*/
public function setValue($value): void
{
$this->value = json_encode($value);
}
}
@@ -1,16 +0,0 @@
<?php
namespace BuiltInConnectors\Common\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "bundle/connectors/common/";
protected $routes = [
];
}
@@ -1,13 +0,0 @@
<?php
namespace BuiltInConnectors\Common\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"connectors.common.main" => "MainConnectorService"
];
}
@@ -1,167 +0,0 @@
<?php
namespace BuiltInConnectors\Common\Services;
use Emojione\Client;
use Emojione\Ruleset;
use BuiltInConnectors\Common\Entity\BuiltInConnectorsEntity;
use Exception;
class MainConnectorService {
protected $app_simple_name = "";
protected $credentials = [];
public function __construct($app)
{
$this->market_service = $app->getServices()->get("app.applications");
$this->rest_client = $app->getServices()->get("app.restclient");
$this->api_url = rtrim($app->getContainer()->getParameter("env.internal_server_name")?:$app->getContainer()->getParameter("env.server_name"), "/") . "/api/v1/";
$this->server_url = rtrim($app->getContainer()->getParameter("env.server_name"), "/") . "/bundle/connectors/";
$this->emojione_client = new Client(new Ruleset());
$this->doctrine = $app->getServices()->get("app.twake_doctrine");
}
public function setConnector($simple_name){
$this->app_simple_name = $simple_name;
}
private function getConnectorKeys(){
$simple_name = $this->app_simple_name;
if(!isset($this->credentials[$simple_name])){
$this->credentials[$simple_name] = $this->market_service->getCredentials($simple_name);
}
return $this->credentials[$simple_name];
}
public function postApi($route, $data, $timeout = 3, $raw = false){
$cred = $this->getConnectorKeys();
$custom = array(
CURLOPT_HTTPHEADER => Array(
"Authorization: Basic ".base64_encode($cred["api_id"].":".$cred["api_key"]),
"Content-Type: application/json"
),
);
return $this->post(rtrim($this->api_url, "/") . "/" . ltrim($route, "/"), $data, $raw, $custom, $timeout);
}
public function post($route, $data, $raw = false, $custom_options = Array(), $timeout = 1){
$data_string = json_encode($data);
$restClient = $this->rest_client;
$custom = array(
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => false
);
foreach ($custom_options as $key=>$value){
$custom[$key] = $value;
}
$resp = $restClient->post($route, $data_string, $custom);
try {
if(!$raw) {
$data = json_decode($resp->getContent(), 1);
}else{
$data = $resp->getContent();
}
return $data;
} catch (\Exception $e) {
return false;
}
}
public function get($route, $raw = false, $custom_options = Array(), $timeout = 1){
$restClient = $this->rest_client;
$custom = array(
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => false
);
foreach ($custom_options as $key=>$value){
$custom[$key] = $value;
}
$resp = $restClient->get($route, $custom);
try {
if(!$raw) {
$data = json_decode($resp->getContent(), 1);
}else{
$data = $resp->getContent();
}
return $data;
} catch (\Exception $e) {
return false;
}
}
public function getServerBaseUrl(){
return $this->server_url;
}
public function generateToken($length = 10){
try {
return bin2hex(random_bytes(intval($length / 2)));
}catch(\Exception $e){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
}
/**
* @return string
*/
public function getAppName()
{
return $this->app_simple_name;
}
/** Save connector document to db */
public function saveDocument($id, $content){
$cred = $this->getConnectorKeys();
if(!$cred["api_id"]){
return false;
}
$document = new BuiltInConnectorsEntity($cred["api_id"], $id);
if($content === null){
$this->doctrine->remove($document);
}else{
$document->setValue($content);
$this->doctrine->persist($document);
}
$this->doctrine->flush();
return true;
}
/** Remove connector document from db */
public function removeDocument($id){
return $this->saveDocument($id, null);
}
/** Get connector document from db */
public function getDocument($id){
$cred = $this->getConnectorKeys();
if(!$cred["api_id"]){
return false;
}
$documentsRepo = $this->doctrine->getRepository("BuiltInConnectors\Common:BuiltInConnectorsEntity");
$document = $documentsRepo->findOneBy(["connector_id" => $cred["api_id"], "document_id" => $id]);
return $document?$document->getValue():null;
}
}
@@ -1,42 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Jitsi;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
require_once __DIR__ . "/ConnectorDefinition.php";
use BuiltInConnectors\Connectors\Jitsi\ConnectorDefinition;
use BuiltInConnectors\Connectors\Jitsi\Resources\Routing;
use BuiltInConnectors\Connectors\Jitsi\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = "bundle/connectors/" . (new ConnectorDefinition())->definition["simple_name"] . $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
public function getDefinition(){
return (new ConnectorDefinition())->definition;
}
public function getConfiguration(){
return (new ConnectorDefinition())->configuration;
}
}
@@ -1,43 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Jitsi;
class ConnectorDefinition
{
public $configuration = [
'jitsi_domain' => 'meet.jit.si'
];
public $definition = [
'app_group_name' => 'twake',
'categories' => [ 'voice_video' ],
'name' => 'Jitsi',
'simple_name' => 'jitsi',
'description' => 'Jitsi allows you to create and join video calls directly from Twake.',
'icon_url' => 'jitsi.png',
'website' => 'https://twake.app',
'privileges' => [],
'capabilities' =>
[
'messages_send',
'display_modal',
'messages_save',
],
'hooks' => [],
'display' =>
[
'messages_module' =>
[
'right_icon' => true,
'commands' =>
[
[
'command' => 'Meeting name',
'description' => 'Create a Jisti call',
]
]
]
],
'api_allowed_ips' => '*',
'api_event_url' => '/event'
];
}
@@ -1,71 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Jitsi\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
use BuiltInConnectors\Connectors\Jitsi\ConnectorDefinition;
class Index extends BaseController
{
public function icon()
{
$configuration = (new ConnectorDefinition())->definition;
$route = realpath(__DIR__."/../Resources/medias/".$configuration["icon_url"]);
$filename = basename($route);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpeg"; break;
case "svg": $ctype="image/svg+xml"; break;
default:
}
header('Content-type: ' . $ctype);
return new Response(file_get_contents($route));
}
public function event(Request $request)
{
$data = $request->request->get("data");
$event = $request->request->get("event");
$type = $request->request->get("type");
$this->get('connectors.jitsi.event')->proceedEvent($type, $event, $data);
return new Response([]);
}
public function call(Request $request){
$user_id = $request->query->get("twake_user", false);
$id = explode("__", explode("twake_", array_pop(explode("/", $_SERVER['REQUEST_URI'])))[1]);
$group_id = str_replace("_", "-", $id[0]);
$id = str_replace("_", "", $id[1]);
$user = $this->get('connectors.jitsi.event')->getUserFromId(str_replace("twake-", "", str_replace("_", "-", $id)), $user_id, $group_id);
$loader = new \Twig\Loader\FilesystemLoader(realpath(__DIR__.'/../Views/'));
$twig = new \Twig\Environment($loader, [
'cache' => $this->app->getAppRootDir() . "/" . $this->app->getContainer()->get("configuration", "twig.cache"),
]);
$template = $twig->load("Templates/call.html.twig");
$configuration = (new ConnectorDefinition())->configuration;
return new Response($template->render(
Array(
"id" => $id,
"user" => $user,
"jitsi_domain" => $this->getParameter("defaults.connectors.jitsi.jitsi_domain", $configuration["jitsi_domain"])
)
));
}
}
@@ -1,18 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Jitsi\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "/";
protected $routes = [
"icon" => ["handler" => "Index:icon", "methods" => ["GET"]],
"event" => ["handler" => "Index:event", "methods" => ["POST"]],
"call/{id}" => ["handler" => "Index:call", "methods" => ["GET"]],
];
}
@@ -1,13 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Jitsi\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"connectors.jitsi.event" => "Event"
];
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

@@ -1,137 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Jitsi\Services;
class Event
{
public function __construct($app) {
$this->main_service = $app->getServices()->get("connectors.common.main");
}
public function getUserFromId($room_id, $user_id, $group_id = null){
$this->main_service->setConnector("jitsi");
$user_object = $this->main_service->postApi("users/get", Array("user_id" => $user_id, "group_id" => $group_id));
return $user_object["object"];
}
public function proceedEvent($type, $event, $data)
{
$this->main_service->setConnector("jitsi");
$group = $data["group"];
$user = $data["user"];
$message = $data["message"];
$channel = $data["channel"];
$parent_message = $data["parent_message"];
$creator = $data["user"];
if ($type == "action" && ($event == "command" || $event == "open")) {
$message = [
"channel_id" => $channel["id"],
"content" => Array(
Array("type"=>"system", "content"=>"Choose a subject for your call"),
Array("type"=>"br"),
Array("type"=>"input", "content" => $data["command"], "placeholder" => "Meeting about ...", "passive_id" => "meeting_name"),
Array("type"=>"br"),
Array("type"=>"button", "style"=>"default", "action_id"=>"cancel", "content"=>"Cancel"),
Array("type"=>"button", "style"=>"primary", "action_id"=>"create", "content"=>"Create")
),
"hidden_data" => Array(
),
"parent_message_id" => isset($parent_message["id"])?$parent_message["id"]:"",
"ephemeral_message_recipients" => [$user["id"]],
"_once_ephemeral_message" => true
];
$data_string = Array(
"group_id" => $group["id"],
"workspace_id" => $channel["workspace_id"],
"message" => $message
);
$message = $this->main_service->postApi("messages/save", $data_string);
}
if ($type == "interactive_message_action" && $event == "cancel") {
$data_string = Array(
"group_id" => $group["id"],
"workspace_id" => $channel["workspace_id"],
"message" => $data["message"]
);
$this->main_service->postApi("messages/remove", $data_string);
}
if ($type == "interactive_message_action" && $event == "create") {
$original_message = $message;
$room_id = $group["id"]."__".$original_message["channel_id"];
$url = rtrim($this->main_service->getServerBaseUrl(), "/") . "/jitsi/call/twake_" . str_replace("-", "_", $room_id);
$message = [];
$message["channel_id"] = $original_message["channel_id"];
$message["sender"] = $user["id"];
$message["parent_message_id"] = isset($original_message["parent_message_id"])?$original_message["parent_message_id"]:"";
$message["content"] = Array(
["type" => "system", "content" => ["@" . $creator["username"] . " invite you to join the call ", ["type" => "bold", "content" => $data["form"]["meeting_name"]],". "]],
["type" => "system", "content" => ["type" => "button", "inline" => "true", "style"=>"primary", "action_id"=>"show_link", "content" => "Show call link"]],
["type" => "br"],
["type" => "url", "user_identifier" => true, "url" => $url, "content" => ["type" => "button", "content" => ["Join call ", ["type" => "bold", "content" => $data["form"]["meeting_name"]]]]]);
$message["hidden_data"] = Array(
"allow_delete" => "everyone",
"room_id" => $room_id
);
$data_string = Array(
"group_id" => $group["id"],
"workspace_id" => $channel["workspace_id"],
"message" => $data["message"]
);
$this->main_service->postApi("messages/remove", $data_string);
$data_string = Array(
"group_id" => $group["id"],
"workspace_id" => $channel["workspace_id"],
"message" => $message
);
$message = $this->main_service->postApi("messages/save", $data_string);
$message_id = $message["object"]["id"];
}
if ($type == "interactive_message_action" && $event == "show_link") {
$room_id = $message["hidden_data"]["room_id"];
$url = rtrim($this->main_service->getServerBaseUrl(), "/") . "/jitsi/call/twake_" . str_replace("-", "_", $room_id);
$display = Array(
"type" => "system", "content" => [
"Partagez ce lien avec les participants de l'appel.",
Array("type" => "br"),
Array("type" => "copiable", "content" => $url)
]
);
$data_string = Array(
"group_id" => $group["id"],
"user_id" => $data["user"]["id"],
"connection_id" => $data["connection_id"],
"form" => $display
);
$this->main_service->postApi("general/configure", $data_string);
}
}
}
@@ -1,59 +0,0 @@
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset="utf-8">
<script src='https://{{ jitsi_domain }}/external_api.js'></script>
<title></title>
</head>
<body>
<style>
html, body, iframe {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<div id="meet">
</div>
<script type="text/javascript">
const domain = '{{ jitsi_domain }}';
window.history.pushState({"pageTitle":document.title},"", document.location.pathname);
var username = localStorage.getItem("username");
var thumbnail = localStorage.getItem("thumbnail");
{% if user %}
username = '{{ user.username }}';
localStorage.setItem("username", username);
thumbnail = '{{ user.thumbnail }}';
localStorage.setItem("thumbnail", thumbnail);
{% endif %}
const options = {
roomName: '{{id}}',
};
const api = new JitsiMeetExternalAPI(domain, options);
//To set name of a participant
api.executeCommand('displayName', '@'+username);
//To set an avatar
if(thumbnail){
api.executeCommand('avatarUrl', thumbnail);
}
// api.addEventListener("participantJoined", function(object){
// console.log(object);
// console.log("nombre de participants",api.getNumberOfParticipants());
// });
</script>
</body>
</html>
@@ -1,42 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Linshare;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
require_once __DIR__ . "/ConnectorDefinition.php";
use BuiltInConnectors\Connectors\Linshare\ConnectorDefinition;
use BuiltInConnectors\Connectors\Linshare\Resources\Routing;
use BuiltInConnectors\Connectors\Linshare\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = "bundle/connectors/" . (new ConnectorDefinition())->definition["simple_name"] . $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
public function getDefinition(){
return (new ConnectorDefinition())->definition;
}
public function getConfiguration(){
return (new ConnectorDefinition())->configuration;
}
}
@@ -1,62 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Linshare;
class ConnectorDefinition
{
public $configuration = [
'domain' => '',
'key' => [
"issuer" => "Twake",
"private" => "-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgHpJ/MAWh52lMCOt4btMb06LHAXn3BrrQoKrZ5IEPPLKqGwl7MVn
X6r+wEtMX5MmTQ68JHb4ohVVjKiJyySql/GXNcwGmx8jhTpFBzOTRDJBm60Z8wz3
G4Uy0IPWt1TRz4oiS9V5cC69ZpvxOQd/yaeN9BDkI/Tda4fDOa3PRINRAgMBAAEC
gYA1+uzf2dIZS26ZgUrQQ6gqcot3K+bj1w9v4LuCH+7LeZuoyYDfjocTUwqM8nSJ
3vFK3M/32D6rziydxN1wHQGench+cfR8yun8V9EV7Y5bTIX8DwMvLGvBkZT0u5Ai
J3g6JkWZTQHdthbOyADCgv7OxCjLrq9egE6py2R5cqk4NQJBALayivwy3WizoKNl
hpTdnIngyUbQnRd/3Enx50qaM3qGjyIpENOsNBhJQDtfQf82MRjAhrrsPSDmGvjL
HXFpqNsCQQCrWrIoGx68e//A5GR8dK7XfxBYaTPsXEXQD3uvegFxYxJJj26Qw8lx
i6XKA2lZKuAiyISrk1UWezG/gCzkF5ZDAkBCyDjtv1oXr7GEiNQNDoTuEXEBpbgG
owJPNVGqf3tZyl3/yqsP9N6GEiCck1F4jMKdnaKiKUCfCf3J+9UjY9AJAkA14SPJ
xpVIkPjfLzGFjK75ZaO/GP1RocX14Rh0GbngbFVwud/7NwTdZhqwRZhXiErHxSMq
S/5iPkRrQaNb6Sq/AkEAqQIOghY6T0SPrKfj+utFJMe0YchSU/bjApyE6U3pj1Vf
JZ7e+kO+wtORxj1bDh9nE6YEvW/fOY6/Sw+HoyYW9w==
-----END RSA PRIVATE KEY-----",
"public" => "-----BEGIN PUBLIC KEY-----
MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHpJ/MAWh52lMCOt4btMb06LHAXn
3BrrQoKrZ5IEPPLKqGwl7MVnX6r+wEtMX5MmTQ68JHb4ohVVjKiJyySql/GXNcwG
mx8jhTpFBzOTRDJBm60Z8wz3G4Uy0IPWt1TRz4oiS9V5cC69ZpvxOQd/yaeN9BDk
I/Tda4fDOa3PRINRAgMBAAE=
-----END PUBLIC KEY-----"
]
];
public $definition = [
'app_group_name' => 'linshare',
'categories' => [ 'files' ],
'name' => 'Linshare',
'simple_name' => 'linshare',
'description' => 'Linshare allows you to send Linshare documents into Twake messages.',
'icon_url' => 'linshare.jpg',
'website' => 'https://www.linshare.org/',
'privileges' => [],
'capabilities' =>
[
"messages_save",
'display_modal',
],
'hooks' => [],
'display' => [
"messages_module" => [
"in_plus" => [
"should_wait_for_popup" => true
]
],
"configuration" => [
"can_configure_in_workspace" => true
]
],
'api_allowed_ips' => '*',
'api_event_url' => '/event'
];
}
@@ -1,61 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Linshare\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
use BuiltInConnectors\Connectors\Linshare\ConnectorDefinition;
class Index extends BaseController
{
public function icon()
{
$configuration = (new ConnectorDefinition())->definition;
$route = realpath(__DIR__."/../Resources/medias/".$configuration["icon_url"]);
$filename = basename($route);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpeg"; break;
case "svg": $ctype="image/svg+xml"; break;
default:
}
header('Content-type: ' . $ctype);
return new Response(file_get_contents($route));
}
public function event(Request $request)
{
$data = $request->request->get("data");
$event = $request->request->get("event");
$type = $request->request->get("type");
if($event == "workspace" && $type == "configuration" || $event == "save_configuration_domain"){
$this->get('connectors.linshare.configure')->proceedEvent($type, $event, $data);
}else{
$this->get('connectors.linshare.event')->proceedEvent($type, $event, $data);
}
return new Response([]);
}
public function download(Request $request)
{
$file_uuid = $request->query->get("file_uuid");
$group_id = $request->query->get("group_id");
$owner_id = $request->query->get("owner_id");
$sign = $request->query->get("sign");
$twake_user = $request->query->get("twake_user");
$this->get('connectors.linshare.event')->download($twake_user, $file_uuid, $group_id, $owner_id, $sign);
return new Response([]);
}
}
@@ -1,18 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Linshare\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "/";
protected $routes = [
"icon" => ["handler" => "Index:icon", "methods" => ["GET"]],
"event" => ["handler" => "Index:event", "methods" => ["POST"]],
"download" => ["handler" => "Index:download", "methods" => ["GET"]],
];
}
@@ -1,14 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Linshare\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"connectors.linshare.configure" => "Configure",
"connectors.linshare.event" => "Event"
];
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

@@ -1,77 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Linshare\Services;
use BuiltInConnectors\Connectors\Linshare\ConnectorDefinition;
class Configure
{
public function __construct($app) {
$this->app = $app;
$this->main_service = $app->getServices()->get("connectors.common.main");
}
public function proceedEvent($type, $event, $data) {
$this->main_service->setConnector("linshare");
$configuration = (new ConnectorDefinition())->configuration;
$linshare_domain = $this->app->getContainer()->getParameter("defaults.connectors.linshare.domain", $configuration["domain"]);
$group = $data["group"];
$entity = null;
$user = $data["user"];
$workspace = $data["workspace"];
if($event == "save_configuration_domain"){
$document_id = $group["id"]."_domain_conf";
$document_value = $data["form"]["domain_url"];
$this->main_service->saveDocument($document_id, $document_value);
$type = "configuration"; //Reopen/Update configuration
}
if ($type == "configuration") {
$document_id = $group["id"]."_domain_conf";
$document_value = $this->main_service->getDocument($document_id);
if($document_value){
$linshare_domain = $document_value;
}
$linshare_publickey = $this->app->getContainer()->getParameter("defaults.connectors.linshare.key.public", $configuration["key"]["public"]);
$form = Array("type" => "nop", "content" => [
Array("type" => "nop" , "content" => "• To configure your company with LinShare you must enter your LinShare domain URL first."),
Array("type" => "br"),
Array("type" => "br"),
Array("type" => "bold" , "content" => "Domain url"),
Array("type" => "br"),
Array("type" => "input", "placeholder" => "https://linshare.org", "content" => $linshare_domain, "passive_id" => "domain_url"),
Array("type" => "button", "content" => "Save domain", "action_id" => "save_configuration_domain", "style" => "primary"),
Array("type" => "br"),
Array("type" => "system" , "content" => ["Current domain is ", Array("type" => "bold" , "content" => $linshare_domain)]),
Array("type" => "br"),
Array("type" => "br"),
Array("type" => "nop" , "content" => "• To authorize Twake in LinShare, add this public key to LinShare adminitration."),
Array("type" => "br"),
Array("type" => "br"),
Array("type" => "bold" , "content" => "Public key"),
Array("type" => "br"),
Array("type" => "mcode", "content" => $linshare_publickey)
]);
$data_string = Array(
"group_id" => $group["id"],
"user_id" => $user["id"],
"connection_id" => $data["connection_id"],
"form" => $form
);
$res = $this->main_service->postApi("general/configure", $data_string);
}
}
}
@@ -1,245 +0,0 @@
<?php
namespace BuiltInConnectors\Connectors\Linshare\Services;
use BuiltInConnectors\Connectors\Linshare\ConnectorDefinition;
class Event
{
public function __construct($app) {
$this->app = $app;
$this->main_service = $app->getServices()->get("connectors.common.main");
}
public function getJWT($user_email){
$configuration = (new ConnectorDefinition())->configuration;
$data = [];
$data["sub"] = $user_email;
$linshare_privatekey = $this->app->getContainer()->getParameter("defaults.connectors.linshare.key.private", $configuration["key"]["private"]);
$data["iss"] = $this->app->getContainer()->getParameter("defaults.connectors.linshare.key.issuer", $configuration["key"]["issuer"]) ?: "Twake";
// Create JWT
$header = json_encode(['alg' => 'RS512']);
$data["iat"] = date("U");
$data["exp"] = date("U") + 5 * 60;
$payload = json_encode($data);
$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
openssl_sign( $base64UrlHeader . "." . $base64UrlPayload, $signature, $linshare_privatekey, OPENSSL_ALGO_SHA512);
$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
return $jwt;
}
public function proceedEvent($type, $event, $data) {
$this->main_service->setConnector("linshare");
$definition = (new ConnectorDefinition())->definition;
$group = $data["group"];
$entity = null;
$user = $data["user"];
$workspace = $data["workspace"];
$channel = $data["channel"];
$parent_message = $data["parent_message"];
$interactive_context = $data["interactive_context"];
if ($type == "action") {
$linshare_domain = $this->app->getContainer()->getParameter("defaults.connectors.linshare.domain", $configuration["domain"]);
$document_id = $group["id"]."_domain_conf";
$document_value = $this->main_service->getDocument($document_id);
if($document_value){
$linshare_domain = $document_value;
}
// GET Documents from LinShare
$token = $this->getJWT($user["email"]);
$documents = $this->main_service->get(rtrim($linshare_domain, "/") . "/linshare/webservice/rest/user/documents/", false, [
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Authorization: Bearer " . $token
]
]);
$values = [];
foreach($documents as $document){
$uuid = $document["uuid"];
$values[] = [
"name" => $document["name"],
"value" => json_encode(["uuid"=>$uuid, "name"=>$document["name"]])
];
}
$select = [
"type" => "select",
"title"=>"Choose file",
"values" => $values,
"passive_id" => "file_select"
];
$form = Array("type" => "nop", "content" => [
"Choose a file to send from your space",
Array("type" => "br"),
$select,
Array("type" => "br"),
Array("type" => "button", "action_id" => "send_file", "content" => "Envoyer", "interactive_context" => [
"channel_id" => $channel["id"]
]),
]);
$data_string = Array(
"group_id" => $group["id"],
"user_id" => $user["id"],
"connection_id" => $data["connection_id"],
"form" => $form
);
$res = $this->main_service->postApi("general/configure", $data_string);
}
if($type == "interactive_configuration_action" && $event == "send_file"){
$data_string = Array(
"group_id" => $group["id"],
"user_id" => $user["id"],
"connection_id" =>$data["connection_id"]
);
$this->main_service->postApi("general/configure_close", $data_string);
$file = json_decode($data["form"]["file_select"], 1);
$server_route = rtrim($this->app->getContainer()->getParameter("env.server_name"), "/");
if(!$file || !$file["name"]){
return;
}
$download_parameters = [
"file_uuid=" . $file["uuid"],
"group_id=" . $group["id"],
"owner_id=" . $user["id"]
];
$download_route = $server_route . "/bundle/connectors/" . $definition["simple_name"] . "/download";
$download_route = $download_route . "?" . join("&", $download_parameters);
$linshare_privatekey = $this->app->getContainer()->getParameter("defaults.connectors.linshare.key.private", $configuration["key"]["private"]);
openssl_sign($file["uuid"] . $user["id"], $signature, $linshare_privatekey, OPENSSL_ALGO_SHA512);
$download_route .= "&sign=" . str_replace(str_split('+/='), str_split('._-'), base64_encode($signature));
$message["channel_id"] = $interactive_context["channel_id"];
$message["sender"] = $user["id"];
$message["parent_message_id"] = isset($parent_message["id"])?$parent_message["id"]:"";
$message["content"] = Array(
["type" => "url", "user_identifier" => true, "url" => $download_route, "content" => ["type" => "button", "content" => "Download " . $file["name"]]]
);
$message["hidden_data"] = Array(
"allow_delete" => "everyone"
);
$data_string = Array(
"group_id" => $group["id"],
"message" => $message
);
$message = $this->main_service->postApi("messages/save", $data_string);
}
}
public function download($twake_user, $file_uuid, $group_id, $owner_id, $sign){
$this->main_service->setConnector("linshare");
$linshare_publickey = $this->app->getContainer()->getParameter("defaults.connectors.linshare.key.public", $configuration["key"]["public"]);
$r = openssl_verify($file_uuid . $owner_id, base64_decode(str_replace(str_split('._-'), str_split('+/='), $sign)), $linshare_publickey, OPENSSL_ALGO_SHA512);
if(!$r){
echo "This document isn't available.";
die();
}
$linshare_domain = $this->app->getContainer()->getParameter("defaults.connectors.linshare.domain", $configuration["domain"]);
$document_id = $group_id."_domain_conf";
$document_value = $this->main_service->getDocument($document_id);
if($document_value){
$linshare_domain = $document_value;
}
//Get user email
$user_object = $this->main_service->postApi("users/get", Array("user_id" => $twake_user, "group_id" => $group_id));
$requester_email = $user_object["object"]["email"];
//Get owner email
$owner_email = $requester_email;
if($twake_user != $owner_id){
$user_object = $this->main_service->postApi("users/get", Array("user_id" => $owner_id, "group_id" => $group_id));
$owner_email = $user_object["object"]["email"];
}
//TODO download as the requester and not as the owner
//Test if user has access to this file
$token = $this->getJWT($owner_email);
$document = $this->main_service->get(rtrim($linshare_domain, "/") . "/linshare/webservice/rest/user/documents/".$file_uuid, false, [
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Authorization: Bearer " . $token
]
]);
if(!$document){
echo "This document isn't available.";
die();
}
$size = $document["size"];
$quoted = $document["name"];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
if($size) header('Content-Length: ' . $size);
$url = rtrim($linshare_domain, "/") . "/linshare/webservice/rest/user/documents/".$file_uuid."/download";
$options = [
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Authorization: Bearer " . $token
]
];
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_HEADER] = false;
$options[CURLOPT_URL] = $url;
$options[CURLOPT_CUSTOMREQUEST] = "GET";
$curl_write_flush = function ($curl_handle, $chunk)
{
echo $chunk;
ob_flush(); // flush output buffer (Output Control configuration specific)
flush(); // flush output body (SAPI specific)
return strlen($chunk); // tell Curl there was output (if any).
};
$curl = curl_init();
curl_setopt_array($curl, $options);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_WRITEFUNCTION, $curl_write_flush);
curl_exec($curl);
curl_close($curl);
die();
}
}
@@ -1,26 +0,0 @@
<?php
namespace DevelopersApiV1\Calendar;
require_once __DIR__ . "/Resources/Routing.php";
use DevelopersApiV1\Calendar\Resources\Routing;
use DevelopersApiV1\Calendar\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
}
}
@@ -1,122 +0,0 @@
<?php
namespace DevelopersApiV1\Calendar\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Calendar extends BaseController
{
public function removeEvent(Request $request)
{
$capabilities = ["calendar_event_remove"];
$application = $this->get("app.applications_api")->getAppFromRequest($request, $capabilities);
if (is_array($application) && $application["error"]) {
return new Response($application);
}
$object = $request->request->get("object", null);
$user = null;
$object = $this->get("app.calendar.event")->remove($object, Array(), $user);
$event = Array(
"client_id" => "system",
"action" => "remove",
"object_type" => "",
"front_id" => $object["front_id"]
);
$workspace_calendars = $object["workspaces_calendars"] ? $object["workspaces_calendars"] : [];
$workspace_ids = [];
foreach ($workspace_calendars as $wc) {
if (!in_array($wc["workspace_id"], $workspace_ids)) {
$workspace_ids[] = $wc["workspace_id"];
$this->get("app.websockets")->push("calendar_events/" . $wc["workspace_id"], $event);
}
}
$this->get("administration.counter")->incrementCounter("total_api_calendar_operation", 1);
return new Response(Array("result" => $object));
}
public function saveEvent(Request $request)
{
$capabilities = ["calendar_event_save"];
$application = $this->get("app.applications_api")->getAppFromRequest($request, $capabilities);
if (is_array($application) && $application["error"]) {
return new Response($application);
}
$object = $request->request->get("object", null);
$user = null;
try {
$object = $this->get("app.calendar.event")->save($object, Array(), $user);
} catch (\Exception $e) {
$object = false;
}
if (!$object) {
return new Response(Array("error" => "unknown error or malformed query."));
}
if ($object) {
$event = Array(
"client_id" => "system",
"action" => "save",
"object_type" => "",
"object" => $object
);
$workspace_calendars = $object["workspaces_calendars"] ? $object["workspaces_calendars"] : [];
$workspace_ids = [];
foreach ($workspace_calendars as $wc) {
if (!in_array($wc["workspace_id"], $workspace_ids)) {
$workspace_ids[] = $wc["workspace_id"];
$this->get("app.websockets")->push("calendar_events/" . $wc["workspace_id"], $event);
}
}
}
$this->get("administration.counter")->incrementCounter("total_api_calendar_operation", 1);
return new Response(Array("object" => $object));
}
public function getCalendarList(Request $request)
{
$privileges = ["workspace_calendar"];
$application = $this->get("app.applications_api")->getAppFromRequest($request, [], $privileges);
if (is_array($application) && $application["error"]) {
return new Response($application);
}
$objects = false;
$user_id = $request->request->get("user_id", "");
$workspace_id = $request->request->get("workspace_id", "");
if ($workspace_id) {
if ($user_id) {
$user_entity = $this->get("app.users")->getById($user_id, true);
}
if ($user_entity) {
$objects = $this->get("app.calendar.calendar")->get(Array("workspace_id" => $workspace_id), $user_entity);
}
}
if ($objects === false) {
return new Response(Array("error" => "payload_error"));
}
$res = [];
foreach ($objects as $object) {
$res[] = $object;
}
$this->get("administration.counter")->incrementCounter("total_api_calendar_operation", 1);
return new Response(Array("data" => $res));
}
}
@@ -1,19 +0,0 @@
<?php
namespace DevelopersApiV1\Calendar\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/v1/calendar/";
protected $routes = [
#Calendar routing
"event/remove" => ["handler" => "Calendar:removeEvent", "methods" => ["POST"]],
"event/save" => ["handler" => "Calendar:saveEvent", "methods" => ["POST"]],
"get_calendars" => ["handler" => "Calendar:getCalendarList", "methods" => ["POST"]],
];
}
@@ -1,26 +0,0 @@
<?php
namespace DevelopersApiV1\Channels;
require_once __DIR__ . "/Resources/Routing.php";
use DevelopersApiV1\Channels\Resources\Routing;
use DevelopersApiV1\Channels\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
}
}
@@ -1,80 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: ehlnofey
* Date: 05/06/18
* Time: 15:46
*/
namespace DevelopersApiV1\Channels\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Channel extends BaseController
{
public function getDirectChannel(Request $request)
{
$capabilities = [];
$application = $this->get("app.applications_api")->getAppFromRequest($request, $capabilities);
if (is_array($application) && $application["error"]) {
return new Response($application);
}
$user_id = $request->request->get("user_id", "");
if ($user_id) {
$user_entity = $this->get("app.users")->getById($user_id, true);
if ($user_entity) {
$object = $this->get("app.channels.direct_messages_system")->save(Array("app_id" => $application->getId(), "group_id" => $request->request->get("group_id", null)), Array(), $user_entity);
}
}
$this->get("administration.counter")->incrementCounter("total_api_messages_operation", 1);
return new Response(Array("object" => $object));
}
public function getChannelsByWorkspace(Request $request)
{
$privileges = ["channels"];
$application = $this->get("app.applications_api")->getAppFromRequest($request, [], $privileges);
if (is_array($application) && $application["error"]) {
return new Response($application);
}
$objects = false;
$user_id = $request->request->get("user_id", "");
$workspace_id = $request->request->get("workspace_id", "");
if ($workspace_id) {
if ($user_id) {
$user_entity = $this->get("app.users")->getById($user_id, true);
}
if ($user_entity) {
$objects = $this->get("app.channels.channels_system")->get(Array("workspace_id" => $workspace_id), $user_entity);
}
}
if ($objects === false) {
return new Response(Array("error" => "payload_error"));
}
$res = [];
foreach ($objects as $object) {
if (!$object["direct"] && !$object["application"]) {
$res[] = $object;
}
}
$this->get("administration.counter")->incrementCounter("total_api_messages_operation", 1);
return new Response(Array("data" => $res));
}
}
@@ -1,18 +0,0 @@
<?php
namespace DevelopersApiV1\Channels\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/v1/channels/";
protected $routes = [
#Message routing
"get_direct_channel" => ["handler" => "Channel:getDirectChannel", "methods" => ["POST"]],
"get_by_workspace" => ["handler" => "Channel:getChannelsByWorkspace", "methods" => ["POST"]],
];
}
@@ -1,30 +0,0 @@
<?php
namespace DevelopersApiV1\Core;
require_once __DIR__ . "/Resources/Routing.php";
require_once __DIR__ . "/Resources/Services.php";
use DevelopersApiV1\Core\Resources\Routing;
use DevelopersApiV1\Core\Resources\Services;
use Common\BaseBundle;
class Bundle extends BaseBundle
{
protected $bundle_root = __DIR__;
protected $bundle_namespace = __NAMESPACE__;
protected $routes = [];
protected $services = [];
public function init()
{
$routing = new Routing();
$this->routes = $routing->getRoutes();
$this->routing_prefix = $routing->getRoutesPrefix();
$this->initRoutes();
$this->services = (new Services())->getServices();
$this->initServices();
}
}
@@ -1,32 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: lucie
* Date: 08/06/18
* Time: 14:17
*/
namespace DevelopersApiV1\Core\Controller;
use Common\BaseController;
use Common\Http\Response;
use Common\Http\Request;
class Base extends BaseController
{
public function getInfoFromToken(Request $request)
{
$info = $this->get("api.v1.check_user_data")->getInfo($request->request->get("token", null));
if ($info)
return new Response($info->getAsArray());
else
return new Response(array("error" => "invalid_token"));
}
public function BadRequest()
{
return new Response(Array("errors" => "0000", "description" => "Bad request"));
}
}
@@ -1,178 +0,0 @@
<?php
namespace DevelopersApiV1\Core\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* AccessLog
*
* @ORM\Table(name="access_log",options={"engine":"MyISAM"})
* @ORM\Entity()
*/
class AccessLog
{
/**
* @ORM\Column(name="id", type="twake_timeuuid")
* @ORM\Id
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $appid;
/**
* @ORM\Column(type="integer")
*/
private $minutes;
/**
* @ORM\Column(type="integer")
*/
private $readaccesscount;
/**
* @ORM\Column(type="integer")
*/
private $writeaccesscount;
/**
* @ORM\Column(type="integer")
*/
private $manageaccesscount;
/**
* @return mixed
*/
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getAppId()
{
return $this->appid;
}
/**
* @param mixed $appid
*/
public function setAppId($appid)
{
$this->appid = $appid;
}
/**
* @return mixed
*/
public function getMinutes()
{
return $this->minutes;
}
/**
* @param mixed $minutes
*/
public function setMinutes($minutes)
{
$this->minutes = $minutes;
}
/**
* @return mixed
*/
public function getReadAccessCount()
{
return $this->readaccesscount;
}
/**
*/
public function readAccessIncrease()
{
$this->readAccessCount++;
}
/**
* @return mixed
*/
public function getWriteAccessCount()
{
return $this->writeaccesscount;
}
/**
*/
public function writeAccessIncrease()
{
$this->writeAccessCount++;
}
/**
* @return mixed
*/
public function getManageAccessCount()
{
return $this->manageaccesscount;
}
/**
*/
public function manageAccessIncrease()
{
$this->manageAccessCount++;
}
/**
* @param mixed $readaccesscount
*/
public function setReadAccessCount($readaccesscount)
{
$this->readaccesscount = $readaccesscount;
}
/**
* @param mixed $writeaccesscount
*/
public function setWriteAccessCount($writeaccesscount)
{
$this->writeaccesscount = $writeaccesscount;
}
/**
* @param mixed $manageaccesscount
*/
public function setManageAccessCount($manageaccesscount)
{
$this->manageaccesscount = $manageaccesscount;
}
public function clear($minutes)
{
$this->setMinutes($minutes);
$this->setReadAccessCount(0);
$this->setWriteAccessCount(0);
$this->setManageAccessCount(0);
}
public function __construct()
{
$this->setId(0);
$this->setAppId(0);
$this->setMinutes(0);
$this->setReadAccessCount(0);
$this->setWriteAccessCount(0);
$this->setManageAccessCount(0);
}
}
@@ -1,16 +0,0 @@
<?php
namespace DevelopersApiV1\Core\Resources;
use Common\BaseRouting;
class Routing extends BaseRouting
{
protected $routing_prefix = "api/v1/core/";
protected $routes = [
"token" => ["handler" => "Base:getInfoFromToken", "methods" => ["POST"]],
];
}
@@ -1,20 +0,0 @@
<?php
namespace DevelopersApiV1\Core\Resources;
use Common\BaseServices;
class Services extends BaseServices
{
protected $services = [
"api.v1.check" => "CheckService",
// arguments: ["@app.twake_doctrine", "@api.v1.access_log"]
"api.v1.api_status" => "ApiStatus",
// arguments: ["@app.twake_doctrine"]
"api.v1.access_log" => "AccessLogSystem",
// arguments: ["@app.twake_doctrine"]
"api.v1.check_user_data" => "CheckUserInfo",
// arguments: ["@app.twake_doctrine"]
];
}
@@ -1,51 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: ehlnofey
* Date: 08/06/18
* Time: 10:33
*/
namespace DevelopersApiV1\Core\Services;
use DevelopersApiV1\Core\Entity\AccessLog;
use App\App;
class AccessLogSystem
{
/**
* AccessLog constructor.
*/
public function __construct(App $app)
{
$this->doctrine = $app->getServices()->get("app.twake_doctrine");
}
public function record($applicationId, $rightLevel)
{
$accessLogger = $this->doctrine->getRepository("DevelopersApiV1\Core:AccessLog")->findOneBy(Array("appid" => $applicationId));
if ($accessLogger == null) {
$accessLogger = new AccessLog();
$accessLogger->setAppId($applicationId);
}
$minutes = $accessLogger->getMinutes();
if ($minutes != date("i"))
$accessLogger->clear(date("i"));
if ($rightLevel == 1) //read
$accessLogger->readAccessIncrease();
elseif ($rightLevel == 2) //write
$accessLogger->writeAccessIncrease();
elseif ($rightLevel == 3) //manage
$accessLogger->manageAccessIncrease();
$this->doctrine->persist($accessLogger);
$this->doctrine->flush();
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More