Commits

Vittore Zen committed eee1cfc

Manage group into cron and some beautify

  • Participants
  • Parent commits 98ac352

Comments (0)

Files changed (8)

File doc/installazione.md

 
 ```
 apt-get update
-apt-get install php5-intl php5 php5-mysql php5-ldap php5-curl \
+apt-get install php5-intl php5 php5-mysql php5-ldap php5-curl ldap-tools \
 freeradius freeradius-postgresql  mysql-server php-pear \
 rsync git-core curl acl
 ```

File doc/risoluzioneProblemi.md

-Risoluzione problemi comuni
-------------------------------
+# Risoluzione problemi comuni
 
-* Debug della configurazione
+
+## Debug della configurazione
 
 Per procedere al debug della configurazione e verificare eventuali errori puntare il proprio browser 
 all' indirizzo http://indirizzo_del_server/app_dev.php questo visualizzerà eventuali errori del sistema 
 indicando di non usare il certificato ssl:
 
 ```
-parameters:
-    ad_ldap:
+    active_directory:
        use_ssl: false
 ```
 
 */3 * * * * /usr/bin/php /var/www/igroove/app/console getEmail
 ```
 
+
+## Nota per le installazioni su domini Windows 2003
+
+Se lanciando il comando:
+
+```
+/usr/bin/php /var/www/igroove/app/console cron
+```
+
+non vengono creati i gruppi di primo livello, cioè i gruppi che corrispondono ai nomi dei data provider bisogna creare i gruppi corrispondenti manualmente
+ricordadosi che i gruppi di primo livello devono essere Domain LOCAL group e non Global group.
+

File externals/json_services/segremat/index.php

-<?php
-$serviceKey = "lkhjglkh78435vlsd";
-$key = $_REQUEST['key'];
-if ($key != md5($serviceKey . date('Ymd'))) {
-    echo json_encode('1.no valid key');
-    die;
-}
-include ( 'lib/adodb5/adodb.inc.php');
-$filedb = 'C:\inetpub\segremat\Anagrafe.mdb';
-set_time_limit(0);
-
-$db = NewADOConnection('access');
-$db->debug = false;
-$dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=$filedb;Uid=Admin;Pwd=;";
-$db->Connect($dsn);
-$sql = "SELECT Anagrafica.CodiceAlunno, 
-    Anagrafica.Nome, Anagrafica.Cognome, Anagrafica.MailStudente, 
-    Anagrafica.CF_Alunno, Anagrafica.DataNascita, Anagrafica.Classe, 
-    Anagrafica.Settore, Anagrafica.SettoreClasse 
-    FROM Anagrafica 
-    WHERE Anagrafica.TipoNominativo=1
-    ORDER BY Anagrafica.Cognome ASC, Anagrafica.Nome ASC;";
-$recordSet = $db->Execute($sql);
-$elenco = array();
-while (!$recordSet->EOF) {
-    $CodiceAlunno = $recordSet->fields[0];
-    $Nome = $recordSet->fields[1];
-    $Cognome = $recordSet->fields[2];
-    $MailStudente = $recordSet->fields[3];
-    $CF_Alunno = $recordSet->fields[4];
-    $DataNascita = $recordSet->fields[5];
-    $Classe = $recordSet->fields[6];
-    $Settore = $recordSet->fields[7];
-    $SettoreClasse = $recordSet->fields[8];
-
-    $elenco[$CF_Alunno] = array(
-                'id' => $CF_Alunno,
-                'firstname' => trim(ucwords(strtolower($Nome))),
-                'lastname' => trim(ucwords(strtolower($Cognome))),
-                'email' => trim(strtolower($MailStudente)),
-                'group' => trim(str_replace('^', '', $SettoreClasse))
-    );
-    $recordSet->MoveNext();
-}
-$sql = "SELECT 
-    Anagrafica.CF_Alunno
-    FROM Anagrafica 
-    WHERE Anagrafica.TipoNominativo=1 AND (Anagrafica.MailStudente='' OR Anagrafica.MailStudente IS NULL)";
-$recordSet = & $db->Execute($sql);
-while (!$recordSet->EOF) {
-    $CF_Alunno = $recordSet->fields[0];
-    $elenco[$CF_Alunno]['email'] = 'email@non.indicata.it';
-    $recordSet->MoveNext();
-}
-$recordSet->Close();
-$db->Close();
-echo json_encode($elenco);
+<?php
+$serviceKey = "lkhjglkh78435vlsd";
+$key = $_REQUEST['key'];
+if ($key != md5($serviceKey . date('Ymd'))) {
+    echo json_encode('1.no valid key');
+    die;
+}
+include ( 'lib/adodb5/adodb.inc.php');
+$filedb = 'C:\inetpub\segremat\Anagrafe.mdb';
+set_time_limit(0);
+
+$db = NewADOConnection('access');
+$db->debug = false;
+$dsn = "Driver={Microsoft Access Driver (*.mdb)};Dbq=$filedb;Uid=Admin;Pwd=;";
+$db->Connect($dsn);
+$sql = "SELECT Anagrafica.CodiceAlunno, 
+    Anagrafica.Nome, Anagrafica.Cognome, Anagrafica.MailStudente, 
+    Anagrafica.CF_Alunno, Anagrafica.DataNascita, Anagrafica.Classe, 
+    Anagrafica.Settore, Anagrafica.SettoreClasse 
+    FROM Anagrafica 
+    WHERE Anagrafica.TipoNominativo=1
+    ORDER BY Anagrafica.Cognome ASC, Anagrafica.Nome ASC;";
+$recordSet = $db->Execute($sql);
+$elenco = array();
+while (!$recordSet->EOF) {
+    $CodiceAlunno = utf8_encode($recordSet->fields[0]);
+
+    $Nome = $recordSet->fields[1];
+    $Cognome = $recordSet->fields[2];
+    $MailStudente = $recordSet->fields[3];
+    $CF_Alunno =  utf8_encode($recordSet->fields[4]);
+    $DataNascita = $recordSet->fields[5];
+    $Classe = $recordSet->fields[6];
+    $Settore = $recordSet->fields[7];
+    $SettoreClasse = $recordSet->fields[8];
+
+if (strlen($CF_Alunno)==0) {
+        continue;
+    }
+
+    $elenco[$CF_Alunno] = array(
+                'id' => $CF_Alunno,
+                'firstname' => utf8_encode(trim(ucwords(strtolower($Nome)))),
+                'lastname' => utf8_encode(trim(ucwords(strtolower($Cognome)))),
+                'email' => utf8_encode(trim(strtolower($MailStudente))),
+                'group' => utf8_encode(trim(str_replace('^', '', $SettoreClasse)))
+    );
+    $recordSet->MoveNext();
+}
+
+$sql = "SELECT 
+    Anagrafica.CF_Alunno
+    FROM Anagrafica 
+    WHERE Anagrafica.TipoNominativo=1 AND (Anagrafica.MailStudente='' OR Anagrafica.MailStudente IS NULL)";
+$recordSet = & $db->Execute($sql);
+while (!$recordSet->EOF) {
+     $CF_Alunno= utf8_encode($recordSet->fields[0]);
+     if (strlen($CF_Alunno)==0) {
+        continue;
+    }
+    $elenco[$CF_Alunno]['email'] = 'email@non.indicata.it';
+    $recordSet->MoveNext();
+}
+$recordSet->Close();
+$db->Close();
+echo json_encode($elenco);

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

 use Symfony\Component\Console\Output\OutputInterface;
 use Zen\IgrooveBundle\Entity\Student;
 use Zen\IgrooveBundle\LdapTool;
-use Zen\IgrooveBundle\GmailGroup;
-use Zen\IgrooveBundle\GmailUser;
+use Zen\IgrooveBundle\Manager\GmailGroupManager;
+use Zen\IgrooveBundle\Manager\GmailUser;
 use Zen\IgrooveBundle\Entity\GroupComposition;
+use adLDAP\adLDAP;
 
 class CronCommand extends ContainerAwareCommand
 {
         echo "\r\nCRON: Cron start";
         $config = $this->getContainer()->getParameter('data_provider');
         foreach ($config as $provider) {
-            //////echo "\r\n'CRON: importFromDataProviders: ' . $provider['name']);
             echo "\r\n * * * CRON: importFromDataProviders: " . $provider['name'] . " * * *";
             $this->parseProvider($provider);
         }
         $this->removeEmptyGroups();
-        ////echo "\r\n'CRON: Cron end');
+        echo "\r\nCRON: Cron end";
     }
 
     private function parseProvider($provider)
     {
-        // if ($provider['name']!='Formazione continua') return;
 
         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();
+
             if (!$elements) {
                 $elements = array();
             }
             $elements = array();
         }
         $this->parsingGroups($provider, $elements);
-        $this->parsingUsers($provider, $elements);
-        $this->syncronizeGroupsWithUsers($provider); // popolo/cancello i gruppi ldap con i dati presenti nel db
+        //$this->parsingUsers($provider, $elements);
+        //$this->syncronizeGroupsWithUsers($provider);
     }
 
     private function parsingGroups($provider, $elements)
     {
-        $logger = $this->getContainer()->get('logger');
-        $rootGroupName = $provider['name'];
+
+        $providerName=$provider['name'];
+        $rootGroupName = '_' .$provider['name'];
         $rootGroupName = LdapTool::ldapEscape($rootGroupName);
-        $gGroup = new GmailGroup($provider, $logger);
-        $gGroup->createGroup($rootGroupName);
-        $em = $this->getContainer()->get('doctrine')->getEntityManager();
+        $gGroup = new GmailGroupManager($provider);
+        //$gGroup->createGroup($rootGroupName);
+        $em = $this->getContainer()->get('doctrine')->getManager();
         $repository = $em->getRepository('ZenIgrooveBundle:GroupComposition');
         $repository->removeAllImported($rootGroupName);
-        $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('_' . $rootGroupName);
+        $adldap = new adLDAP($config);
+        $ldapRootGroup = $adldap->group()->info($rootGroupName);
+
         if ($ldapRootGroup['count'] == 0) {
             $attributes = array(
-                'group_name' => '_' . $rootGroupName,
+                'group_name' => $rootGroupName,
                 'container' => array(),
-                'description' => 'Gruppo creato da igroove'
+                'description' => 'Gruppo creato da igroove',
             );
             $result = $adldap->group()->create($attributes);
-            $ldapRootGroup = $adldap->group()->info('_' . $rootGroupName);
-            ////echo "\r\n'CRON: Create group ' . '_' . $rootGroupName);
-            echo "\r\n" . 'CRON: Create group ' . '_' . $rootGroupName;
-            $gGroup->createGroup($rootGroupName);
+            $ldapRootGroup = $adldap->group()->info($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")) {
+        /*        if (strpos($v, "CN=Users")) {
                     unset($existingLdapGroups[$k]);
                     continue;
                 }
-                $existingLdapGroups[$k] = trim(substr($v, 4, strpos($v, ',', 4) - 4));
+        */
+                $existingLdapGroups[$k] = trim(substr($v, 3, strpos($v, ',', 3) - 3));
             }
         } else {
             $existingLdapGroups = array();
         }
-        $existingNotImportedGroups = $repository->getNotImportedGroups($rootGroupName);
+
+        $existingNotImportedGroups = $repository->getNotImportedGroups($providerName);
+        foreach ($existingNotImportedGroups as $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);
         $toDeletedGroups = array_diff($existingLdapGroups, $allNeededGroups);
         $existingLdapGroupsLower = array();
+
         foreach ($existingLdapGroups as $element) {
             $existingLdapGroupsLower[] = strtolower($element);
         }
         foreach ($toCreatedGroups as $groupName) {
             $escapedGroupName = LdapTool::ldapEscape($groupName);
             $attributes = array(
-                'group_name' => '_' . $escapedGroupName,
+                'group_name' => $escapedGroupName,
                 'container' => array(),
                 'description' => 'Creato da igroove'
             );
             if (in_array(strtolower($escapedGroupName), $existingLdapGroupsLower)) {
                 continue;
             }
+
             $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;
+            echo "\r\n" . 'CRON: Create group ' .  $escapedGroupName;
             $gGroup->createGroup($escapedGroupName);
+
         }
         foreach ($toDeletedGroups as $groupName) {
             $escapedGroupName = LdapTool::ldapEscape($groupName);
             if (in_array(strtolower($escapedGroupName), $justAdded)) {
                 continue;
             }
-            $result = $adldap->group()->delete('_' . $escapedGroupName, $this);
-            ////$logger->warn('CRON: remove group ' . '_' . $escapedGroupName);
-            echo "\r\n" . 'CRON: remove group ' . '_' . $escapedGroupName;
+            $result = $adldap->group()->delete($escapedGroupName);
+            echo "\r\n" . 'CRON: remove group ' . $escapedGroupName;
             $gGroup->removeGroup($escapedGroupName);
         }
     }
          *     + questi utenti vanno rimossi anche dal db <--- NO! Non rimuovo mai utenti
          * lo faccio a mano a fine anno
          */
-        $logger = $this->getContainer()->get('logger');
-        $rootGroupName = $provider['name'];
+        $providerName=$provider['name'];
+        $rootGroupName = '_' .$provider['name'];
         $rootGroupName = LdapTool::ldapEscape($rootGroupName);
-        $em = $this->getContainer()->get('doctrine')->getEntityManager();
+        $em = $this->getContainer()->get('doctrine')->getManager();
         $repository = $em->getRepository('ZenIgrooveBundle:Student');
         $config = $this->getContainer()->getParameter('ad_ldap');
         $config['account_suffix'] = '@' . $config['account_suffix'];
 
     private function removeEmptyGroups()
     {
-        $logger = $this->getContainer()->get('logger');
-        $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);
         $groups = $adldap->group()->all(false, $search = "_*", true);
 
-        $excludeGroups = array("_internetUsersFromCalendar",
+        $excludeGroups = array(
             "_InternetAccessUsers",
             "_InternetAccess"
         );
             $groupMembers = $adldap->group()->members($group);
             if (!$groupMembers) {
                 $adldap->group()->delete($group);
-                ////$logger->warn('CRON: remove group ' . $group);
+                echo "\r\nCRON: remove empty group " . $group;
             }
         }
     }

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

  * Guest controller.
  *
  */
-class GuestController extends Controller {
-
+class GuestController extends Controller
+{
     /**
      * Lists all Guest entities.
      *
      * @Secure(roles="ROLE_RECEPTION")
      * @Template()
      */
-    public function indexAction() {
+    public function indexAction()
+    {
         $request = $this->get('Request');
         $queryString = $request->get('queryString', false);
         $em = $this->getDoctrine()->getManager();
      * @Secure(roles="ROLE_RECEPTION")
      * @Template()
      */
-    public function showAction($id) {
+    public function showAction($id)
+    {
         $em = $this->getDoctrine()->getManager();
 
         $entity = $em->getRepository('ZenIgrooveBundle:Guest')->find($id);
      * @Secure(roles="ROLE_RECEPTION")
      * @Template()
      */
-    public function newAction() {
+    public function newAction()
+    {
         $entity = new Guest();
         $form = $this->createForm(new GuestType(), $entity);
 
      * @Template("ZenIgrooveBundle:Guest:new.html.twig")
      * @Secure(roles="ROLE_RECEPTION")
      */
-    public function createAction() {
+    public function createAction()
+    {
         $entity = new Guest();
         $request = $this->getRequest();
         $form = $this->createForm(new GuestType(), $entity);
      * @Secure(roles="ROLE_RECEPTION")
      * @Template()
      */
-    public function editAction($id) {
+    public function editAction($id)
+    {
         $em = $this->getDoctrine()->getManager();
 
         $entity = $em->getRepository('ZenIgrooveBundle:Guest')->find($id);
      * @Template("ZenIgrooveBundle:Guest:edit.html.twig")
      * @Secure(roles="ROLE_RECEPTION")
      */
-    public function updateAction($id) {
+    public function updateAction($id)
+    {
         $em = $this->getDoctrine()->getManager();
 
         $entity = $em->getRepository('ZenIgrooveBundle:Guest')->find($id);
      * @Route("/guest/{id}/delete", name="guest_delete")
      * @Secure(roles="ROLE_RECEPTION")
      */
-    public function deleteAction($id) {
+    public function deleteAction($id)
+    {
         $em = $this->getDoctrine()->getManager();
         $entity = $em->getRepository('ZenIgrooveBundle:Guest')->find($id);
 
      * @Route("/checkGuest/guest{id}/{password}", name="checkGuest")
      * @Template("ZenIgrooveBundle:Guest:checkGuest.text.twig")
      */
-    public function checkGuestAction($id, $password) {
+    public function checkGuestAction($id, $password)
+    {
         $em = $this->getDoctrine()->getManager();
         $query = $em->getRepository('ZenIgrooveBundle:Guest')
                 ->createQueryBuilder('g')
      * @Secure(roles="ROLE_RECEPTION")
      * @Template()
      */
-    public function printAction($id) {
+    public function printAction($id)
+    {
         $em = $this->getDoctrine()->getManager();
 
         $entity = $em->getRepository('ZenIgrooveBundle:Guest')->find($id);

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

 use Symfony\Component\HttpFoundation\File\UploadedFile;
 use Consegna\ElaboratiBundle\Studente;
 
-class StudentConsegnaController extends Controller {
-
+class StudentConsegnaController extends Controller
+{
     /**
      * @Route("/consegna", name="consegna")
      * @Template
      */
-    public function consegnaAction() {
+    public function consegnaAction()
+    {
         $adConfig = $this->container->getParameter('ad_ldap');
 
         $studente = new Studente($adConfig);
      * @Route("/homeworkList", name="consegnaListaCompiti")
      * @Template
      */
-    public function listaCompitiAction() {
+    public function listaCompitiAction()
+    {
         $request = $this->get('request');
         $session = $this->getRequest()->getSession();
         $username = $session->get('username');
      * @Route("/upload", name="upload")
      * @Template
      */
-    public function uploadAction() {
+    public function uploadAction()
+    {
         $request = $this->get('request');
         $session = $this->getRequest()->getSession();
 

File src/Zen/IgrooveBundle/Features/Context/FeatureContext.php

     /**
      * @Given /^I am logged as user "([^"]*)" with password "([^"]*)"$/
      */
-    public function iAmLoggedAsUserWithPassword($username, $password) {
+    public function iAmLoggedAsUserWithPassword($username, $password)
+    {
         return array(
             new Given('I am on "/"'),
             new When(sprintf('I fill in "username" with "%s"', $username)),

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

     private $rootGroupName;
     private $logger;
 
-    public function __construct($provider, $logger)
+    public function __construct($provider)
     {
         if (!array_key_exists('gmail_username', $provider)) {
             return false;
         }
-        $this->logger = $logger;
         $this->client = \Zend_Gdata_ClientLogin::getHttpClient($provider['gmail_username'], $provider['gmail_password'], 'apps');
         $this->gdata = new \Zend_Gdata_Gapps($this->client, $provider['gmail_domain']);
         $this->rootGroupName = $provider['name'];
         $group = $this->gdata->retrieveGroup($name);
         if (!$group) {
             $this->gdata->createGroup($name, $groupName, $this->rootGroupName . " - $groupName", 'Anyone');
-            $this->logger->info('CRON: Create gMail group ' . $name);
+            echo "\r\nCRON: Create gMail group " . $name;
         }
     }
 
         $group = $this->gdata->retrieveGroup($name);
         if ($group) {
             $this->gdata->deleteGroup($name, $groupName);
-            $this->logger->warn('CRON: Delete gMail group ' . $name);
+            echo "\r\nCRON: Delete gMail group " . $name;
         }
     }
 
         $group = $this->gdata->retrieveGroup($name);
         if (!$group) {
             $this->gdata->createGroup($name, $groupName, $this->rootGroupName . " - $groupName", 'Anyone');
-            $this->logger->info('CRON: Create gMail group ' . $name);
+            echo "\r\nCRON: Create gMail group " . $name;
         }
         $feed = $this->gdata->retrieveAllMembers($name);
         $list = array();
             }
             try {
                 $this->gdata->addMemberToGroup($email, $name);
-                $this->logger->info('CRON: Add ' . $email . ' to gMail group ' . $name);
+                echo "\r\nCRON: Add ' . $email . ' to gMail group " . $name;
             } catch (\Zend_Gdata_Gapps_ServiceException $e) {
-                $this->logger->err('CRON: email ' . $email . ' not valid');
+                echo "\r\nCRON: email " . $email ." not valid";
             }
         }
         foreach ($removeThese as $email) {
                 continue;
             }
             $this->gdata->removeMemberFromGroup($email, $name);
-            $this->logger->info('CRON: Remove ' . $email . ' to gMail group ' . $name);
+            echo "\r\nCRON: Remove " . $email . " to gMail group " . $name;
         }
     }