Commits

Vittore Zen committed 6566131

Manage internet access

  • Participants
  • Parent commits eee1cfc

Comments (0)

Files changed (16)

     web.vm.network :private_network, ip: "33.33.33.10"
     web.vm.network :forwarded_port, guest: 80, host: 8080,  :name => "http", :auto => true
     #web.vm.network :forwarded_port, guest: 3306, host: 3306,  :name => "mysq", :auto => true
-    web.vm.synced_folder ".", "/vagrant"
+    web.vm.synced_folder ".", "/vagrant", type: "nfs"
     web.vm.provision :puppet do |puppet|
       puppet.manifests_path = "puppet/debian7-web/manifests"
       puppet.manifest_file = "app.pp"
     end
   end
-  config.vm.define "w2008ad" do |w2008ad|
-    w2008ad.vm.box = "windows2008ad"
-    w2008ad.vm.guest = :windows
-
-    w2008ad.windows.halt_timeout = 15
-    w2008ad.windows.username = "vagrant"
-    w2008ad.windows.password = "vagrant"
-    w2008ad.windows.halt_timeout = 15
-    w2008ad.vm.network :private_network, ip: "33.33.33.11"
-    w2008ad.vm.network :forwarded_port, guest: 80, host: 8081  # HTTP
-    w2008ad.vm.network :forwarded_port, guest: 5985, host: 5985, :name => "winrm", :auto => true
-    w2008ad.vm.synced_folder ".", "/vagrant"
-    w2008ad.vm.provider :virtualbox do |vb|
-        vb.gui = true
-    end
+# config.vm.define "w2008ad" do |w2008ad|
+#   w2008ad.vm.box = "windows2008ad"
+#   w2008ad.vm.guest = :windows
+#
+#    w2008ad.windows.halt_timeout = 15
+#    w2008ad.windows.username = "vagrant"
+#    w2008ad.windows.password = "vagrant"
+#    w2008ad.windows.halt_timeout = 15
+#    w2008ad.vm.network :private_network, ip: "33.33.33.11"
+#    w2008ad.vm.network :forwarded_port, guest: 80, host: 8081  # HTTP
+#    w2008ad.vm.network :forwarded_port, guest: 5985, host: 5985, :name => "winrm", :auto => true
+#    w2008ad.vm.synced_folder ".", "/vagrant"
+#    w2008ad.vm.provider :virtualbox do |vb|
+#        vb.gui = true
+#    end
 # w2008ad.vm.provision :shell, :path => "provision.bat"
-  end
-  config.vm.define "mikrotik" do |mt|
-    mt.vm.box = "mikrotik"
-    mt.vm.network :private_network, ip:  "33.33.33.12"
-    mt.vm.network :forwarded_port, guest: 8728, host: 8728,  :name => "api", :auto => true
-    mt.vm.network :forwarded_port, guest: 8791, host: 8791,  :name => "winbox", :auto => true
-  end
+#  end
+#  config.vm.define "mikrotik" do |mt|
+#    mt.vm.box = "mikrotik"
+#    mt.vm.network :private_network, ip:  "33.33.33.12"
+#   mt.vm.network :forwarded_port, guest: 8728, host: 8728,  :name => "api", :auto => true
+#   mt.vm.network :forwarded_port, guest: 8791, host: 8791,  :name => "winbox", :auto => true
+# end
 end

File app/config/parameters.yml.dist

     locale:            it
     secret:            ThisTokenIsNotSoSecretChangeIt
     
-    
+    dizda_cloud_dropbox_user: def@zen.pn.it
+    dizda_cloud_dropbox_password: abc
+    dizda_cloud_dropbox_remote_path: backup/cash    

File src/Zen/IgrooveBundle/Command/CronCommand.php

 
     private function parseProvider($provider)
     {
-
         if (array_key_exists('uri', $provider)) {
             $rawFile = file_get_contents($provider['uri'] . '?key=' . md5($provider['json_key'] . date('Ymd')));
             $elements = ($rawFile) ? json_decode($rawFile) : array();
             $elements = array();
         }
         $this->parsingGroups($provider, $elements);
-        //$this->parsingUsers($provider, $elements);
-        //$this->syncronizeGroupsWithUsers($provider);
+        $this->parsingUsers($provider, $elements);
+        $this->syncronizeGroupsWithUsers($provider);
     }
 
     private function parsingGroups($provider, $elements)
     {
-
-        $providerName=$provider['name'];
-        $rootGroupName = '_' .$provider['name'];
+        $providerName = $provider['name'];
+        $rootGroupName = '_' . $provider['name'];
         $rootGroupName = LdapTool::ldapEscape($rootGroupName);
         $gGroup = new GmailGroupManager($provider);
         //$gGroup->createGroup($rootGroupName);
             );
             $result = $adldap->group()->create($attributes);
             $ldapRootGroup = $adldap->group()->info($rootGroupName);
-            echo "\r\n" . 'CRON: Create group ' .  $rootGroupName;
+            echo "\r\n" . 'CRON: Create group ' . $rootGroupName;
         }
         /*         * ** parsing dei gruppi
           $gruppi ldap esistenti <- $ldapRootGroup
          *
          */
 
-              if (array_key_exists('member', $ldapRootGroup[0])) {
-                  $existingLdapGroups = $ldapRootGroup[0]['member'];
+        if (array_key_exists('member', $ldapRootGroup[0])) {
+            $existingLdapGroups = $ldapRootGroup[0]['member'];
             unset($existingLdapGroups['count']);
             foreach ($existingLdapGroups as $k => $v) {
-        /*        if (strpos($v, "CN=Users")) {
-                    unset($existingLdapGroups[$k]);
-                    continue;
-                }
-        */
+                /*        if (strpos($v, "CN=Users")) {
+                  unset($existingLdapGroups[$k]);
+                  continue;
+                  }
+                 */
                 $existingLdapGroups[$k] = trim(substr($v, 3, strpos($v, ',', 3) - 3));
             }
         } else {
 
         $existingNotImportedGroups = $repository->getNotImportedGroups($providerName);
         foreach ($existingNotImportedGroups as $key => $value) {
-            $existingNotImportedGroups['_' .$key]='_' .$value;
+            $existingNotImportedGroups['_' . $key] = '_' . $value;
         }
         $groupsFromImportedFile = array();
         foreach ($elements as $element) {
-            $groupsFromImportedFile['_' .LdapTool::ldapEscape($element->group)] = '_' .LdapTool::ldapEscape($element->group);
+            $groupsFromImportedFile['_' . LdapTool::ldapEscape($element->group)] = '_' . LdapTool::ldapEscape($element->group);
         }
         $allNeededGroups = array_unique(array_merge($existingNotImportedGroups, $groupsFromImportedFile));
         $toCreatedGroups = array_diff($allNeededGroups, $existingLdapGroups);
 
             $justAdded[] = strtolower($escapedGroupName);
             $result = $adldap->group()->create($attributes);
-            $result = $adldap->group()->addGroup( $rootGroupName, $escapedGroupName);
+            $result = $adldap->group()->addGroup($rootGroupName, $escapedGroupName);
             $existingLdapGroupsLower[] = strtolower($escapedGroupName);
-            echo "\r\n" . 'CRON: Create group ' .  $escapedGroupName;
+            echo "\r\n" . 'CRON: Create group ' . $escapedGroupName;
             $gGroup->createGroup($escapedGroupName);
-
         }
         foreach ($toDeletedGroups as $groupName) {
             $escapedGroupName = LdapTool::ldapEscape($groupName);
          *     + questi utenti vanno rimossi anche dal db <--- NO! Non rimuovo mai utenti
          * lo faccio a mano a fine anno
          */
-        $providerName=$provider['name'];
-        $rootGroupName = '_' .$provider['name'];
+        $providerName = $provider['name'];
+        $rootGroupName = '_' . $provider['name'];
         $rootGroupName = LdapTool::ldapEscape($rootGroupName);
         $em = $this->getContainer()->get('doctrine')->getManager();
         $repository = $em->getRepository('ZenIgrooveBundle:Student');
-        $config = $this->getContainer()->getParameter('ad_ldap');
+        $config = $this->getContainer()->getParameter('active_directory');
         $config['account_suffix'] = '@' . $config['account_suffix'];
-        $adldap = new \adLDAP($config);
+        $adldap = new adLDAP($config);
         $ldapAllUsersArray = LdapTool::getAllUsersLists($config);
         $ldapAllUsers = $ldapAllUsersArray['all'];
         $ldapAllIgrooveUsers = $ldapAllUsersArray['igroove'];
 
         $i = 1;
         foreach ($elements as $element) {
-            echo "\r\n" . ($i++) . ". " . $element->lastname . ' ' . $element->firstname;
+            echo "\r\n" . ($i++) . ". " . $element->lastname . ' // ' . $element->firstname;
             $student = $repository->findOneBy(array('distinguished_id' => strtolower($element->id)));
             $existInLdap = (array_key_exists(strtolower($element->id), $ldapAllIgrooveUsers)) ? true : false;
             $existInDb = ($student) ? true : false;
+            $element->email = ($element->email == 'email@non.indicata.it') ? 'no-email@for.this.student.network' : $element->email;
             /*
              * Ho 4 casi:
              * - l'utente esiste in ldap e nel db -> aggiorno entrambi con i dati importati
              * - l'utente non esiste in ldap e nel db -> trovo lo username e creo l'utente in ldap e nel db con i dati importati
              */
             if ($existInLdap and $existInDb) {
-                echo "/1/ -> update LDAP";
+                echo "\t/1/ -> update LDAP";
                 $student->setFirstname($element->firstname ? $element->firstname : 'MANCA IL NOME');
                 $student->setLastname($element->lastname ? $element->lastname : 'MANCA IL COGNOME');
                 if (@$element->email) {
                     $student->setEmail($element->email);
                 }
 
-                LdapTool::updateLdapUser($student, $config, $ldapAllUsers, $logger);
+                LdapTool::updateLdapUser($student, $config, $ldapAllUsers);
             }
             if ($existInLdap and ! $existInDb) {
-                echo "/2/ -> create in db -> update LDAP";
+                echo "\t/2/ -> create in db -> update LDAP";
                 $student = new Student();
                 $student->setUsername(strtolower($ldapAllUsers[strtolower($element->id)]['samaccountname']));
                 $student->setDistinguishedId(strtoupper($element->id));
                 $student->setFirstname($element->firstname ? $element->firstname : 'MANCA IL NOME');
                 $student->setLastname($element->lastname ? $element->lastname : 'MANCA IL COGNOME');
-
-                $student->setStartingPassword(LdapTool::getRandomPassword($this->getContainer()->getParameter('ad_ldap')));
+                $student->setStartingPassword(LdapTool::getRandomPassword($config['password']));
                 $student->setImported(true);
-                LdapTool::updateLdapUser($student, $config, $ldapAllUsers, $logger);
+                LdapTool::updateLdapUser($student, $config, $ldapAllUsers);
             }
             if (!$existInLdap and $existInDb) {
-                echo "/3/ -> create in LDAP";
+                echo "\t/3/ -> create in LDAP";
                 $student->setFirstname($element->firstname ? $element->firstname : 'MANCA IL NOME');
                 $student->setLastname($element->lastname ? $element->lastname : 'MANCA IL COGNOME');
                 $student->setImported(true);
                 if (strlen($student->getStartingPassword()) == 0) {
-                    $student->setStartingPassword(LdapTool::getRandomPassword($this->getContainer()->getParameter('ad_ldap')));
+                    $student->setStartingPassword(LdapTool::getRandomPassword($config['password']));
                 }
-                $student = LdapTool::createLdapUser($student, $ldapAllUsers, $config, $provider, $logger);
+                $student = LdapTool::createLdapUser($student, $ldapAllUsers, $config, $provider);
                 $ldapAllUsersArray = LdapTool::getAllUsersLists($config);
                 $ldapAllUsers = $ldapAllUsersArray['all'];
                 $ldapAllIgrooveUsers = $ldapAllUsersArray['igroove'];
             }
             if (!$existInLdap and ! $existInDb) {
-                echo "/4/ -> create in db -> create in LDAP";
+                echo "\t/4/ -> create in db -> create in LDAP";
                 $student = new Student();
                 $student->setDistinguishedId(strtoupper($element->id));
                 $student->setFirstname($element->firstname ? $element->firstname : 'MANCA IL NOME');
                 $student->setLastname($element->lastname ? $element->lastname : 'MANCA IL COGNOME');
-                $student->setStartingPassword(LdapTool::getRandomPassword($this->getContainer()->getParameter('ad_ldap')));
+                $student->setStartingPassword(LdapTool::getRandomPassword($config['password']));
                 $student->setImported(true);
-                $student = LdapTool::createLdapUser($student, $ldapAllUsers, $config, $provider, $logger);
+                $student = LdapTool::createLdapUser($student, $ldapAllUsers, $config, $provider);
                 $ldapAllUsersArray = LdapTool::getAllUsersLists($config);
                 $ldapAllUsers = $ldapAllUsersArray['all'];
                 $ldapAllIgrooveUsers = $ldapAllUsersArray['igroove'];
             }
             $composition = new GroupComposition();
-            $composition->setRootGroup($rootGroupName);
+            $composition->setRootGroup($providerName);
             $composition->setSubGroup(LdapTool::ldapEscape($element->group));
             $composition->setStudent($student);
             $composition->setImported(true);
             $em->persist($composition);
             $student->addGroupComposition($composition);
             $em->persist($student);
+
             $emailStudente = $this->gestioneEmailStudente(
-                    $student, $element->email, $config, $adldap, $ldapAllUsers, $logger, $gmailConnection);
-            if ((array_key_exists(strtolower($student->getDistinguishedId()), $ldapAllUsers)) AND ( array_key_exists('email', $ldapAllUsers[strtolower($student->getDistinguishedId())])) AND ( $ldapAllUsers[strtolower($student->getDistinguishedId())]['email'] != $emailStudente)
-            ) {
-                $student->setEmail($emailStudente);
-                $em->persist($student);
-                LdapTool::updateLdapUser($student, $config, $ldapAllUsers, $logger);
+                    $student, $element->email, $config, $adldap, $ldapAllUsers, $gmailConnection);
+            if ($emailStudente != @$ldapAllUsers[strtolower($student->getDistinguishedId())]['email']) {
+
+                if ((array_key_exists(strtolower($student->getDistinguishedId()), $ldapAllUsers)) AND ( array_key_exists('email', $ldapAllUsers[strtolower($student->getDistinguishedId())])) AND ( $ldapAllUsers[strtolower($student->getDistinguishedId())]['email'] != $emailStudente)
+                ) {
+                    $student->setEmail($emailStudente);
+                    $em->persist($student);
+                    LdapTool::updateLdapUser($student, $config, $ldapAllUsers);
+                    echo " (change email to $emailStudente)";
+                }
             }
 
             if ($provider['force_imported_password']) {
 
     private function syncronizeGroupsWithUsers($provider)
     {
-        $logger = $this->getContainer()->get('logger');
-        $em = $this->getContainer()->get('doctrine')->getEntityManager();
+        $em = $this->getContainer()->get('doctrine')->getManager();
         $repository = $em->getRepository('ZenIgrooveBundle:GroupComposition');
         $groupsName = $repository->getAllSubGroup($provider['name']);
-        $gGroup = new GmailGroup($provider, $logger);
+        $gGroup = new GmailGroupManager($provider);
         echo "\r\n* * * syncronizeGroupsWithUsers";
         foreach ($groupsName as $groupName) {
             echo "\r\n - " . $groupName;
             $studentsInGroup = $repository->getAllStudentsInThisGroup($provider['name'], $groupName);
             $listInDb = (is_array($studentsInGroup)) ? array_keys($studentsInGroup) : array();
-            $config = $this->getContainer()->getParameter('ad_ldap');
+            $config = $this->getContainer()->getParameter('active_directory');
             $config['account_suffix'] = '@' . $config['account_suffix'];
-            $adldap = new \adLDAP($config);
+            $adldap = new adLDAP($config);
             $groupMembers = $adldap->group()->members('_' . $groupName);
             $groupMembers = (is_array($groupMembers)) ? $groupMembers : array();
             // ottenere i dati del gruppo
     private function gestioneEmailStudente($studente, $email, $config, $adldap, $ldapAllUsers, $logger, $gmailConnection = false)
     {
         if (!$this->getContainer()->hasParameter('google_apps_for_student')) {
-            return false;
+            return $studente->getEmail();
         }
         $googleAppsForStudentConfig = $this->getContainer()->getParameter('google_apps_for_student');
         $emailStripped = substr($email, 0, strpos($email, '@'));
                 $notFound = true;
                 foreach ($ldapAllUsers as $user) {
                     if (($user['email'] == $email) AND ( $user['samaccountname'] != $username)) {
-                        $studente->setEmail('email@erro.re');
+                        $studente->setEmail('email@errore.network');
                         $container = $this->getContainer();
                         $mailer = $container->get('mailer');
                         $message = \Swift_Message::newInstance()

File src/Zen/IgrooveBundle/Command/InternetCommand.php

 use Symfony\Component\Console\Input\InputInterface;
 use Symfony\Component\Console\Output\OutputInterface;
 use Zen\IgrooveBundle\LdapTool;
-use Zen\IgrooveBundle\GoogleCalendar;
-use PEAR2\Net\RouterOS\Client as Ros;
-use PEAR2\Net\RouterOS\Request as RosRequest;
+use Zen\IgrooveBundle\MikrotikPool;
+use adLDAP\adLDAP;
 
 class InternetCommand extends ContainerAwareCommand
 {
     protected function execute(InputInterface $input, OutputInterface $output)
     {
         $dataProvider = $this->getContainer()->getParameter('data_provider');
-        $logger = $this->getContainer()->get('logger');
 
-        $nowDown = new \DateTime('now -4 minutes');
+        $nowDown = new \DateTime('now -1 minutes');
 
-        $nowUp = new \DateTime('now +4 minutes');
+        $nowUp = new \DateTime('now +1 minutes');
 
         $setThese = array();
         $events = array();
                 if (($timeToCheck >= $nowDown) and ( $timeToCheck <= $nowUp)) {
                     $setThese[$provider['name']] = $check;
                 }
-
-                if (array_key_exists('calendar', $provider)) {
-                    $calendar = $provider['calendar'];
-                    $googleCalendar = new GoogleCalendar($provider, $calendar, $logger);
-                    $users = $googleCalendar->getUsersFromDates(date('Y-m-d\T') . $nowDown . ':00', date('Y-m-d\T') . $nowUp . ':00');
-                }
             }
         }
-        print_r($setThese);
-
-        if (sizeof($setThese) > 0) {
-            $config = $this->getContainer()->getParameter('ad_ldap');
-            $config['account_suffix'] = '@' . $config['account_suffix'];
-            $adldap = new \adLDAP($config);
-            $groupsInInternet = $adldap->group()->inGroup('_InternetAccess');
-            if (!$groupsInInternet) {
-                $attributes = array(
-                    'group_name' => '_InternetAccess',
-                    'container' => array(),
-                    'description' => 'Gruppo creato da igroove'
-                );
-                $result = $adldap->group()->create($attributes);
-            }
-            $groupNameInInternet = array();
-            if (is_array($groupsInInternet)) {
-                foreach ($groupsInInternet as $key => $groupAD) {
-                    $groupNameInInternet[] = substr($groupAD, 4, strpos($groupAD, ',', 3) - 4);
-                }
-            }
-            foreach ($setThese as $name => $toSet) {
-                if ($toSet == 'force_off_convitto') {
-                    $this->forceOffConvitto();
-                } else {
-                    $groups = $adldap->group()->inGroup('_' . $name);
-                    if (!$groups) {
-                        continue;
-                    }
-                    foreach ($groups as $key => $groupAD) {
-                        $group = substr($groupAD, 4, strpos($groupAD, ',', 3) - 4);
-                        $explodeFlag = true;
-                        if ($toSet == 'on') {
-                            $result = $adldap->group()->addGroup('_InternetAccess', '_' . $group);
-                        }
-                        if ($toSet == 'off') {
-                            $result = $adldap->group()->removeGroup('_InternetAccess', '_' . $group);
-                        }
-                    }
-                }
-                if ($toSet == 'force_off') {
-                    $this->forceMikrotikOffForGroup($name);
-                }
-            }
-        }
-        $config = $this->getContainer()->getParameter('ad_ldap');
+        $config = $this->getContainer()->getParameter('active_directory');
         $config['account_suffix'] = '@' . $config['account_suffix'];
-        $adldap = new \adLDAP($config);
-        $ldapRootGroup = $adldap->group()->info('_internetUsersFromCalendar');
-        if ($ldapRootGroup['count'] == 0) {
+        $adldap = new adLDAP($config);
+
+        $groupInfo = $adldap->group()->info('_InternetAccess');
+
+        if ($groupInfo == 0) {
             $attributes = array(
-                'group_name' => '_internetUsersFromCalendar',
+                'group_name' => '_InternetAccess',
                 'container' => array(),
                 'description' => 'Gruppo creato da igroove'
             );
             $result = $adldap->group()->create($attributes);
         }
-        $result = $adldap->group()->addGroup('_InternetAccess', '_internetUsersFromCalendar');
-        $groupMembers = $adldap->group()->members('_internetUsersFromCalendar');
-        $groupMembers = (is_array($groupMembers)) ? $groupMembers : array();
-        // ottenere i dati del gruppo
-        // calcolare chi aggiungere e chi rimuovere
-
-        $removeTheseUsers = array_diff($groupMembers, $users);
-        $addTheseUsers = array_diff($users, $groupMembers);
-        foreach ($removeTheseUsers as $user) {
-            $explodeFlag = true;
-            $groups = $adldap->group()->removeUser('_internetUsersFromCalendar', $user);
-        }
-        foreach ($addTheseUsers as $user) {
-            $explodeFlag = true;
-            $groups = $adldap->group()->addUser('_internetUsersFromCalendar', $user);
-        }
 
-        if ($explodeFlag) {
-            $logger->warn('CRON-INTERNET: explode users');
-            $config = $this->getContainer()->getParameter('ad_ldap');
-            $config['account_suffix'] = '@' . $config['account_suffix'];
-            $adldap = new \adLDAP($config);
-            LdapTool::Explode($config);
-        }
-        echo "\r\nCRON-INTERNET: end";
-    }
+        $userNameInInternet = $adldap->group()->members('_InternetAccess', false);
+        $groupsInInternet = $adldap->group()->inGroup('_InternetAccess');
 
-    protected function forceMikrotikOffForGroup($group)
-    {
-        $logger = $this->getContainer()->get('logger');
-        $mikrotiks = $this->getContainer()->getParameter('mikrotik');
-        $dataProviders = $this->getContainer()->getParameter('data_provider');
-        $radiusSuffix = 'no-radius-suffix-set';
-        foreach ($dataProviders as $dataProvider) {
-            if ($dataProvider['name'] == $group) {
-                $radiusSuffix = '@' . @$dataProvider['radius_suffix'];
+        $groupNameInInternet = array();
+        if (is_array($groupsInInternet)) {
+            foreach ($groupsInInternet as $key => $groupAD) {
+                $groupNameInInternet[] = substr($groupAD, 3, strpos($groupAD, ',', 3) - 3);
             }
         }
-        $config = $this->getContainer()->getParameter('ad_ldap');
-        $config['account_suffix'] = '@' . $config['account_suffix'];
-        $adldap = new \adLDAP($config);
-        $groupMembers = $adldap->group()->members('_' . $group, true);
-        foreach ($mikrotiks as $mikrotik) {
-            $client = new Ros($mikrotik['ip'], $mikrotik['username'], $mikrotik['password']);
-            if ($client) {
-                $responses = $client->sendSync(new RosRequest('/ip/hotspot/active/print'));
-                foreach ($responses as $element) {
-                    $activeUser = strstr(strtolower(trim($element->getArgument('user'))), $radiusSuffix, true);
-                    if (in_array($activeUser, $groupMembers)) {
-                        $id = $element->getArgument('.id');
-                        $delRequest = new RosRequest('/ip/hotspot/active/remove');
-                        $delRequest->setArgument('numbers', $id);
-                        $client->sendSync($delRequest);
+        print "\r\nActual groups in _InternetAccess: " . implode(', ', $groupNameInInternet);
+        print "\r\nActual users in _InternetAccess: " . implode(', ', $userNameInInternet);
+        echo "\r\n + Check timeout ";
+        $date = new \DateTime();
+        $em = $this->getContainer()->get('doctrine')->getManager();
+        $query = $em->getRepository('ZenIgrooveBundle:InternetOpen')
+                ->createQueryBuilder('i')
+                ->select('i.type, i.account')
+                ->where(' i.close_at <= :date')
+                ->setParameter('date', $date)
+                ->getQuery();
+        $closures = $query->getResult();
+        foreach ($closures as $closure) {
+            if ($closure['type'] == 'group') {
+                echo "\r\n   + TIMEOUT - remove group " . $closure['account'];
+                $result = $adldap->group()->removeGroup('_InternetAccess', $closure['account']);
+            }
+            if ($closure['type'] == 'user') {
+                echo "\r\n   + TIMEOUT - remove user " . $closure['account'];
+                $em->getRepository('ZenIgrooveBundle:InternetOpen')->removeUser($closure['account']);
+                $result = $adldap->group()->removeUser('_InternetAccess', $closure['account']);
+            }
+        }
+
+        if (sizeof($setThese) > 0) {
+            echo "\r\n + It's time to close (or open)!";
+            foreach ($setThese as $name => $toSet) {
+
+                $groups = $adldap->group()->inGroup('_' . $name);
+                if (!$groups) {
+                    continue;
+                }
+                foreach ($groups as $key => $groupAD) {
+                    $group = substr($groupAD, 4, strpos($groupAD, ',', 3) - 4);
+                    $explodeFlag = true;
+                    if ($toSet == 'on') {
+                        echo "\r\n   + Open to _" . $group;
+                        $result = $adldap->group()->addGroup('_InternetAccess', '_' . $group);
+                    }
+                    if ($toSet == 'off') {
+                        echo "\r\n   + Close to _" . $group;
+
+                        $result = $adldap->group()->removeGroup('_InternetAccess', '_' . $group);
                     }
                 }
             }
         }
+
+        echo "\r\n + Explode users";
+
+        LdapTool::Explode($config);
+        echo "\r\n + Try to talks with mikrotiks";
+        $mikrotikPool = new MikrotikPool($this->getContainer()->getParameter('mikrotik'));
+        $mikrotikPool->KickOffUsers($config);
+        echo "\r\n + All done!\r\n";
     }
 
 }

File src/Zen/IgrooveBundle/Command/RosCommand.php

 use Symfony\Component\HttpFoundation\Request;
 use PEAR2\Net\RouterOS\Client as Ros;
 use PEAR2\Net\RouterOS\Request as RosRequest;
-use Monolog\Logger;
 
 class RosCommand extends ContainerAwareCommand
 {
     {
         $this
                 ->setName('ros')
-                ->setDescription('Importing and parsin');
+                ->setDescription('Importing and parsing');
     }
 
     protected function execute(InputInterface $input, OutputInterface $output)
     {
         $mikrotiks = $this->getContainer()->getParameter('mikrotik');
-        foreach ($mikrotiks as $mikrotik) {
-            $logger = $this->getContainer()->get('logger');
             $em = $this->getContainer()->get('doctrine')->getEntityManager();
             $repository = $em->getRepository('ZenIgrooveBundle:Mac');
             $entities = $repository->getActiveMacs(new \DateTime());
                         strtoupper($entity['device']) . ' - ' .
                         ucwords(strtolower($entity['lastname'] . ' ' . $entity['firstname']));
             }
+
+        foreach ($mikrotiks as $mikrotik) {
+            echo "\r\n Router: ".$mikrotik['ip'];
             $client = new Ros($mikrotik['ip'], $mikrotik['username'], $mikrotik['password']);
             if ($client) {
                 $responses = $client->sendSync(new RosRequest('/ip/hotspot/ip-binding/print'));
                 $macToRemove = array_diff_key($macIntoMikrotik, $macInIgroove);
                 foreach ($macToAdd as $mac => $comment) {
                     print "\r\n[Mikrotik router] Add " . $mac . " " . $comment;
-                    $logger->warn("[Mikrotik router] Add " . $mac . " " . $comment);
                     $addRequest = new RosRequest('/ip/hotspot/ip-binding/add');
                     $addRequest->setArgument('mac-address', $mac);
                     $addRequest->setArgument('type', "bypassed");
                 }
                 foreach ($macToRemove as $mac => $element) {
                     print "\r\n[Mikrotik router] Remove #" . $element['id'] . " " . $mac . " " . $element['comment'];
-                    $logger->warn("[Mikrotik router] Remove #" . $element['id'] . " " . $mac . " " . $element['comment']);
                     $delRequest = new RosRequest('/ip/hotspot/ip-binding/remove');
                     $delRequest->setArgument('numbers', $element['id']);
                     $client->sendSync($delRequest);

File src/Zen/IgrooveBundle/Controller/InternetController.php

 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
 use JMS\SecurityExtraBundle\Annotation\Secure;
+use Zen\IgrooveBundle\Entity\InternetOpen;
 use Zen\IgrooveBundle\LdapTool;
-use Monolog\Logger;
+use Zen\IgrooveBundle\MikrotikPool;
+use adLDAP\adLDAP;
+use Zen\IgrooveBundle\Manager\InternetAccessManager;
 
 class InternetController extends Controller
 {
             }
         }
 
-        return array('groups' => $groups, 'random' => time());
+        return array('groups' => $groups);
     }
 
     /**
      */
     public function getChildGroupsAction($rootGroup)
     {
-        $config = $this->container->getParameter('ad_ldap');
+        $config = $this->container->getParameter('active_directory');
         $config['account_suffix'] = '@' . $config['account_suffix'];
-        $adldap = new \adLDAP($config);
+        $adldap = new adLDAP($config);
         $groupsInInternet = $adldap->group()->inGroup('_InternetAccess');
         $groupNameInInternet = array();
         if (is_array($groupsInInternet)) {
                 $groupNameInInternet[] = substr($group, 4, strpos($group, ',', 3) - 4);
             }
         }
+        $userNameInInternet = $adldap->group()->members('_InternetAccessUsers');
+
         $groups = $adldap->group()->inGroup('_' . $rootGroup);
         $groupsList = array();
         foreach ($groups as $key => $group) {
             $groupName = substr($group, 4, strpos($group, ',', 3) - 4);
             $groupMembers = $adldap->group()->members('_' . $groupName);
-            $stato = (in_array($groupName, $groupNameInInternet)) ? true : false;
-            $groupsList[$groupName] = array(
-                'name' => $groupName,
-                'count' => sizeof($groupMembers),
-                'stato' => $stato
-            );
+            if (in_array($groupName, $groupNameInInternet)) {
+                $groupsList[$groupName] = array(
+                    'name' => $groupName,
+                    'count' => sizeof($groupMembers),
+                    'stato' => true,
+                    'user' => array()
+                );
+            } else {
+                $groupsList[$groupName] = array(
+                    'name' => $groupName,
+                    'count' => sizeof($groupMembers),
+                    'stato' => false,
+                    'user' => array_intersect($groupMembers, $userNameInInternet)
+                );
+            }
         }
         ksort($groupsList);
 
-        return array('random' => time(), 'rootGroup' => $rootGroup, 'groups' => $groupsList);
+        $dataProvider = $this->container->getParameter('data_provider');
+        $now = new \DateTime();
+        $setThese = array();
+        $events = array();
+        $explodeFlag = false;
+        $users = array();
+
+        $startTime = new \DateTime('today');
+        $timeToSet = new \DateTime("+1 hour");
+        foreach ($dataProvider as $provider) {
+            if ($provider['name'] != $rootGroup) {
+                continue;
+            }
+            foreach ($provider['internet'] as $time => $check) {
+                $timeToCheck = new \DateTime($time);
+                if (($now >= $startTime) and ( $now <= $timeToCheck)) {
+                    $setThese = $check;
+                    $timeToSet = $timeToCheck;
+                    break;
+                }
+                $startTime = $timeToCheck;
+            }
+        }
+
+        return array('rootGroup' => $rootGroup, 'groups' => $groupsList, 'timeToSet' => $timeToSet);
     }
 
     /**
-     * @Route("/toogleInternet/{rootGroup}/{group}", name="toogleInternet")
+     * @Route("/internet/users/group/{group}/{rootGroup}", name="getUsersInGroup")
      * @Secure(roles="ROLE_TEACHER")
      * @Template()
      */
-    public function toogleInternetAction($rootGroup, $group)
+    public function getUsersInGroupAction($group,$rootGroup)
     {
-        $logger = $this->get('logger');
-        $config = $this->container->getParameter('ad_ldap');
-        $mikrotik = $this->container->getParameter('mikrotik');
+        $config = $this->container->getParameter('active_directory');
         $config['account_suffix'] = '@' . $config['account_suffix'];
-        $adldap = new \adLDAP($config);
-        $groupsInInternet = $adldap->group()->inGroup('_InternetAccess');
-        $groupNameInInternet = array();
-        if (is_array($groupsInInternet)) {
-            foreach ($groupsInInternet as $key => $groupAD) {
-                $groupNameInInternet[] = substr($groupAD, 4, strpos($groupAD, ',', 3) - 4);
+        $adldap = new adLDAP($config);
+        $usersInGroup = $adldap->group()->members('_' . $group);
+        $userNameInInternet = $adldap->group()->members('_InternetAccessUsers');
+        $em = $this->getDoctrine()->getManager();
+        $query = $em->getRepository('ZenIgrooveBundle:Student')
+                ->createQueryBuilder('s')
+                ->select('s')
+                ->Join('s.group_compositions', 'c', 'WITH', ' c.subGroup = :sub_group')
+                ->orderBy('s.lastname, s.firstname')
+                ->setParameter('sub_group', $group)
+                ->getQuery();
+        $students = $query->getResult();
+        foreach ($students as $student) {
+            if (array_search($student->getUsername(), $userNameInInternet)) {
+                $student->stato = true;
+            } else {
+                $student->stato = false;
             }
         }
-        if (in_array($group, $groupNameInInternet)) {
-            $result = $adldap->group()->removeGroup('_InternetAccess', '_' . $group);
-        } else {
-            $result = $adldap->group()->addGroup('_InternetAccess', '_' . $group);
-        }
-        LdapTool::Explode($config, $mikrotik);
+
+        $startTime = new \DateTime('today');
+        $timeToSet = new \DateTime("+1 hour");
+
+        return array('group' => $group, 'students' => $students, 'timeToSet' => $timeToSet, 'rootGroup'=> $rootGroup);
+    }
+
+    /**
+     * @Route("/internet/on/{rootGroup}", name="internetOn")
+     * @Secure(roles="ROLE_TEACHER")
+     * @Template()
+     */
+    public function internetOnAction($rootGroup)
+    {
+        $request = $this->get('Request');
+        $timeToSet = $request->get('timeToSet', false);
+        $group = $request->get('group', false);
+        $em = $this->getDoctrine()->getManager();
+        $closeAt = new \DateTime($timeToSet);
+        $internetOpen = new InternetOpen();
+        $internetOpen->setType('group');
+        $internetOpen->setAccount('_' . $group);
+        $internetOpen->setCloseAt($closeAt);
+        $em->persist($internetOpen);
+        $em->flush();
+
+        $config = $this->container->getParameter('active_directory');
+         $config['account_suffix'] = '@' . $config['account_suffix'];
+        $mikrotik = $this->container->getParameter('mikrotik');
+        $internetAccessManager = new InternetAccessManager($config, $mikrotik);
+        $internetAccessManager->addGroup('_' .$group);
+
+        LdapTool::Explode($config);
+
+        return $this->redirect(
+                        $this->generateUrl(
+                                'getChildGroups', array(
+                            'rootGroup' => $rootGroup
+        )));
+    }
+
+    /**
+     * @Route("/internet/off/{rootGroup}/{group}", name="internetOff")
+     * @Secure(roles="ROLE_TEACHER")
+     * @Template()
+     */
+    public function internetOffAction($rootGroup,$group)
+    {
+        $em = $this->getDoctrine()->getManager();
+
+        $em->getRepository('ZenIgrooveBundle:InternetOpen')->removeGroup('_' .$group);
+
+        $config = $this->container->getParameter('active_directory');
+        $config['account_suffix'] = '@' . $config['account_suffix'];
+        $mikrotik = $this->container->getParameter('mikrotik');
+        $internetAccessManager = new InternetAccessManager($config, $mikrotik);
+        $internetAccessManager->removeGroup('_' .$group);
+
+        LdapTool::Explode($config);
+        $mikrotikPool = new MikrotikPool($mikrotik);
+        $mikrotikPool->KickOffUsers($config);
+
+        return $this->redirect(
+                        $this->generateUrl(
+                                'getChildGroups', array(
+                            'rootGroup' => $rootGroup
+        )));
+    }
+
+    /**
+     * @Route("/internet/on/user/{rootGroup}/{group}", name="internetOnUser")
+     * @Secure(roles="ROLE_TEACHER")
+     * @Template()
+     */
+    public function internetOnUserAction($rootGroup, $group)
+    {
+        $request = $this->get('Request');
+        $timeToSet = $request->get('timeToSet', false);
+        $user = $request->get('user', false);
+        $em = $this->getDoctrine()->getManager();
+        $closeAt = new \DateTime($timeToSet);
+        $internetOpen = new InternetOpen();
+        $internetOpen->setType('user');
+        $internetOpen->setAccount($user);
+        $internetOpen->setCloseAt($closeAt);
+        $em->persist($internetOpen);
+        $em->flush();
+
+        $config = $this->container->getParameter('active_directory');
+        $config['account_suffix'] = '@' . $config['account_suffix'];
+        $mikrotik = $this->container->getParameter('mikrotik');
+        $internetAccessManager = new InternetAccessManager($config, $mikrotik);
+        $internetAccessManager->addUser($user);
+
+        LdapTool::Explode($config);
+
+        return $this->redirect(
+                        $this->generateUrl(
+                                'getUsersInGroup', array(
+                            'group' => $group,
+                            'rootGroup' => $rootGroup
+        )));
+    }
+
+    /**
+     * @Route("/internet/off/user/{rootGroup}/{group}/{user}", name="internetOffUser")
+     * @Secure(roles="ROLE_TEACHER")
+     * @Template()
+     */
+    public function internetOffUserAction($rootGroup, $group, $user)
+    {
+        $em = $this->getDoctrine()->getManager();
+        $em->getRepository('ZenIgrooveBundle:InternetOpen')->removeUser($user);
+
+        $config = $this->container->getParameter('active_directory');
+        $mikrotik = $this->container->getParameter('mikrotik');
+        $internetAccessManager = new InternetAccessManager($config, $mikrotik);
+        $internetAccessManager->removeUser($user);
+
+        $config['account_suffix'] = '@' . $config['account_suffix'];
+        LdapTool::Explode($config);
+        $mikrotikPool = new MikrotikPool($mikrotik);
+        $mikrotikPool->KickOffUsers($config);
 
         return $this->redirect(
                         $this->generateUrl(
-                                'getChildGroups', array('random' => time(),
+                                'getUsersInGroup', array(
+                            'group' => $group,
                             'rootGroup' => $rootGroup
         )));
     }

File src/Zen/IgrooveBundle/Controller/MacController.php

 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
 use Zen\IgrooveBundle\Entity\Mac;
 use Zen\IgrooveBundle\Form\MacType;
-use Monolog\Logger;
 
 /**
  * Mac controller.
         $form->bindRequest($request);
 
         if ($form->isValid()) {
-            $logger = $this->get('logger');
             $em = $this->getDoctrine()->getManager();
             $em->persist($entity);
             $em->flush();
         $editForm->bindRequest($request);
 
         if ($editForm->isValid()) {
-            $logger = $this->get('logger');
             $em->persist($entity);
             $em->flush();
 
         $form->bindRequest($request);
 
         if ($form->isValid()) {
-            $logger = $this->get('logger');
             $em = $this->getDoctrine()->getManager();
             $entity = $em->getRepository('ZenIgrooveBundle:Mac')->find($id);
 

File src/Zen/IgrooveBundle/Controller/StudentController.php

 
             if ($list) {
                 return $this->redirect($this->generateUrl('showStudentsGroup', array(
-                                    'random' => time(),
+
                                     'rootGroup' => 1,
                                     'group' => 1
                                         )
                 ));
             } else {
                 return $this->redirect($this->generateUrl('showRootGroup', array(
-                                    'random' => time(),
+
                                     'rootGroup' => 'Studenti senza attribuzione'
                                         )
                 ));
             $groups[] = $provider['name'];
         }
 
-        return array('groups' => $groups, 'random' => time());
+        return array('groups' => $groups);
     }
 
     /**
     public function getStudentsChildGroupsAction($rootGroup, $random)
     {
         if ($rootGroup == 'Studenti senza attribuzione') {
-            return $this->redirect($this->generateUrl('showStudentsGroup', array('random' => time(),
+            return $this->redirect($this->generateUrl('showStudentsGroup', array(
                                 'rootGroup' => 'Studenti senza attribuzione',
                                 'group' => 'Da assegnare')));
         }
                 ->getQuery();
         $groups = $query->getResult();
 
-        return array('random' => time(), 'rootGroup' => $rootGroup, 'groups' => $groups);
+        return array('rootGroup' => $rootGroup, 'groups' => $groups);
     }
 
     /**

File src/Zen/IgrooveBundle/Entity/InternetOpen.php

 /**
  * @ORM\Entity
  * @ORM\HasLifecycleCallbacks
+  * @ORM\Entity(repositoryClass="Zen\IgrooveBundle\Repository\InternetOpenRepository")
  */
 class InternetOpen
 {

File src/Zen/IgrooveBundle/LdapTool.php

 
 namespace Zen\IgrooveBundle;
 
-use Monolog\Logger;
-use PEAR2\Net\RouterOS\Client as Ros;
-use PEAR2\Net\RouterOS\Request as RosRequest;
+use adLDAP\adLDAP;
 
 class LdapTool
 {
     public static function Explode($config, $mikrotiks = false)
     {
-        $adldap = new \adLDAP($config);
-        $userIntoMikrotik = array();
-        if ($mikrotiks) {
-            foreach ($mikrotiks as $mikrotik) {
-                $client[$mikrotik['ip']] = new Ros($mikrotik['ip'], $mikrotik['username'], $mikrotik['password']);
-                if ($client[$mikrotik['ip']]) {
-                    $responses = $client[$mikrotik['ip']]->sendSync(new RosRequest('/ip/hotspot/active/print'));
-                    $macIntoMikrotik[$mikrotik['ip']] = array();
-
-                    foreach ($responses as $element) {
-                        $userIntoMikrotik[$mikrotik['ip']][strtolower(
-                                        substr(
-                                                $element->getArgument('user'), 0, strpos($element->getArgument('user'), '@'
-                                                )
-                                        )
-                                )] = $element->getArgument('.id');
-                    }
-                }
-            }
-        }
+        $adldap = new adLDAP($config);
+
         $groupMembers = $adldap->group()->members('_InternetAccess', true);
-        $groupMembersUsers1 = $adldap->group()->members('_InternetAccessUsers');
-        $groupMembersUsers2 = $adldap->group()->membersLarge('_InternetAccessUsers');
-        $groupMembersUsers = (sizeof($groupMembersUsers1) != 0) ? $groupMembersUsers1 : $groupMembersUsers2;
+        $groupMembersUsers = $adldap->group()->members('_InternetAccessUsers');
         if (!$groupMembersUsers) {
             $groupMembersUsers = array();
             $attributes = array(
         $removeUsers = array_diff($groupMembersUsers, $groupMembers);
         foreach ($removeUsers as $user) {
             $groups = $adldap->group()->removeUser('_InternetAccessUsers', $user);
-            foreach ($mikrotiks as $mikrotik) {
-                if (array_key_exists(strtolower($user), $userIntoMikrotik[$mikrotik['ip']])) {
-                    $delRequest = new RosRequest('/ip/hotspot/active/remove');
-                    $delRequest->setArgument('numbers', $userIntoMikrotik[$mikrotik['ip']][strtolower($user)]);
-                    $client[$mikrotik['ip']]->sendSync($delRequest);
-                }
-            }
         }
         $addUsers = array_diff($groupMembers, $groupMembersUsers);
         foreach ($addUsers as $user) {
 
     public static function getAllUsersLists($config)
     {
-        $adldap = new \adLDAP($config);
-        $ldapMembers = array();
-        for ($i = 48; $i <= 57; $i++) {
-            $ldapMembers = array_merge($ldapMembers, $adldap->user()->allWithDetails(chr($i) . '*'));
-        }
-        for ($i = 65; $i <= 90; $i++) {
-            $ldapMembers = array_merge($ldapMembers, $adldap->user()->allWithDetails(chr($i) . '*'));
-        }
-        for ($i = 97; $i <= 122; $i++) {
-            $ldapMembers = array_merge($ldapMembers, $adldap->user()->allWithDetails(chr($i) . '*'));
-        }
+        $adldap = new adLDAP($config);
+        $ldapMembers = $adldap->user()->all(
+                array("samaccountname", "displayname", 'description', 'department', 'givenname', 'sn', 'mail', 'homedirectory','homedrive')
+        );
+        /*
+
+          return;
+          $adldap = new adLDAP($config);
+          $ldapMembers = array();
+          for ($i = 48; $i <= 57; $i++) {
+          $ldapMembers = array_merge($ldapMembers, $adldap->user()->allWithDetails(chr($i) . '*'));
+          }
+          for ($i = 65; $i <= 90; $i++) {
+          $ldapMembers = array_merge($ldapMembers, $adldap->user()->allWithDetails(chr($i) . '*'));
+          }
+          for ($i = 97; $i <= 122; $i++) {
+          $ldapMembers = array_merge($ldapMembers, $adldap->user()->allWithDetails(chr($i) . '*'));
+          }
+         *
+         */
         $ldapLists = array();
         $ldapIgrooveLists = array();
         $i = 1;
+
         foreach ($ldapMembers as $k => $v) {
-            $id = ($v[2]) ? $v[2] : ($i++);
-            if (strpos($v[1], 'igroove')) {
-                $ldapIgrooveLists[strtolower($id)] = array(
-                    'samaccountname' => $k,
-                    'dn' => $v[0],
-                    'description' => $v[1],
-                    'firstname' => $v[3],
-                    'lastname' => $v[4],
-                    'email' => $v[5]
-                );
-            }
+
+            $id = ($v['department']) ? $v['department'] : ($i++);
             $ldapLists[strtolower($id)] = array(
-                'samaccountname' => $k,
-                'dn' => $v[0],
-                'description' => $v[1],
-                'department' => $v[2],
-                'firstname' => $v[3],
-                'lastname' => $v[4],
-                'email' => $v[5],
-                'homedirectory' => $v[6]
+                'samaccountname' => $v['samaccountname'],
+                'dn' => $v['displayname'],
+                'description' => $v['description'],
+                'firstname' => $v['givenname'],
+                'lastname' => $v['sn'],
+                'email' => $v['mail'],
+                'department' => $v['department'],
+                'homedirectory' => $v['homedirectory'],
+                'homedrive' => $v['homedrive']
             );
+            if (strpos($v['description'], 'igroove')) {
+                $ldapIgrooveLists[strtolower($id)] = $ldapLists[strtolower($id)];
+            }
         }
 
         return array('igroove' => $ldapIgrooveLists, 'all' => $ldapLists);
     }
 
-    public static function updateLdapUser($student, $config, $ldapAllUsers, $logger)
+    public static function updateLdapUser($student, $config, $ldapAllUsers)
     {
         if (!array_key_exists(strtolower($student->getDistinguishedId()), $ldapAllUsers)) {
             return false;
         }
         $userInLdap = $ldapAllUsers[strtolower($student->getDistinguishedId())];
         $homedirectory = $config['home_folder'] . strtolower($student->getUsername());
-        if (!$student->getEmail()) {
-            $student->setEmail('');
+if ($student->getEmail() != "") {
+            $attributes["email"] = $student->getEmail();
+        } else {
+            $attributes["email"] = 'no-email@for.this.student.network';
         }
+
         if (
-                ($userInLdap['firstname'] == $student->getFirstname()) and ( $userInLdap['lastname'] == $student->getLastname()) and ( $userInLdap['department'] == strtoupper($student->getDistinguishedId())) and ( $userInLdap['email'] == $student->getEmail()) and ( $userInLdap['homedirectory'] == $homedirectory)
+                ($userInLdap['firstname'] == $student->getFirstname()) and ( $userInLdap['lastname'] == $student->getLastname()) and ( $userInLdap['department'] == strtoupper($student->getDistinguishedId()))
+                and (( $userInLdap['email'] == $student->getEmail()) or ($student->getEmail()=='') )and ( $userInLdap['homedirectory'] == $homedirectory) and ( $userInLdap['homedrive'] == $config['home_drive'] . ':')
         ) {
+            echo " -> Same record";
+
             return true;
         }
         $attributes = array(
             "surname" => $student->getLastName(),
             "description" => "Creato da igroove",
             "department" => strtoupper($student->getDistinguishedId()),
-            "home_drive" => "H:",
-            "home_directory" => $homedirectory
+            "home_drive" => strtoupper($config['home_drive'] . ':'),
+            "home_directory" => $homedirectory,
+            'email' => $attributes["email"]
         );
 
-        if ($student->getEmail() != "") {
-            $attributes["email"] = $student->getEmail();
-        } else {
-            $attributes["email"] = '';
-        }
-
-        $adldap = new \adLDAP($config);
+        $adldap = new adLDAP($config);
         $result = $adldap->user()->modify(strtolower($student->getUsername()), $attributes);
 
-        $logger->warn('CRON: Update user details for ' . $student->getUsername() . ' aka ' . $student->getFirstname() . ' ' . $student->getLastname());
+        //      echo "\r\nCRON: Update user details for " . $student->getUsername() . ' aka ' . $student->getFirstname() . ' ' . $student->getLastname();
     }
 
-    public static function createLdapUser($student, $ldapAllUsers, $config, $provider, $logger)
+    public static function createLdapUser($student, $ldapAllUsers, $config, $provider)
     {
-        $samAccounts = array();
-        foreach ($ldapAllUsers as $user) {
-            $samAccounts[] = $user['samaccountname'];
-        }
         if ($provider['auto_create_username']) {
-            $lastname = LdapTool::ldapEscape(str_replace(array(' ', '\''), '', ($student->getLastname())));
-            $firstname = LdapTool::ldapEscape(str_replace(array(' ', '\''), '', ($student->getFirstname() . '23456789')));
-            $trySamAccount = false;
-            for ($i = 1; $i <= strlen($firstname); $i++) {
-                $trySamAccount = substr(strtolower(substr($firstname, 0, $i) . '.' . $lastname), 0, 20);
-                if (!in_array($trySamAccount, $samAccounts)) {
-                    $username = $trySamAccount;
-                    break;
-                }
-            }
-            if (!$trySamAccount) {
-                $logger->err('CRON: Error creating user ' . $student->getFirstname() . ' ' . $student->getLastname());
 
-                return false;
-            }
+            $username = LdapTool::generateUsername($student, $ldapAllUsers, $config, $provider);
             $student->setUsername(strtolower($username));
         } else {
             $student->setUsername(strtolower($student->getDistinguishedId()));
             "department" => strtoupper($student->getDistinguishedId()),
             "enabled" => 1,
             "password" => $student->getStartingPassword(),
-            "container" => array('Users'),
-            "home_drive" => "H:",
+            "container" => array(),
+            "home_drive" => strtoupper($config['home_drive'] . ':'),
             "home_directory" => $home_directory
         );
 
         if ($student->getEmail()) {
             $attributes["email"] = $student->getEmail();
         } else {
-            $attributes["email"] = 'no-email@for.this.student.it';
+            $attributes["email"] = 'no-email@for.this.student.network';
         }
 
-        $adldap = new \adLDAP($config);
-        $result = @$adldap->user()->create($attributes);
+        $adldap = new adLDAP($config);
+        $result = $adldap->user()->create($attributes);
         if (!$result) {
             $attributes['firstname'].= ' - ' . $attributes['department'];
             $result = @$adldap->user()->create($attributes);
             if (!$result) {
-                $logger->err('CRON: ERROR creating user ' . $student->getUsername() . ' aka ' . $student->getFirstname() . ' ' . $student->getLastname());
+                echo "\r\nCRON: ERROR creating user " . $student->getUsername() . ' aka ' . $student->getFirstname() . ' ' . $student->getLastname();
 
                 return $student;
             }
         }
-        echo "\r\nCRON: Create user " . $student->getUsername() . ' aka ' . $student->getFirstname() . ' ' . $student->getLastname();
-
+        //    echo "\r\nCRON: Create user " . $student->getUsername() . ' aka ' . $student->getFirstname() . ' ' . $student->getLastname();
         return $student;
     }
 
 
     public static function getRandomPassword($config)
     {
-        $len = $config['password_min_char'];
-        $password = rand(pow(10, $len - 1), pow(10, $len) - 1);
+        $password = '';
+        if (@$config['complexity'] == true) {
+            $password = 'az-';
+        }
+        $len = $config['min_char'] - strlen($password);
+        $password .= rand(pow(10, $len - 1), pow(10, $len) - 1);
 
         return $password;
     }
 
+    private static function generateUsername($student, $ldapAllUsers, $config, $provider)
+    {
+        $samAccounts = array();
+        foreach ($ldapAllUsers as $user) {
+            $samAccounts[] = $user['samaccountname'];
+        }
+        if ($config['username_style'] == 'INIZIALENOME.COGNOME') {
+            $lastname = LdapTool::ldapEscape(str_replace(array(' ', '\''), '', ($student->getLastname())));
+            $firstname = LdapTool::ldapEscape(str_replace(array(' ', '\''), '', ($student->getFirstname() . '23456789')));
+            $trySamAccount = false;
+            for ($i = 1; $i <= strlen($firstname); $i++) {
+                $trySamAccount = substr(strtolower(substr($firstname, 0, $i) . '.' . $lastname), 0, 20);
+                if (!in_array($trySamAccount, $samAccounts)) {
+                    $username = $trySamAccount;
+                    break;
+                }
+            }
+            if (!$trySamAccount) {
+                $logger->err('CRON: Error generatin username for user ' . $student->getFirstname() . ' ' . $student->getLastname());
+
+                return false;
+            }
+
+            return (strtolower($username));
+        }
+        if ($config['username_style'] == 'NOME.COGNOME') {
+            $lastname = LdapTool::ldapEscape(str_replace(array(' ', '\''), '', ($student->getLastname())));
+            $firstname = LdapTool::ldapEscape(str_replace(array(' ', '\''), '', ($student->getFirstname())));
+
+            $trySamAccount = substr("$firstname.$lastname",0,20);
+            if ( !in_array($trySamAccount, $samAccounts)) {
+                $username = $trySamAccount;
+
+                return (strtolower($username));
+            }
+
+                die;
+                $trySamAccount = false;
+                for ($i = 1; $i <= strlen($firstname); $i++) {
+                    $trySamAccount = substr(strtolower(substr($firstname, 0, $i) . '.' . $lastname), 0, 20);
+                    if (!in_array($trySamAccount, $samAccounts)) {
+                        $username = $trySamAccount;
+                        break;
+                    }
+                }
+                if (!$trySamAccount) {
+                    $logger->err('CRON: Error generatin username for user' . $student->getFirstname() . ' ' . $student->getLastname());
+
+                    return false;
+                }
+
+                return (strtolower($username));
+            }
+
+    }
+
 }

File src/Zen/IgrooveBundle/Manager/InternetAccessManager.php

 <?php
+
 namespace Zen\IgrooveBundle\Manager;
 
+use Zen\IgrooveBundle\LdapTool;
+use Zen\IgrooveBundle\MikrotikPool;
+use adLDAP\adLDAP;
+
 class InternetAccessManager
 {
+    private $mikrotikPool;
+    private $config;
+    private $groupNameInInternet;
+    private $userNameInInternet;
+
+    public function __construct($config, $mikrotik)
+    {
+        if (substr($config['account_suffix'],0,1)!='@') {
+        $config['account_suffix'] = '@' . $config['account_suffix'];
+        }
+        $this->adldap = new adLDAP($config);
+        $this->mikrotikPool = new MikrotikPool($mikrotik);
+        $this->getUsers();
+    }
+
+    private function getUsers()
+    {
+        $groupsInInternet = $this->adldap->group()->inGroup('_InternetAccess');
+        $groupNameInInternet = array();
+        if (is_array($groupsInInternet)) {
+            foreach ($groupsInInternet as $key => $groupAD) {
+                $groupNameInInternet[] = substr($groupAD, 3, strpos($groupAD, ',', 3) - 3);
+            }
+        }
+
+        $this->userNameInInternet= $this->adldap->group()->members('_InternetAccess',false);
+
+        $this->groupNameInInternet = $groupNameInInternet;
+    }
+
+    public function addGroup($group)
+    {
+        if (!in_array($group, $this->groupNameInInternet)) {
+            $result = $this->adldap->group()->addGroup('_InternetAccess',  $group);
+            $this->getUsers();
+            LdapTool::Explode($this->config);
+        }
+    }
+
+    public function removeGroup($group)
+    {
+        if (in_array($group, $this->groupNameInInternet)) {
+            $result = $this->adldap->group()->removeGroup('_InternetAccess',  $group);
+            $this->getUsers();
+
+            LdapTool::Explode($this->config);
+            $this->mikrotikPool->KickOffUsers($this->config);
+        }
+    }
+
+    public function addUser($user)
+    {
+        if (!in_array($user, $this->userNameInInternet)) {
+            $result = $this->adldap->group()->addUser('_InternetAccess',  $user);
+            $this->getUsers();
+            LdapTool::Explode($this->config);
+        }
+    }
+
+    public function removeUser($user)
+    {
+        if (in_array($user, $this->userNameInInternet)) {
+            $result = $this->adldap->group()->removeUser('_InternetAccess',$user);
+            $this->getUsers();
+
+            LdapTool::Explode($this->config);
+            $this->mikrotikPool->KickOffUsers($this->config);
+        }
+    }
 
 }

File src/Zen/IgrooveBundle/MikrotikPool.php

+<?php
+
+namespace Zen\IgrooveBundle;
+
+use PEAR2\Net\RouterOS\Client as Ros;
+use PEAR2\Net\RouterOS\Request as RosRequest;
+use adLDAP\adLDAP;
+
+class MikrotikPool
+{
+    private $mikrotiks;
+    private $mikrotikClient;
+    private $userIntoMikrotik;
+    private $internetAccessUsers;
+
+    public function __construct($mikrotiks)
+    {
+        $this->mikrotiks=$mikrotiks;
+        $userIntoMikrotik = array();
+        if ($mikrotiks) {
+            foreach ($mikrotiks as $mikrotik) {
+                $mikrotikClient[$mikrotik['ip']] = new Ros($mikrotik['ip'], $mikrotik['username'], $mikrotik['password']);
+                if ($mikrotikClient[$mikrotik['ip']]) {
+                    $responses = $mikrotikClient[$mikrotik['ip']]->sendSync(new RosRequest('/ip/hotspot/active/print'));
+                    $macIntoMikrotik[$mikrotik['ip']] = array();
+
+                    foreach ($responses as $element) {
+                        $userIntoMikrotik[$mikrotik['ip']][strtolower(
+                                        substr(
+                                                $element->getArgument('user'), 0, strpos($element->getArgument('user'), '@'
+                                                )
+                                        )
+                                )] = $element->getArgument('.id');
+                    }
+                }
+            }
+        }
+
+        $this->userIntoMikrotik=$userIntoMikrotik;
+
+    }
+
+    public function KickOffUsers($config)
+    {
+                $adldap = new adLDAP($config);
+                $groupMembersUsers= $adldap->group()->members('_InternetAccessUsers');
+        if (!$groupMembersUsers) {
+            $groupMembersUsers = array();
+            $attributes = array(
+                'group_name' => '_InternetAccessUsers',
+                'container' => array(),
+                'description' => 'Gruppo creato da igroove'
+            );
+            $result = @$adldap->group()->create($attributes);
+        }
+
+                        $this->internetAccessUsers=$groupMembersUsers;
+
+        foreach ($groupMembersUsers as $user) {
+            foreach ($this->mikrotiks as $mikrotik) {
+                if (array_key_exists(strtolower($user), $this->userIntoMikrotik[$mikrotik['ip']])) {
+                    $delRequest = new RosRequest('/ip/hotspot/active/remove');
+                    $delRequest->setArgument('numbers', $thi->userIntoMikrotik[$mikrotik['ip']][strtolower($user)]);
+                    $client[$mikrotik['ip']]->sendSync($delRequest);
+                }
+            }
+        }
+
+    }
+
+}

File src/Zen/IgrooveBundle/Repository/InternetOpenRepository.php

+<?php
+
+namespace Zen\IgrooveBundle\Repository;
+
+use Doctrine\ORM\EntityRepository;
+
+/**
+ * InternetOpenRepository
+ *
+ * This class was generated by the Doctrine ORM. Add your own custom
+ * repository methods below.
+ */
+class InternetOpenRepository extends EntityRepository
+{
+    public function removeGroup($group)
+    {
+
+                $em = $this->getEntityManager();
+        $query = $em->getRepository('ZenIgrooveBundle:InternetOpen')
+                ->createQueryBuilder('i')
+                ->delete()
+                ->where('i.type = :type and i.account = :account')
+                ->setParameter('type', 'group')
+                ->setParameter('account', $group)
+                ->getQuery();
+        $results = $query->getResult();
+
+        return $results;
+    }
+
+        public function removeUser($user)
+    {
+
+                $em = $this->getEntityManager();
+        $query = $em->getRepository('ZenIgrooveBundle:InternetOpen')
+                ->createQueryBuilder('i')
+                ->delete()
+                ->where('i.type = :type and i.account = :account')
+                ->setParameter('type', 'user')
+                ->setParameter('account', $user)
+                ->getQuery();
+        $results = $query->getResult();
+
+        return $results;
+    }
+
+}

File src/Zen/IgrooveBundle/Resources/views/Internet/getChildGroups.html.twig

 {% extends '::base.html.twig' %}
 
-{% block content %}
-    <ul data-role="listview" data-inset="true"  data-theme="g">
-        <li data-role="list-divider">Utilizzatori &gt; {{ rootGroup }}</li>
+{% block body %}
+    <h1>Utilizzatori &gt; {{ rootGroup }}</h1>
+    <h3>Legenda</h3>
+    <p>
+        <i class="glyphicon glyphicon-globe"></i> Navigazione attiva per tutto il gruppo -
+        <i class="glyphicon glyphicon-user"></i>  Sono presenti utenti con navigazione singola attiva
+    </p>
+    <div class="table-responsive">
+        <table class="table table-striped">
 
-        {% set listDivider = '' %}
+            {% set listDivider = '' %}
             {% for group in groups %}
 
                 {% if group.name|upper|slice(0, 1) != listDivider %}
                     {% set listDivider = group.name|upper|slice(0, 1) %}
-                        <li data-role="list-divider">{{listDivider }}</li>
+                    <tr class="info"><td colspan="3"align="center">{{ listDivider }}</td></tr>
+                    {% endif %}
+                <tr>
+                    <td>
+                        {% if group.stato  %}
+                            <i class="glyphicon glyphicon-globe"></i>
+                        {% endif %}
+                        {% if group.user  %}
+                            <i class="glyphicon glyphicon-user"></i>
+                        {% endif %}
+                    </td>
+                    <td>{{ group.name }}
+                    </td>
+                    <td>
+                        <button id="BTN-{{group.name}}"
+                            class="btn btn-success internetOn" >
+                            <i class="glyphicon glyphicon-time"></i> Attiva
+                        </button>
+                        <a href="{{ path('internetOff',{'rootGroup': rootGroup,'group':group.name, 'rootGroup': rootGroup}) }}" class="btn btn-danger">
+                            Disattiva
+                        </a>
+{% if not group.stato  %}
+                        <a href="{{ path('getUsersInGroup',{'group':group.name, 'rootGroup': rootGroup}) }}" class="btn btn-default">
+                            <i class="glyphicon glyphicon-user"></i> Singolo studente
+                        </a>
                             {% endif %}
-                            <li data-icon="false">
-                                <a href="{{ path('toogleInternet',
-                {'random': random, 'rootGroup': rootGroup,'group':group.name}
-             ) }}">
-                                    {{ group.name }}
-                                    <span class="ui-li-count">
-                                        {% if group.stato  %}
-                                            <span style="color:green">
-                                            {% else %}
-                                                <span style="color:red">
-                                                {% endif %}
-                                                {{ group.count }} utenti
-                                            </span></span>
-                                </a>
-                            </li>
-                            {% endfor %}
-                            </ul>
-
-                            {% endblock %}
+
+                    </td>
+                </tr>
+            {% endfor %}
+        </table>
+    </div>
+
+
+    <div class="modal fade" id="setTime" tabindex="-1" role="dialog" aria-labelledby="setTime" aria-hidden="true">
+        <div class="modal-dialog">
+            <div class="modal-dialog">
+                <div class="modal-content">
+                    <div class="modal-header">
+                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
+                        <h4 class="modal-title">Attivazione internet</h4>
+                    </div>
+                    <div class="modal-body">
+                        Attiva <span id="group"></span> fino alle: <input type="text" id="timeToSet" value="{{ timeToSet|date("H:i") }}">
+                    </div>
+                    <div class="modal-footer">
+                        <button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
+                        <button id="confirm" type="button" class="btn btn-primary">Attiva</button>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <script>
+        var group='';
+        var timeToSet='{{ timeToSet|date("H:i") }}';
+        $(".internetOn").click(function() {
+            $('#setTime').modal('show');
+            group=(this.id).substring(4);
+             $('#group').html(group);
+        });
+                $("#confirm").click(function() {
+            timeToSet=$('#timeToSet').val();
+            window.location.href = "{{ path('internetOn',{'rootGroup': rootGroup}) }}?group=" + group + "&timeToSet=" +timeToSet;
+            $('#setTime').modal('hide');
+        });
+    </script>
+
+    <a href="{{ path('internet') }}" class="btn btn-default"><i class="glyphicon glyphicon-icon-arrow-left"></i>Ritorna alla lista</a>
+
+{% endblock %}

File src/Zen/IgrooveBundle/Resources/views/Internet/getUsersInGroup.html.twig

+{% extends '::base.html.twig' %}
+
+{% block body %}
+
+
+
+
+            <h1>Users &gt; {{ group }}</h1>
+    <h3>Legenda</h3>
+    <p>
+        <i class="glyphicon glyphicon-globe"></i> Navigazione attiva
+    </p>
+    <div class="table-responsive">
+        <table class="table table-striped">
+
+
+           {% for student in students %}
+
+
+                <tr>
+                    <td>
+                        {% if student.stato  %}
+                            <i class="glyphicon glyphicon-globe"></i>
+                        {% endif %}
+
+                    </td>
+                    <td>{{ student.lastname }} {{ student.firstname}}
+
+             (
+
+                        {{ student.username }}
+               )
+                    </td>
+                    <td>
+                        <button id="BTN-{{student.username}}"
+                            class="btn btn-success internetOn" >
+                            <i class="glyphicon glyphicon-time"></i> Attiva
+                        </button>
+                        <a href="{{ path('internetOffUser',{'user': student.username,'group':group,  'rootGroup': rootGroup}) }}" class="btn btn-danger">
+                            Disattiva
+                        </a>
+
+
+                    </td>
+                </tr>
+
+        {% endfor %}
+
+
+        </table>
+    </div>
+
+
+    <div class="modal fade" id="setTime" tabindex="-1" role="dialog" aria-labelledby="setTime" aria-hidden="true">
+        <div class="modal-dialog">
+            <div class="modal-dialog">
+                <div class="modal-content">
+                    <div class="modal-header">
+                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
+                        <h4 class="modal-title">Attivazione internet</h4>
+                    </div>
+                    <div class="modal-body">
+                        Attiva <span id="user"></span> fino alle: <input type="text" id="timeToSet" value="{{ timeToSet|date("H:i") }}">
+                    </div>
+                    <div class="modal-footer">
+                        <button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
+                        <button id="confirm" type="button" class="btn btn-primary">Attiva</button>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+                     <a href="{{ path ('getChildGroups', { 'rootGroup': rootGroup }) }}" class="btn btn-default"><i class="glyphicon glyphicon-icon-arrow-left"></i>Ritorna alla lista {{rootGroup}}</a>
+
+
+    <script>
+        var user='';
+        var timeToSet='{{ timeToSet|date("H:i") }}';
+        $(".internetOn").click(function() {
+            $('#setTime').modal('show');
+            user=(this.id).substring(4);
+             $('#user').html(user);
+        });
+                $("#confirm").click(function() {
+            timeToSet=$('#timeToSet').val();
+            window.location.href = "{{ path('internetOnUser',{'group': group, 'rootGroup': rootGroup}) }}?user=" + user + "&timeToSet=" +timeToSet;
+            $('#setTime').modal('hide');
+        });
+
+
+
+       </script>
+
+
+{% endblock %}

File src/Zen/IgrooveBundle/Resources/views/Internet/internet.html.twig

 {% extends '::base.html.twig' %}
 
-{% block content %}
-    <ul data-role="listview" data-inset="true"  data-theme="g">
-        <li data-role="list-divider">Users</li>
-            {% for group in groups %}
-            <li><a href="{{ path ('getChildGroups', { 'rootGroup': group ,'random': random }) }}">{{ group }}</a></li>
-            {% endfor %}
-    </ul>
-
+{% block body %}
+    <h1>Utilizzatori</h1>
+    <div class="list-group">
+        {% for group in groups %}
+            <a class="list-group-item" href="{{ path ('getChildGroups', { 'rootGroup': group }) }}">{{ group }}</a>
+        {% endfor %}
+    </div>
 {% endblock %}