Пример #1
0
    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return void
     * @throws \RuntimeException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('
	Welcome to the EtuUTT UV manager

This command helps you to syncronize downloaded UV with the database.

If you did not import the guide previously, please use

	etu:uv:import url

This manager is very carfeul: it won\'t remove any UV from the
databsse, it will only update them.
');
        /*
         * Init the components
         */
        /** @var Container $container */
        $container = $this->getContainer();
        /** @var EntityManager $em */
        $em = $container->get('doctrine')->getManager();
        /** @var DialogHelper $dialog */
        $dialog = $this->getHelperSet()->get('dialog');
        /*
         * Loading registry
         */
        $output->writeln("Loading registry ...");
        if (!file_exists(__DIR__ . '/../Resources/objects/registry.json')) {
            throw new \RuntimeException('The registry can not be loaded. Please run "etu:uv:import url" to create it.');
        }
        /** @var UV[] $registry */
        $registry = unserialize(file_get_contents(__DIR__ . '/../Resources/objects/registry.json'));
        if (!$registry || !is_array($registry)) {
            throw new \RuntimeException('The registry can not be loaded as its file is corrupted. Please run "etu:uv:import url" to recreate it.');
        }
        $regitryCodes = array();
        foreach ($registry as $key => $registryUV) {
            unset($registry[$key]);
            $registry[$registryUV->getCode()] = $registryUV;
            $regitryCodes[] = $registryUV->getCode();
        }
        /*
         * Loading database
         */
        $output->writeln("Loading database ...");
        /** @var UV[] $database */
        $database = $em->getRepository('EtuModuleUVBundle:UV')->findBy(array('isOld' => false));
        $databaseCodes = array();
        foreach ($database as $key => $databaseUV) {
            unset($database[$key]);
            $database[$databaseUV->getCode()] = $databaseUV;
            $databaseCodes[] = $databaseUV->getCode();
        }
        /*
         * Finding differences
         */
        $output->writeln("\nFinding differences ...");
        $output->writeln('----------------------------------------');
        $toAdd = array_diff($regitryCodes, $databaseCodes);
        $toRemove = array_diff($databaseCodes, $regitryCodes);
        $toUpdate = array();
        $codes = array_intersect($databaseCodes, $regitryCodes);
        foreach ($codes as $code) {
            if (!$this->areEquals($registry[$code], $database[$code])) {
                $toUpdate[] = $code;
            }
        }
        $toAddCount = count($toAdd);
        $toRemoveCount = count($toRemove);
        $toUpdateCount = count($toUpdate);
        $output->writeln(sprintf('%s UV to add', $toAddCount));
        $output->writeln(sprintf('%s UV to update', $toUpdateCount));
        $output->writeln(sprintf('%s UV to set as not existent anymore', $toRemoveCount));
        $output->write("\n");
        if ($toAddCount + $toRemoveCount + $toUpdateCount == 0) {
            $output->writeln("Nothing to sync.\n");
            return;
        }
        $startNow = $dialog->ask($output, 'Start the synchronization now (y/n) [y]? ', 'y') == 'y';
        if (!$startNow) {
            $output->writeln("Aborted.\n");
            return;
        }
        // Add
        if ($toAddCount > 0) {
            $output->writeln("Adding ...");
            $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, $toAddCount);
            $bar->update(0);
            $i = 1;
            foreach ($toAdd as $code) {
                $entity = $registry[$code];
                $em->persist($entity);
                $bar->update($i);
                $i++;
                if ($i % 10 == 0) {
                    $em->flush();
                }
            }
            $em->flush();
            $output->writeln("\n");
        }
        // Update
        if ($toUpdateCount > 0) {
            $output->writeln("Updating ...");
            $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, $toUpdateCount);
            $bar->update(0);
            $i = 1;
            foreach ($toUpdate as $code) {
                $regEntity = $registry[$code];
                $entity = $database[$code];
                $entity->setCategory($regEntity->getCategory())->setName($regEntity->getName())->setCm($regEntity->getCm())->setTd($regEntity->getTd())->setTp($regEntity->getTp())->setThe($regEntity->getThe())->setAutomne($regEntity->getAutomne())->setPrintemps($regEntity->getPrintemps())->setCredits($regEntity->getCredits())->setObjectifs($regEntity->getObjectifs())->setProgramme($regEntity->getProgramme());
                $em->persist($entity);
                if ($i % 10 == 0) {
                    $em->flush();
                }
                $bar->update($i);
                $i++;
            }
            $em->flush();
            $output->writeln("\n");
        }
        // Remove (set as old)
        if ($toRemoveCount > 0) {
            $output->writeln("Setting as old ...");
            $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, $toRemoveCount);
            $bar->update(0);
            $i = 1;
            foreach ($toRemove as $code) {
                $entity = $database[$code];
                $entity->setIdOld(true);
                $em->persist($entity);
                if ($i % 10 == 0) {
                    $em->flush();
                }
                $bar->update($i);
                $i++;
            }
            $em->flush();
            $output->writeln("\n");
        }
        $output->writeln("Done.\n");
    }
Пример #2
0
    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return void
     * @throws \RuntimeException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $dialog = $this->getHelperSet()->get('dialog');
        $output->writeln('
	Welcome to the EtuUTT users manager

This command helps you to synchronise database with LDAP.

For each user that don\'t exit anymore in the LDAP, the command will
ask you to keep or delete him/her.
');
        $container = $this->getContainer();
        // Users
        $output->writeln('Finding users differences ...');
        /** @var $synchronizer Synchronizer */
        $synchronizer = $container->get('etu.user.sync');
        $output->writeln('----------------------------------------');
        /** @var $usersImportIterator ImportIterator */
        $usersImportIterator = $synchronizer->createUsersSyncProcess()->getImportIterator();
        /** @var $usersRemoveIterator RemoveIterator */
        $usersRemoveIterator = $synchronizer->createUsersSyncProcess()->getRemoveIterator();
        /** @var $usersUpdateIterator UpdateIterator */
        $usersUpdateIterator = $synchronizer->createUsersSyncProcess()->getUpdateIterator();
        $output->writeln(sprintf('%s user(s) to import from LDAP', $usersImportIterator->count()));
        $output->writeln(sprintf('%s user(s) to remove/keep in database', $usersRemoveIterator->count()));
        $output->writeln(sprintf('%s user(s) to compare with the LDAP', $usersUpdateIterator->count()));
        $output->write("\n");
        $startNow = $dialog->ask($output, 'Start the synchronization now (y/n) [y]? ', 'y') == 'y';
        if (!$startNow) {
            $output->writeln("Aborted.\n");
            return;
        }
        // Import users
        if ($usersImportIterator->count() > 0) {
            $output->write("\n");
            $output->writeln('Importing users ...');
            /** @var $em EntityManager */
            $em = $container->get('doctrine')->getManager();
            $bde = $em->createQueryBuilder()->select('o')->from('EtuUserBundle:Organization', 'o')->where('o.login = :login')->setParameter('login', 'bde')->setMaxResults(1)->getQuery()->getOneOrNullResult();
            $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, $usersImportIterator->count());
            $bar->update(0);
            $i = 1;
            /** @var $user ElementToImport */
            foreach ($usersImportIterator as $user) {
                $user->import(false, $bde);
                $bar->update($i);
                $i++;
            }
            $output->write("\n");
            $output->writeln('Saving in database ...');
            $container->get('doctrine')->getManager()->flush();
        }
        // Updating users
        if ($usersUpdateIterator->count() > 0) {
            $output->write("\n");
            $output->writeln('Comparing users ...');
            $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, $usersUpdateIterator->count());
            $bar->update(0);
            $i = 1;
            $countPersisted = 0;
            /** @var $user ElementToUpdate */
            foreach ($usersUpdateIterator as $user) {
                $persisted = $user->update();
                if ($persisted) {
                    $countPersisted++;
                }
                $bar->update($i);
                $i++;
            }
            $output->write("\n");
            $output->writeln('Saving in database ...');
            $output->write("\n");
            $output->writeln($countPersisted . ' user(s) updated');
            $container->get('doctrine')->getManager()->flush();
        }
        // Remove users
        $output->write("\n\n");
        if ($usersRemoveIterator->count() > 0) {
            if ($usersRemoveIterator->count() == 1) {
                $item = $usersRemoveIterator->get(0);
                $output->writeln(sprintf('There is 1 user (`%s`) which is not in the LDAP but in the database.', $item->getElement()->getLogin()));
                $output->writeln("How do you want to deal with it?\n");
                $output->writeln("1 - Delete it");
                $output->writeln("2 - Keep it\n");
                $choice = $dialog->ask($output, 'What do you choose [1]? ', '1');
                if ($choice == 2) {
                    $password = $container->get('etu.user.crypting')->encrypt(substr($item->getElement()->getSalt(), 0, 6));
                    $item->keep($password);
                    $output->writeln("\n1 user kept");
                } else {
                    $item->remove();
                    $output->writeln("\n1 user removed");
                }
            } else {
                $logins = array();
                /** @var $item ElementToRemove */
                foreach ($usersRemoveIterator as $item) {
                    $logins[] = $item->getElement()->getLogin();
                }
                if ($usersRemoveIterator->count() <= 20) {
                    $output->writeln(sprintf('There are %s users which are not in the LDAP but in the database (`%s`).', $usersRemoveIterator->count(), implode('`, `', $logins)));
                } else {
                    $output->writeln(sprintf('There are %s users which are not in the LDAP but in the database.', $usersRemoveIterator->count()));
                }
                $output->writeln("How do you want to deal with them?\n");
                $choice = 0;
                while (!in_array($choice, array(1, 2, 3))) {
                    $output->writeln("1 - Delete all of them");
                    $output->writeln("2 - Ask me for some to keep, delete the rest");
                    $output->writeln("3 - Keep all of them");
                    $output->writeln("4 - Display the list\n");
                    $choice = $dialog->ask($output, 'What do you choose [2]? ', '2');
                    if ($choice == 4) {
                        $names = array();
                        foreach ($usersRemoveIterator as $user) {
                            $names[] = $user->getElement()->getFullName() . ' (' . $user->getElement()->getLogin() . ')';
                        }
                        $output->writeln(implode("\n", $names) . "\n");
                    }
                }
                $remove = array();
                $keep = array();
                if ($choice == 1) {
                    $remove = $usersRemoveIterator->all();
                } elseif ($choice == 2) {
                    $remove = $usersRemoveIterator->all();
                    $output->writeln("Keep blank to finish the list\n");
                    $loginToKeep = null;
                    while (1) {
                        $loginToKeep = $dialog->ask($output, 'Login to keep: ');
                        if (empty($loginToKeep)) {
                            break;
                        }
                        if (($key = array_search($loginToKeep, $logins)) !== false) {
                            $keep[] = $usersRemoveIterator->get($key);
                            unset($remove[$key]);
                        } else {
                            $output->writeln("The login can not be found in the list. Please retry.\n");
                        }
                    }
                } else {
                    $keep = $usersRemoveIterator->all();
                }
                // Keep
                foreach ($keep as $item) {
                    $password = $container->get('etu.user.crypting')->encrypt(substr($item->getElement()->getSalt(), 0, 6));
                    $item->keep($password);
                }
                $container->get('doctrine')->getManager()->flush();
                // Remove
                foreach ($remove as $item) {
                    $item->remove();
                }
                $container->get('doctrine')->getManager()->flush();
                $output->writeln(sprintf("\n%s user(s) kept, %s user(s) removed", count($keep), count($remove)));
            }
        }
        $output->writeln("Done.\n");
    }
Пример #3
0
    /**
     * @param \Symfony\Component\Console\Input\InputInterface $input
     * @param \Symfony\Component\Console\Output\OutputInterface $output
     * @return void
     * @throws \RuntimeException
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('
	Welcome to the EtuUTT schedules manager

This command helps you to synchronise database\'s with officials schedules.
');
        $output->writeln("\nGetting officials schedules ...");
        $output->writeln("------------------------------------------------------------");
        $tempDirectory = __DIR__ . '/../Resources/temp';
        if (!file_exists($tempDirectory . '/schedules')) {
            mkdir($tempDirectory . '/schedules');
        }
        $scheduleApi = new ScheduleApi();
        $output->writeln('Requesting CRI API (' . CriBrowser::ROOT_URL . ') ...');
        $pageContent = $scheduleApi->findPage(1);
        $content = $pageContent['courses'];
        $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, $pageContent['paging']->totalPages);
        $bar->update(1);
        for ($page = 2; true; $page++) {
            $pageContent = $scheduleApi->findPage($page);
            $courses = $pageContent['courses'];
            if (empty($courses)) {
                break;
            }
            /** @var $content Course[] */
            $content = array_merge($content, $courses);
            $bar->update($page);
        }
        $output->writeln('Loading users from database ...');
        /** @var $em EntityManager */
        $em = $this->getContainer()->get('doctrine')->getManager();
        /** @var $users User[] */
        $users = $em->getRepository('EtuUserBundle:User')->findAll();
        foreach ($users as $key => $user) {
            unset($users[$key]);
            $users[$user->getStudentId()] = $user;
        }
        $output->writeln('Creating schedules ...');
        $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, count($content));
        $bar->update(0);
        $i = 1;
        foreach ($content as $criCourse) {
            if (!isset($users[$criCourse->getStudentId()])) {
                continue;
            }
            $course = new \Etu\Core\UserBundle\Entity\Course();
            $course->setUser($users[$criCourse->getStudentId()]);
            $course->setDay(str_replace('day_', '', $criCourse->getDay()));
            $course->setStart($criCourse->getStart());
            $course->setEnd($criCourse->getEnd());
            $course->setUv($criCourse->getUv());
            $course->setType($criCourse->getType());
            $course->setWeek($criCourse->getWeek());
            if ($criCourse->getRoom()) {
                $course->setRoom($criCourse->getRoom());
            }
            $em->persist($course);
            $bar->update($i);
            $i++;
        }
        $bar->update(count($content));
        $output->writeln('Deleteing old schedules ...');
        $em->createQuery('DELETE FROM EtuUserBundle:Course')->execute();
        $output->writeln('Inserting new schedules ...');
        $em->flush();
        $output->writeln("\nDone.\n");
    }
Пример #4
0
 /**
  * @param \Symfony\Component\Console\Input\InputInterface $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  * @return void
  * @throws \RuntimeException
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln("\nConnecting to database ...");
     $output->writeln('----------------------------------------');
     $dialog = $this->getHelperSet()->get('dialog');
     $host = $dialog->ask($output, 'Host: ');
     $name = $dialog->ask($output, 'Name: ');
     $user = $dialog->ask($output, 'User: '******'Pass: '******'mysql:host=' . $host . ';dbname=' . $name, $user, $pass);
     $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     $output->writeln("\nFinding users differences ...");
     $output->writeln('----------------------------------------');
     /** @var EntityManager $em */
     $em = $this->getContainer()->get('doctrine')->getManager();
     /*
      * Imported
      */
     $imported = $pdo->query('SELECT * FROM admis')->fetchAll(\PDO::FETCH_OBJ);
     $importedLogins = [];
     $importedRegistry = [];
     foreach ($imported as $import) {
         $importedRegistry[$import->login] = $import;
         $importedLogins[] = $import->login;
     }
     /*
      * Database
      */
     $qb = $em->createQueryBuilder();
     $dbUsers = $qb->select('u.login')->from('EtuUserBundle:User', 'u')->where($qb->expr()->in('u.login', $importedLogins))->getQuery()->getArrayResult();
     $dbLogins = [];
     foreach ($dbUsers as $dbUser) {
         $dbLogins[] = $dbUser['login'];
     }
     $toImport = array_diff($importedLogins, $dbLogins);
     $output->writeln(sprintf('%s users to import', count($toImport)));
     $output->writeln("\nImporting users ...");
     if (count($toImport) > 0) {
         $bar = new ProgressBar('%fraction% [%bar%] %percent%', '=>', ' ', 80, count($toImport));
         $bar->update(0);
         $i = 1;
         foreach ($toImport as $loginToImport) {
             $import = $importedRegistry[$loginToImport];
             $user = new User();
             $user->setLogin($import->login);
             $user->setPassword($this->getContainer()->get('etu.user.crypting')->encrypt($import->password));
             $user->setFullName($import->prenom . ' ' . $import->nom);
             $user->setSex($import->sexe == 'M' ? User::SEX_MALE : User::SEX_FEMALE);
             $user->setSexPrivacy(User::PRIVACY_PRIVATE);
             $user->setCity(ucfirst(strtolower($import->ville)));
             $user->setCityPrivacy(User::PRIVACY_PRIVATE);
             $user->setPostalCode($import->codePostal);
             $user->setPostalCodePrivacy(User::PRIVACY_PRIVATE);
             $user->setCountry(ucfirst(strtolower($import->pays)));
             $user->setCountryPrivacy(User::PRIVACY_PRIVATE);
             $user->setPersonnalMail($import->email);
             $user->setPersonnalMailPrivacy(User::PRIVACY_PRIVATE);
             $user->setBranch($import->branche);
             $user->setFiliere($import->specialite);
             $user->setNiveau(intval($import->niveau));
             $user->setFormation('Inconnue');
             $user->setLanguage('fr');
             $user->setKeepActive(false);
             $em->persist($user);
             $em->flush();
             $bar->update($i);
             $i++;
         }
     }
     $output->write("\nDone\n");
 }