first commit symfony 6

This commit is contained in:
2022-07-21 16:15:47 +02:00
parent d9bfbb6b3c
commit 5c4961748b
282 changed files with 37482 additions and 0 deletions

View File

@ -0,0 +1,89 @@
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class ApiService
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function setbody(Array $array)
{
return \Unirest\Request\Body::json($array);
}
public function run($method,$url,$query,$header=null) {
// Entete
$headerini = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
if($header) $header=array_merge($headerini,$header);
else $header=$headerini;
// Paramétrage unirest
\Unirest\Request::verifyPeer(false);
\Unirest\Request::verifyHost(false);
\Unirest\Request::timeout(5);
// Déclaration du proxy
$proxyUse = $this->params->get("proxyUse");
if($proxyUse) {
$proxyHost = $this->params->get("proxyHost");
$proxyPort = $this->params->get("proxyPort");
\Unirest\Request::proxy($proxyHost, $proxyPort, CURLPROXY_HTTP, true);
}
if($query) $query = \Unirest\Request\Body::json($query);
$response = false;
switch($method) {
case "POST":
try{
$response = \Unirest\Request::post($url,$header,$query);
}
catch (\Exception $e) {
die();
return false;
}
break;
case "GET":
try{
$response = @\Unirest\Request::get($url,$header,$query);
}
catch (\Exception $e) {
dump($e);
return false;
}
break;
case "DELETE":
try{
$response = \Unirest\Request::delete($url,$header,$query);
}
catch (\Exception $e) {
return false;
}
break;
case "PATCH":
try{
$response = \Unirest\Request::patch($url,$header,$query);
}
catch (\Exception $e) {
return false;
}
break;
}
return $response;
}
}

155
src/Service/AppSession.php Normal file
View File

@ -0,0 +1,155 @@
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AppSession {
private $container;
protected $em;
protected $requeststack;
protected $token;
public function __construct(ContainerInterface $container, EntityManagerInterface $em, RequestStack $requeststack, TokenStorageInterface $token)
{
$this->container = $container;
$this->requeststack = $requeststack;
$this->em = $em;
$this->token = $token;
}
public function onDomainParse(RequestEvent $event) {
$session = $this->requeststack->getSession();
$configs = $this->em->getRepository("App\Entity\Config")->findAll();
foreach($configs as $config) {
$session->set($config->getId(), strval($config->getValue()));
}
$session->set("headerimage","uploads/header/".$session->get("headerimage"));
// Calcul couleur
$session->set("colorbgbodylight-darker", $this->adjustBrightness($session->get("colorbgbodylight"),-10));
$session->set("colorfttitlelight-darker", $this->adjustBrightness($session->get("colorfttitlelight"),-50));
$session->set("colorbgbodydark-darker", $this->adjustBrightness($session->get("colorbgbodydark"),-50));
$session->set("colorbgbodydark-lighter", $this->adjustBrightness($session->get("colorbgbodydark"),+50));
$session->set("colorbgbodydark-rgb", $this->hexToRgb($session->get("colorbgbodydark")));
$session->set("colorbgbodydark-darkrgb", $this->hexToRgb($session->get("colorbgbodydark-darker")));
$session->set("colorbgbodydark-lightrgb", $this->hexToRgb($session->get("colorbgbodydark-lighter")));
// Current user
$token = $this->token->getToken();
if(!$token) return;
$curentuser=$token->getUser();
// Préférence par défaut
$session->set("fgheader", true);
// Préférence
if($curentuser!="anon.") {
$preference=$curentuser->getPreference();
if(is_array($preference)) {
// Préférence header
if(array_key_exists("fgheader",$preference)) {
$fgheader=($preference["fgheader"][0]=="true");
$session->set("fgheader", $fgheader);
}
}
}
// Permissions
$showannuaire=false;
$submitgroup=false;
if($curentuser!="anon.") {
switch($session->get("permannu")) {
case "ROLE_USER" :
$showannuaire=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER")||$curentuser->hasRole("ROLE_USER"));
break;
case "ROLE_MASTER" :
$showannuaire=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER"));
break;
case "ROLE_MODO" :
$showannuaire=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO"));
break;
}
switch($session->get("permgroup")) {
case "ROLE_USER" :
$submitgroup=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER")||$curentuser->hasRole("ROLE_USER"));
break;
case "ROLE_MASTER" :
$submitgroup=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO")||$curentuser->hasRole("ROLE_MASTER"));
break;
case "ROLE_MODO" :
$submitgroup=($curentuser->hasRole("ROLE_ADMIN")||$curentuser->hasRole("ROLE_MODO"));
break;
}
}
$session->set("showannuaire", $showannuaire);
$session->set("submitgroup", $submitgroup);
// Visite
if($curentuser!="anon.") {
$now=new \DateTime();
if(!$curentuser->getVisitedate()) {
$curentuser->setVisitedate($now);
$curentuser->setVisitecpt($curentuser->getVisitecpt()+1);
$this->em->persist($curentuser);
$this->em->flush();
}
else {
$visitedate=clone $curentuser->getVisitedate();
$visitedate->add(new \DateInterval("PT1H"));
if($visitedate<$now) {
$curentuser->setVisitedate($now);
$curentuser->setVisitecpt($curentuser->getVisitecpt()+1);
$this->em->persist($curentuser);
$this->em->flush();
}
}
}
}
private function adjustBrightness($hex, $steps) {
// Steps should be between -255 and 255. Negative = darker, positive = lighter
$steps = max(-255, min(255, $steps));
// Normalize into a six character long hex string
$hex = str_replace('#', '', $hex);
if (strlen($hex) == 3) {
$hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
}
// Split into three parts: R, G and B
$color_parts = str_split($hex, 2);
$return = '';
foreach ($color_parts as $color) {
$color = hexdec($color); // Convert to decimal
$color = max(0,min(255,$color + $steps)); // Adjust color
$return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
}
return '#'.$return;
}
public function hexToRgb($hex) {
$hex = str_replace('#', '', $hex);
$length = strlen($hex);
$rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
$rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
$rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
return $rgb['r'].",".$rgb['g'].",".$rgb['b'];
}
}

841
src/Service/LdapService.php Normal file
View File

@ -0,0 +1,841 @@
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Entity\User;
use App\Entity\Niveau01;
use App\Entity\Niveau02;
use App\Entity\Group;
use App\Entity\UserGroup;
class LdapService
{
private $connection;
public function __construct(ContainerInterface $container)
{
$this->appMasteridentity = $container->getParameter("appMasteridentity");
$this->synchro = $container->getParameter("appSynchro");
$this->host = $container->getParameter("ldapHost");
$this->port = $container->getParameter("ldapPort");
$this->usetls = $container->getParameter("ldapUsetls");
$this->userwriter = $container->getParameter("ldapUserwriter");
$this->user = $container->getParameter("ldapUser");
$this->password = $container->getParameter("ldapPassword");
$this->basedn = $container->getParameter("ldapBasedn");
$this->baseorganisation = $container->getParameter("ldapBaseorganisation");
$this->baseniveau01 = $container->getParameter("ldapBaseniveau01");
$this->baseniveau02 = $container->getParameter("ldapBaseniveau02");
$this->basegroup = $container->getParameter("ldapBasegroup");
$this->baseuser = $container->getParameter("ldapBaseuser");
$this->username = $container->getParameter("ldapUsername");
$this->firstname = $container->getParameter("ldapFirstname");
$this->lastname = $container->getParameter("ldapLastname");
$this->email = $container->getParameter("ldapEmail");
$this->avatar = $container->getParameter("ldapAvatar");
$this->memberof = $container->getParameter("ldapMemberof");
$this->groupgid = $container->getParameter("ldapGroupgid");
$this->groupname = $container->getParameter("ldapGroupname");
$this->groupmember = $container->getParameter("ldapGroupmember");
$this->groupmemberisdn = $container->getParameter("ldapGroupmemberisdn");
$this->filtergroup = $container->getParameter("ldapFiltergroup");
$this->filteruser = $container->getParameter("ldapFilteruser");
$this->userattributes = [$this->username,$this->firstname,$this->lastname,$this->email,$this->avatar,$this->memberof];
}
public function isNine2Ldap() {
return ($this->connect()&&$this->appMasteridentity=="SQL"&&$this->synchro=="NINE2LDAP"&&$this->userwriter&&$this->baseorganisation&&$this->baseniveau01&&$this->baseniveau02&&$this->basegroup&&$this->baseuser);
}
public function connect() {
// Si on est déjà co = on rebind pour gérer le cas d'un timeout de connection
if($this->connection){
if(!@ldap_bind($this->connection, $this->user, $this->password)){
$this->disconnect();
}
}
if($this->connection){
return $this->connection;
} else {
$ldapConn = ldap_connect($this->host, $this->port);
if($ldapConn){
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
if($this->usetls) ldap_start_tls($ldapConn);
if(@ldap_bind( $ldapConn, $this->user, $this->password)){
$this->connection = $ldapConn;
return $this->connection;
}
}
}
return false;
}
public function userconnect($username,$userpassword) {
$ldapConn = ldap_connect($this->host, $this->port);
$this->connection = $ldapConn;
if($this->connection){
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
if($this->usetls) ldap_start_tls($ldapConn);
$dn = $this->getUserDN($username);
if(@ldap_bind( $ldapConn, $dn, $userpassword)){
$res = $this->search(str_replace("*",$username,$this->filteruser),$this->userattributes, $this->baseuser);
$this->disconnect();
return $res;
}
}
$this->disconnect();
return false;
}
public function getParameter($key) {
switch($key) {
case "baseuser" : return $this->baseuser; break;
case "basegroup" : return $this->basegroup; break;
case "baseniveau01" : return $this->baseniveau01; break;
case "baseniveau02" : return $this->baseniveau02; break;
case "basedn" : return $this->basedn; break;
case "filteruser" : return $this->filteruser; break;
}
}
public function search($filter, $attributes = array(), $subBranch = '') {
$connection = $this->connect();
$branch = ($subBranch ? $subBranch : $this->basedn);
$result = ldap_search($connection, $branch, $filter, $attributes,0,0,0);
if(!$result) {
$this->ldapError();
}
return $this->resultToArray($result);
}
public function searchdn($dn, $subBranch = '') {
$connection = $this->connect();
$tbdn=ldap_explode_dn($dn,0);
$branch = ($subBranch ? $subBranch : $this->basedn);
$result = ldap_search($connection, $branch, "(".$tbdn[0].")", [],0,0,0);
if(!$result) {
$this->ldapError();
}
return $this->resultToArray($result);
}
public function deleteByDN($dn){
$connection = $this->connect();
$removed = ldap_delete($connection, $dn);
if(!$removed){
$this->ldapError();
}
}
public function rename($oldDN, $newDN, $parentDN = '', $deleteOldDN = true){
$connection = $this->connect();
$result = ldap_rename($connection, $oldDN, $newDN, $parentDN, $deleteOldDN);
if(!$result) $this->ldapError();
return $result;
}
private function resultToArray($result){
$connection = $this->connect();
$resultArray = array();
if($result){
$entry = ldap_first_entry($connection, $result);
while ($entry){
$row = array();
$attr = ldap_first_attribute($connection, $entry);
while ($attr){
$val = ldap_get_values_len($connection, $entry, $attr);
if(array_key_exists('count', $val) AND $val['count'] == 1){
$row[strtolower($attr)] = $val[0];
} else {
$row[strtolower($attr)] = $val;
}
if(is_array($row[strtolower($attr)])) {
unset($row[strtolower($attr)]["count"]);
}
$attr = ldap_next_attribute($connection, $entry);
}
$resultArray[] = $row;
$entry = ldap_next_entry($connection, $entry);
}
}
return $resultArray;
}
public function in_array_r($item , $array){
return preg_match('/"'.$item.'"/i' , json_encode($array));
}
public function disconnect(){
if($this->connection) {
ldap_unbind($this->connection);
$this->connection=null;
}
}
public function ldapError(){
$connection = $this->connect();
throw new \Exception(
'Error: ('. ldap_errno($connection) .') '. ldap_error($connection)
);
}
public function ldapModify($dn,$attrs) {
$connection = $this->connect();
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
//==================================================================================================================================================================
//== Function Organisation==========================================================================================================================================
//==================================================================================================================================================================
public function addOrganisations() {
$ldapentrys=$this->searchdn($this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->basedn);
}
$ldapentrys=$this->searchdn($this->baseniveau01,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->baseniveau01);
}
$ldapentrys=$this->searchdn($this->baseniveau02,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->baseniveau02);
}
$ldapentrys=$this->searchdn($this->basegroup,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->basegroup);
}
$ldapentrys=$this->searchdn($this->baseuser,$this->baseorganisation);
if(empty($ldapentrys)) {
$this->addOrganisation($this->baseuser);
}
}
public function addOrganisation($dn) {
$connection = $this->connect();
$attrs = array();
$attrs['objectclass'] = ["top","organizationalUnit"];
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
//==================================================================================================================================================================
//== Function User==================================================================================================================================================
//==================================================================================================================================================================
public function addUser(User $user) {
$connection = $this->connect();
$dn = $this->getUserDN($user->getUsername());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesUser();
$this->fillAttributesUser($user, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyUser(User $user,$entry){
$attrs = [];
$this->fillAttributesUser($user, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyUser(User $user){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesUser($user, $attrs);
// Rechercher le DN du user
$dn = $this->getUserDN($user->getUsername());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function modifyUserpwd(User $user){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
// Attributs associés au password
if($this->type=="AD")
$attrs["unicodepwd"] = $user->getPasswordad();
$attrs['userpassword'] = $user->getPassword();
// Rechercher le DN du user
$dn = $this->getUserDN($user->getUsername());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function updateNiveauUser(User $user,$todel=false) {
$dn = $this->basedn;
$connection = $this->connect();
// NIVEAU01
// On recherche le Niveau01 actuellement asscocié à l'utilisateur
$criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))';
$subbranch=$this->baseniveau01;
$results = $this->search($criteria, array('cn'), $subbranch);
foreach($results as $result) {
// Si Niveau01 différent de celui en cours on le détache de ce Niveau01
if($result["cn"]!=$user->getNiveau01()->getLabel()||$todel) {
$dn = $this->getNiveau01DN($result["cn"]);
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
// On recherche le Niveau01 en cours
if(!$todel) {
$criteria = '(cn='.$user->getNiveau01()->getLabel().')';
$subbranch=$this->baseniveau01;
$result = $this->search($criteria, array('memberuid'), $subbranch);
// S'il n'est pas membre du Niveau01 on le rattache
if(!$this->in_array_r($user->getUsername(),$result[0])) {
$dn = $this->getNiveau01DN($user->getNiveau01()->getLabel());
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
// NIVEAU02
// On recherche le Niveau02 actuellement asscocié à l'utilisateur
$criteria = '(&(cn=*)(memberUid='.$user->getUsername().'))';
$subbranch=$this->baseniveau02;
$results = $this->search($criteria, array('cn'), $subbranch);
foreach($results as $result) {
// Si Niveau02 différent de celui en cours on le détache de ce Niveau02
if($user->getNiveau02()===null||$result["cn"]!=$user->getNiveau02()->getLabel()||$todel) {
$dn = $this->getNiveau02DN($result["cn"]);
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
// On recherche le Niveau02 en cours
if(!$todel) {
if($user->getNiveau02()!==null) {
$criteria = '(cn='.$user->getNiveau02()->getLabel().')';
$subbranch=$this->baseniveau02;
$result = $this->search($criteria, array('memberuid'), $subbranch);
// S'il n'est pas membre du Niveau02 on le rattache
if(empty($result)||!$this->in_array_r($user->getUsername(),$result[0])) {
$dn = $this->getNiveau02DN($user->getNiveau02()->getLabel());
$entry['memberuid'] = $user->getUsername();
$result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
}
}
return $result;
}
public function deleteUser(User $user){
$dn = $this->getUserDN($user->getUsername());
return $this->deleteByDN($dn);
}
public function getObjectClassesUser() {
$oc = array(
'top',
'person',
'organizationalPerson',
'inetOrgPerson',
);
return $oc;
}
public function listAttributesUser() {
return [
"uid",
"cn",
"givenname",
"sn",
"mail",
"displayname",
"telephonenumber",
"postaladdress",
"userpassword",
];
}
public function fillAttributesUser(User $user, array &$attrs) {
$attrs['uid'] = $user->getUsername();
$attrs['cn'] = $user->getFirstname() . ' ' . $user->getLastname();
$attrs['givenname'] = $user->getFirstname();
$attrs['sn'] = $user->getLastname();
$attrs['mail'] = $user->getEmail();
$attrs['displayname'] = $user->getFirstname() . ' ' . $user->getLastname();
$attrs['telephonenumber'] = $user->getTelephonenumber();
$attrs['postaladdress'] = $user->getPostaladress();
$attrs['userpassword'] = $user->getPassword();
}
public function getUserDN($username) {
return $this->username.'='.$username.','.$this->baseuser;
}
//==================================================================================================================================================================
//== Function Niveau01==============================================================================================================================================
//==================================================================================================================================================================
public function findNiveau01($ldapfilter) {
$ldapentrys=$this->search($ldapfilter,[$this->groupgid,$this->groupname,$this->groupmember],$this->baseniveau01);
return $ldapentrys;
}
public function findNiveau01ismember($ldapfilter,$username) {
$ldapentrys=$this->findNiveau01($ldapfilter);
foreach($ldapentrys as $ldapentry) {
if(is_array($ldapentry[$this->groupmember])) {
if(in_array($username,$ldapentry[$this->groupmember])) return true;
}
elseif($username==$ldapentry[$this->groupmember]) return true;
}
return false;
}
public function addNiveau01(Niveau01 $niveau01) {
$connection = $this->connect();
$dn = $this->getNiveau01DN($niveau01->getLabel());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesNiveau01();
$this->fillAttributesNiveau01($niveau01, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyNiveau01(Niveau01 $niveau01,$entry){
$attrs = [];
$this->fillAttributesNiveau01($niveau01, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyNiveau01(Niveau01 $niveau01,$oldid){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesNiveau01($niveau01, $attrs);
unset($attrs["cn"]);
$dn = $this->getNiveau01DN($niveau01->getLabel());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
if(isset($oldid)&&$oldid!=$niveau01->getLabel()) {
$olddn = $this->getNiveau01DN($oldid);
$this->rename($olddn,"cn=".$niveau01->getLabel(),$this->baseniveau01);
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function deleteNiveau01(Niveau01 $niveau01){
$dn = $this->getNiveau01DN($niveau01->getLabel());
return $this->deleteByDN($dn);
}
private function getObjectClassesNiveau01() {
$oc = array(
'top',
'posixGroup',
);
return $oc;
}
public function listAttributesNiveau01() {
return [
"cn",
"gidnumber",
"memberuid",
];
}
public function fillAttributesNiveau01(Niveau01 $niveau01, array &$attrs) {
$attrs['cn'] = $niveau01->getLabel();
$attrs['gidnumber'] = $niveau01->getId();
$attrs['memberuid'] = [];
foreach($niveau01->getUsers() as $user) {
array_push($attrs['memberuid'],$user->getUsername());
}
sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0];
}
public function getNiveau01DN($id) {
return 'cn='.$id.','.$this->baseniveau01;
}
//==================================================================================================================================================================
//== Function Niveau02==============================================================================================================================================
//==================================================================================================================================================================
public function addNiveau02(Niveau02 $niveau02) {
$connection = $this->connect();
$dn = $this->getNiveau02DN($niveau02->getLabel());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesNiveau02();
$this->fillAttributesNiveau02($niveau02, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyNiveau02(Niveau02 $niveau02,$entry){
$attrs = [];
$this->fillAttributesNiveau02($niveau02, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyNiveau02(Niveau02 $niveau02,$oldid){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesNiveau02($niveau02, $attrs);
unset($attrs["cn"]);
$dn = $this->getNiveau02DN($niveau02->getLabel());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
if(isset($oldid)&&$oldid!=$niveau02->getLabel()) {
$olddn = $this->getNiveau02DN($oldid);
$this->rename($olddn,"cn=".$niveau02->getLabel(),$this->baseniveau02);
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function deleteNiveau02(Niveau02 $niveau02){
$dn = $this->getNiveau02DN($niveau02->getLabel());
return $this->deleteByDN($dn);
}
private function getObjectClassesNiveau02() {
$oc = array(
'top',
'posixGroup',
);
return $oc;
}
public function listAttributesNiveau02() {
return [
"cn",
"gidnumber",
"memberuid"
];
}
public function fillAttributesNiveau02(Niveau02 $niveau02, array &$attrs) {
$attrs['cn'] = $niveau02->getLabel();
$attrs['gidnumber'] = $niveau02->getId();
$attrs['memberuid'] = [];
foreach($niveau02->getUsers() as $user) {
array_push($attrs['memberuid'],$user->getUsername());
}
sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0];
}
public function getNiveau02DN($id) {
return 'cn='.$id.','.$this->baseniveau02;
}
//==================================================================================================================================================================
//== Function Group=================================================================================================================================================
//==================================================================================================================================================================
public function addGroup(Group $group) {
$connection = $this->connect();
$dn = $this->getGroupDN($group->getLabel());
$attrs = array();
$attrs['objectclass'] = $this->getObjectClassesGroup();
$this->fillAttributesGroup($group, $attrs);
foreach($attrs as $key => $value){
if(empty($value)){
unset($attrs[$key]);
}
}
$result = ldap_add($connection, $dn, $attrs);
if(!$result) $this->ldapError();
return $result;
}
public function ismodifyGroup(Group $group,$entry){
$attrs = [];
$this->fillAttributesGroup($group, $attrs);
foreach($attrs as $key => $value) {
if(!array_key_exists($key,$entry)&&!empty($value)) return true;
elseif(array_key_exists($key,$entry)&&$value!=$entry[$key]) return true;
}
foreach($entry as $key => $value) {
if(!array_key_exists($key,$attrs)&&!empty($value)) return true;
elseif(array_key_exists($key,$attrs)&&$value!=$attrs[$key]) return true;
}
return false;
}
public function modifyGroup(Group $group,$oldid){
$dn = $this->basedn;
$connection = $this->connect();
$attrs = array();
$this->fillAttributesGroup($group, $attrs);
unset($attrs["cn"]);
$dn = $this->getGroupDN($group->getLabel());
foreach($attrs as $key => $value){
if(empty($value)){
// Bien mettre un @ car si l'attribut est déjà vide cela crache une erreur car l'attribut n'existe déjà plus
@ldap_mod_del($connection, $dn, array($key => array()));
unset($attrs[$key]);
}
}
if(isset($oldid)&&$oldid!=$group->getLabel()) {
$olddn = $this->getGroupDN($oldid);
$this->rename($olddn,"cn=".$group->getLabel(),$this->basegroup);
}
$result = ldap_modify($connection, $dn, $attrs);
if(!$result) $this->ldapError();
}
public function deleteGroup(Group $group){
$dn = $this->getGroupDN($group->getLabel());
return $this->deleteByDN($dn);
}
private function getObjectClassesGroup() {
$oc = array(
'top',
'posixGroup',
);
return $oc;
}
public function listAttributesGroup() {
return [
"cn",
"gidnumber",
"memberuid"
];
}
public function fillAttributesGroup(Group $group, array &$attrs) {
$attrs['cn'] = $group->getLabel();
$attrs['gidnumber'] = $group->getId();
$attrs['memberuid'] = [];
foreach($group->getUsers() as $usergroup) {
array_push($attrs['memberuid'],$usergroup->getUser()->getUsername());
}
sort($attrs['memberuid']);
if(count($attrs['memberuid'])==1) $attrs['memberuid'] = $attrs['memberuid'][0];
}
public function getGroupDN($id) {
return 'cn='.$id.','.$this->basegroup;
}
//==================================================================================================================================================================
//== Function UserGroup=============================================================================================================================================
//==================================================================================================================================================================
function addUserGroup(UserGroup $usergroup) {
$dn = $this->basedn;
$connection = $this->connect();
// On recherche le group en cours
$criteria = '(cn='.$usergroup->getGroup()->getLabel().')';
$subbranch=$this->basegroup;
$result = $this->search($criteria, array('memberuid'), $subbranch);
if(!$this->in_array_r($usergroup->getUser()->getUsername(),$result[0])) {
$dn = $this->getGroupDN($usergroup->getGroup()->getLabel());
$entry['memberuid'] = $usergroup->getUser()->getUsername();
$result = ldap_mod_add($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
return $result;
}
function delUserGroup(UserGroup $usergroup) {
$dn = $this->basedn;
$connection = $this->connect();
// On recherche le group en cours
$criteria = '(cn='.$usergroup->getGroup()->getLabel().')';
$subbranch=$this->basegroup;
$result = $this->search($criteria, array('memberuid'), $subbranch);
if($this->in_array_r($usergroup->getUser()->getUsername(),$result[0])) {
$dn = $this->getGroupDN($usergroup->getGroup()->getLabel());
$entry['memberuid'] = $usergroup->getUser()->getUsername();
$result = ldap_mod_del($connection, $dn, $entry);
if(!$result) $this->ldapError();
}
return $result;
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Service;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
class MailService
{
protected $mailer;
protected $twig;
public function __construct(MailerInterface $mailer, \Twig\Environment $twig)
{
$this->mailer = $mailer;
$this->twig = $twig;
}
/**
* Send email
*
* @param string $template email template
* @param mixed $parameters custom params for template
* @param string $to to email address or array of email addresses
* @param string $from from email address
* @param string $fromName from name
*
* @return boolean send status
*/
public function sendEmail($subject, $body, $to, $from, $fromName = null)
{
$template = $this->twig->load('Home/mail.html.twig');
$parameters=["subject"=>$subject,"body"=>$body];
$subject = $template->renderBlock('subject', $parameters);
$bodyHtml = $template->renderBlock('body', $parameters);
try {
if(!is_array($to)) $to=[$to];
foreach($to as $t) {
$message = (new Email())
->subject($subject)
->from(Address::create($fromName. "<".$from.">"))
->to($t)
->html($bodyHtml);
$this->mailer->send($message);
}
} catch (TransportExceptionInterface $e) {
return $e->getMessage();
}
return true;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Service;
use Symfony\Component\PasswordHasher\Exception\InvalidPasswordException;
use Symfony\Component\PasswordHasher\Hasher\CheckPasswordLengthTrait;
use Symfony\Component\PasswordHasher\LegacyPasswordHasherInterface;
class PasswordEncoder implements LegacyPasswordHasherInterface
{
use CheckPasswordLengthTrait;
public function hash(string $plainPassword, string $salt = null): string
{
if ($this->isPasswordTooLong($plainPassword)) {
throw new InvalidPasswordException();
}
$hash = "{SSHA}" . base64_encode(pack("H*", sha1($plainPassword . $salt)) . $salt);
return $hash;
}
public function verify(string $hashedPassword, string $plainPassword, string $salt = null): bool
{
if ('' === $plainPassword || $this->isPasswordTooLong($plainPassword)) {
return false;
}
var_dump($salt);
return $this->hash($plainPassword,$salt) === $hashedPassword;
}
public function needsRehash(string $hashedPassword): bool
{
return false;
}
}

View File

@ -0,0 +1,87 @@
<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use Oneup\UploaderBundle\Event\PostPersistEvent;
class UploadListener
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
protected function getHeight($image) {
$size = getimagesize($image);
$height = $size[1];
return $height;
}
// Cacul de la largeur
protected function getWidth($image) {
$size = getimagesize($image);
$width = $size[0];
return $width;
}
protected function resizeImage($image,$width,$height,$scale) {
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
$newImage = imagecreatetruecolor( $newImageWidth, $newImageHeight );
imagealphablending( $newImage, false );
imagesavealpha( $newImage, true );
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}
chmod($image, 0640);
return $image;
}
public function onUpload(PostPersistEvent $event)
{
$type=$event->getType();
switch($type) {
default:
$file=$event->getFile();
$filename=$file->getFilename();
$response = $event->getResponse();
$response['file'] = $filename;
break;
}
}
}