Ejemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $conn = $app->getApplicationBox()->get_connection();
     $sql = 'SELECT date, login, ip, locked
             FROM badlog
             ORDER BY id ASC';
     $stmt = $conn->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $n = 1;
     foreach ($rs as $row) {
         $date = Datetime::createFromFormat('Y-m-d h:i:s', $row['date']);
         $failure = new AuthFailure();
         if ($date) {
             $failure->setCreated($date);
         }
         $failure->setIp($row['ip']);
         $failure->setLocked(!!$row['locked']);
         $failure->setUsername($row['login']);
         $app['orm.em']->persist($failure);
         if (0 === $n++ % 1000) {
             $app['orm.em']->flush();
             $app['orm.em']->clear();
         }
     }
     $app['orm.em']->flush();
     $app['orm.em']->clear();
     return true;
 }
Ejemplo n.º 2
0
 /**
  * Creates an account
  *
  * @param Application $app       The application
  * @param string      $id        The base for user login
  * @param string      $email     The email
  * @param array       $templates Some extra templates to apply with the ones of this creator
  *
  * @return User
  *
  * @throws RuntimeException         In case the AccountCreator is disabled
  * @throws InvalidArgumentException In case a user with the same email already exists
  */
 public function create(Application $app, $id, $email = null, array $templates = [])
 {
     if (!$this->enabled) {
         throw new RuntimeException('Account creator is disabled');
     }
     $login = $id;
     $n = 1;
     if (null !== $email && null !== $app['repo.users']->findByEmail($email)) {
         throw new InvalidArgumentException('Provided email already exist in account base.');
     }
     while (null !== $app['repo.users']->findByLogin($login)) {
         $login = $id . '#' . $n;
         $n++;
     }
     $user = $app['manipulator.user']->createUser($login, $this->random->generateString(128), $email);
     $base_ids = [];
     foreach ($this->appbox->get_databoxes() as $databox) {
         foreach ($databox->get_collections() as $collection) {
             $base_ids[] = $collection->get_base_id();
         }
     }
     foreach (array_merge($this->templates, $templates) as $template) {
         $app->getAclForUser($user)->apply_model($template, $base_ids);
     }
     return $user;
 }
Ejemplo n.º 3
0
 /**
  * {@inheritdoc}
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     if ($output->getVerbosity() >= OutputInterface::VERBOSITY_QUIET) {
         switch ($output->getVerbosity()) {
             default:
             case OutputInterface::VERBOSITY_NORMAL:
                 $level = Logger::WARNING;
                 break;
             case OutputInterface::VERBOSITY_VERBOSE:
                 $level = Logger::NOTICE;
                 break;
             case OutputInterface::VERBOSITY_VERY_VERBOSE:
                 $level = Logger::INFO;
                 break;
             case OutputInterface::VERBOSITY_DEBUG:
                 $level = Logger::DEBUG;
                 break;
         }
         $handler = new StreamHandler('php://stdout', $level);
         $this->container['monolog'] = $this->container->share($this->container->extend('monolog', function ($logger) use($handler) {
             $logger->pushHandler($handler);
             return $logger;
         }));
         $this->container['task-manager.logger'] = $this->container->share($this->container->extend('task-manager.logger', function ($logger) use($handler) {
             $logger->pushHandler($handler);
             return $logger;
         }));
     }
     return $this->doExecute($input, $output);
 }
Ejemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $sql = 'DELETE FROM Tasks';
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute();
     $stmt->closeCursor();
     $sql = 'SELECT task_id, active, crashed, name, class, settings FROM task2';
     $stmt = $appbox->get_connection()->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     foreach ($rs as $row) {
         try {
             $job = $this->createJob($app, $row['class']);
         } catch (\RuntimeException $e) {
             continue;
         }
         $settings = simplexml_load_string($row['settings']);
         $period = $job->getEditor()->getDefaultPeriod();
         if ($settings->period) {
             $period = (int) $settings->period;
             unset($settings->period);
             $row['settings'] = $settings->asXML();
         }
         $task = new Task();
         $task->setCrashed($row['crashed'])->setJobId($job->getJobId())->setName($row['name'])->setPeriod($period)->setSettings($row['settings'])->setStatus($row['active'] ? Task::STATUS_STARTED : Task::STATUS_STOPPED);
         $app['orm.em']->persist($task);
     }
     $app['orm.em']->flush();
 }
Ejemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $sql = 'DELETE FROM UserNotificationSettings';
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute();
     $stmt->closeCursor();
     $conn = $app->getApplicationBox()->get_connection();
     $sql = 'SELECT * FROM usr_settings
             WHERE prop LIKE "notification_%"';
     $stmt = $conn->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $n = 0;
     $em = $app['orm.em'];
     foreach ($rs as $row) {
         if (null === ($user = $this->loadUser($app['orm.em'], $row['usr_id']))) {
             continue;
         }
         $userSetting = new UserNotificationSetting();
         $userSetting->setName($row['prop']);
         $userSetting->setValue($row['value']);
         $userSetting->setUser($user);
         $em->persist($userSetting);
         $n++;
         if ($n % 200 === 0) {
             $em->flush();
             $em->clear();
         }
     }
     $em->flush();
     $em->clear();
     return true;
 }
Ejemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $sql = 'DELETE FROM UserQueries';
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute();
     $stmt->closeCursor();
     $conn = $app->getApplicationBox()->get_connection();
     $sql = 'SELECT * FROM dsel';
     $stmt = $conn->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $n = 0;
     $em = $app['orm.em'];
     foreach ($rs as $row) {
         if (null === ($user = $this->loadUser($app['orm.em'], $row['usr_id']))) {
             continue;
         }
         $userQuery = new UserQuery();
         $userQuery->setQuery($row['query']);
         $userQuery->setUser($user);
         $em->persist($userQuery);
         $n++;
         if ($n % 1000 === 0) {
             $em->flush();
             $em->clear();
         }
     }
     $em->flush();
     $em->clear();
     return true;
 }
Ejemplo n.º 7
0
 private static function getUnvalidated(Application $app, $home = false)
 {
     $terms = [];
     foreach ($app->getDataboxes() as $databox) {
         try {
             $cgus = $databox->get_cgus();
             if (!isset($cgus[$app['locale']])) {
                 throw new Exception('No CGus for this locale');
             }
             $name = $databox->get_label($app['locale']);
             $update = $cgus[$app['locale']]['updated_on'];
             $value = $cgus[$app['locale']]['value'];
             $userValidation = true;
             if (!$home) {
                 if (!$app->getAclForUser($app->getAuthenticatedUser())->has_access_to_sbas($databox->get_sbas_id())) {
                     continue;
                 }
                 $userValidation = $app['settings']->getUserSetting($app->getAuthenticatedUser(), 'terms_of_use_' . $databox->get_sbas_id()) !== $update && trim($value) !== '';
             }
             if ($userValidation) {
                 $terms[$name] = ['sbas_id' => $databox->get_sbas_id(), 'terms' => $value, 'date' => $update];
             }
         } catch (\Exception $e) {
         }
     }
     return $terms;
 }
Ejemplo n.º 8
0
 /**
  * @covers Alchemy\Phrasea\Setup\Installer
  */
 public function testInstall()
 {
     $app = new Application('test');
     $app->bindRoutes();
     $parser = new Parser();
     $connDatas = $parser->parse(file_get_contents(__DIR__ . '/../../../../../config/configuration.yml'));
     $credentials = $connDatas['main']['database'];
     $config = __DIR__ . '/configuration.yml';
     $compiled = __DIR__ . '/configuration.yml.php';
     @unlink($config);
     @unlink($compiled);
     $app['configuration.store'] = new Configuration(new Yaml(), new Compiler(), $config, $compiled, true);
     $abConn = self::$DI['app']['dbal.provider']->get(['host' => 'localhost', 'port' => 3306, 'user' => $credentials['user'], 'password' => $credentials['password'], 'dbname' => 'ab_unitTests']);
     $abConn->connect();
     $dbConn = self::$DI['app']['dbal.provider']->get(['host' => 'localhost', 'port' => 3306, 'user' => $credentials['user'], 'password' => $credentials['password'], 'dbname' => 'db_unitTests']);
     $dbConn->connect();
     $template = 'en';
     $dataPath = __DIR__ . '/../../../../../datas/';
     $installer = new Installer($app);
     $installer->install(uniqid('admin') . '@example.com', 'sdfsdsd', $abConn, 'http://local.phrasea.test.installer/', $dataPath, $dbConn, $template);
     $this->assertTrue($app['configuration.store']->isSetup());
     $this->assertTrue($app['phraseanet.configuration-tester']->isUpToDate());
     $databoxes = $app['phraseanet.appbox']->get_databoxes();
     $databox = array_pop($databoxes);
     $this->assertContains('<path>' . realpath($dataPath) . '/db_unitTests/subdefs</path>', $databox->get_structure());
     $conf = $app['configuration.store']->getConfig();
     $this->assertArrayHasKey('main', $conf);
     $this->assertArrayHasKey('key', $conf['main']);
     $this->assertGreaterThan(10, strlen($conf['main']['key']));
     @unlink($config);
     @unlink($compiled);
 }
Ejemplo n.º 9
0
 /**
  * Creates an aggregate from all the feeds available to a given user.
  *
  * @param Application $app
  * @param User        $user
  *
  * @param array       $restrictions
  * @return Aggregate
  */
 public static function createFromUser(Application $app, User $user, array $restrictions = [])
 {
     /** @var FeedRepository $feedRepository */
     $feedRepository = $app['repo.feeds'];
     $feeds = $feedRepository->filterUserAccessibleByIds($app->getAclForUser($user), $restrictions);
     $token = $app['repo.aggregate-tokens']->findOneBy(['user' => $user]);
     return new static($app['orm.em'], $feeds, $token);
 }
Ejemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 public function post(Application $app, Request $request)
 {
     $configuration = $this->getConfiguration();
     $configuration['host'] = $request->request->get('host');
     $configuration['port'] = $request->request->get('port');
     $this->saveConfiguration($configuration);
     return $app->redirectPath('admin_searchengine_get');
 }
Ejemplo n.º 11
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $app['conf']->remove(['main', 'api-timers']);
     if ($this->tableHasField($app['orm.em'], 'api_logs', 'api_log_ressource')) {
         $sql = "ALTER TABLE api_logs CHANGE api_log_ressource api_log_resource varchar(64)";
         $app->getApplicationBox()->get_connection()->executeUpdate($sql);
     }
     return true;
 }
Ejemplo n.º 12
0
 public function __construct(Application $app, module_report $report)
 {
     $this->conn = $app->getApplicationBox()->get_connection();
     $this->connbas = $app->findDataboxById($report->getSbasId())->get_connection();
     $this->filter = new module_report_sqlfilter($app, $report);
     $this->sql = '';
     $this->params = [];
     $this->total_row = 0;
     $this->enable_limit = $report->getEnableLimit();
 }
Ejemplo n.º 13
0
 public function __construct(Application $app, module_report $report)
 {
     $this->app = $app;
     $this->conn = $app->findDataboxById($report->getSbasId())->get_connection();
     if (is_array($report->getTransQueryString())) {
         $this->cor_query = $report->getTransQueryString();
     }
     $this->buildFilter($report);
     $this->report = $report;
 }
Ejemplo n.º 14
0
 protected function setUp()
 {
     $this->appbox = $this->getMockBuilder(\appbox::class)->disableOriginalConstructor()->getMock();
     $this->twig = $this->getMockBuilder(\Twig_Environment::class)->disableOriginalConstructor()->getMock();
     $this->aclProvider = $this->getMockBuilder(ACLProvider::class)->disableOriginalConstructor()->getMock();
     $this->authenticator = $this->getMockBuilder(Authenticator::class)->disableOriginalConstructor()->getMock();
     $this->app = $this->getMockBuilder(Application::class)->disableOriginalConstructor()->getMock();
     $this->app->expects($this->any())->method('offsetGet')->willReturnMap([['phraseanet.appbox', $this->appbox], ['twig', $this->twig], ['authentication', $this->authenticator], ['acl', $this->aclProvider]]);
     $this->sut = new Controller($this->app);
 }
Ejemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $sql = 'DELETE FROM FtpExports';
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute();
     $stmt->closeCursor();
     $sql = 'DELETE FROM FtpExportElements';
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute();
     $stmt->closeCursor();
     $conn = $app->getApplicationBox()->get_connection();
     $em = $app['orm.em'];
     $em->getEventManager()->removeEventSubscriber(new TimestampableListener());
     $sql = 'SELECT `id`, `crash`, `nbretry`, `mail`, `addr`, `ssl`,
                 `login`, `pwd`, `passif`,
                 `destfolder`, `sendermail`, `text_mail_sender`,
                 `text_mail_receiver`, `usr_id`, `date`, `foldertocreate`,
                 `logfile`
             FROM ftp_export';
     $stmt = $conn->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $sql = 'SELECT base_id, record_id, subdef, filename, folder, error, done, businessfields
             FROM ftp_export_elements
             WHERE ftp_export_id = :export_id';
     $stmt = $conn->prepare($sql);
     $n = 0;
     foreach ($rs as $row) {
         if (null === ($user = $this->loadUser($app['orm.em'], $row['usr_id']))) {
             continue;
         }
         $export = new FtpExport();
         $export->setAddr($row['addr'])->setCrash($row['crash'])->setNbretry($row['nbretry'])->setMail($row['mail'])->setSsl($row['ssl'])->setLogin($row['login'])->setPwd($row['pwd'])->setPassif($row['passif'])->setDestfolder($row['destfolder'])->setSendermail($row['sendermail'])->setTextMailReceiver($row['text_mail_sender'])->setTextMailSender($row['text_mail_reveiver'])->setUser($user)->setCreated(new \DateTime($row['date']))->setUpdated(new \DateTime($row['date']))->setFoldertocreate($row['foldertocreate'])->setLogfile($row['logfile']);
         $em->persist($export);
         $stmt->execute(['export_id' => $row['id']]);
         $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         foreach ($rs as $element) {
             $element = new FtpExportElement();
             $element->setBaseId($row['base_id'])->setRecordId($row['record_id'])->setBusinessfields($row['businessfields'])->setCreated(new \DateTime($row['date']))->setUpdated(new \DateTime($row['date']))->setDone(!!$row['done'])->setError(!!$row['error'])->setFilename($row['filename'])->setFolder($row['folder'])->setSubdef($row['subdef'])->setExport($export);
             $export->addElement($element);
             $em->persist($element);
         }
         $n++;
         if ($n % 200 === 0) {
             $em->flush();
             $em->clear();
         }
     }
     $stmt->closeCursor();
     $em->flush();
     $em->clear();
     $em->getEventManager()->addEventSubscriber(new TimestampableListener());
     return true;
 }
 private function request($accept)
 {
     $app = new Application(Application::ENV_TEST);
     $app['dispatcher']->addSubscriber(new ContentNegotiationSubscriber($app['negotiator'], $app['phraseanet.content-negotiation.priorities']));
     $app->get('/content/negociation', function () {
         return '';
     });
     $client = new Client($app);
     $client->request('GET', '/content/negociation', array(), array(), array('HTTP_Accept' => $accept));
     return $client->getResponse();
 }
 /**
  * @dataProvider provideExceptionsAndCode
  */
 public function testError($exception, $code)
 {
     $app = new Application('test');
     $app['dispatcher']->addSubscriber(new ApiExceptionHandlerSubscriber($app));
     $app->get('/', function () use($exception) {
         throw $exception;
     });
     $client = new Client($app);
     $client->request('GET', '/');
     $this->assertEquals($code, $client->getResponse()->getStatusCode());
 }
 private function request($accept)
 {
     $app = new Application('test');
     $app['dispatcher']->addSubscriber(new ContentNegotiationSubscriber($app));
     $app->get('/content/negociation', function () {
         return '';
     });
     $client = new Client($app);
     $client->request('GET', '/content/negociation', array(), array(), array('HTTP_Accept' => $accept));
     return $client->getResponse();
 }
Ejemplo n.º 19
0
 public function testNoHeaderNoRedirection()
 {
     $app = new Application();
     unset($app['exception_handler']);
     $app['dispatcher']->addSubscriber(new FirewallSubscriber());
     $app->get('/', function () {
         throw new HttpException(500);
     });
     $client = new Client($app);
     $this->setExpectedException('Symfony\\Component\\HttpKernel\\Exception\\HttpException');
     $client->request('GET', '/');
 }
Ejemplo n.º 20
0
 /**
  * {@inheritdoc}
  */
 public function post(Application $app, Request $request)
 {
     $configuration = $this->getConfiguration();
     $configuration['date_fields'] = [];
     foreach ($request->request->get('date_fields', []) as $field) {
         $configuration['date_fields'][] = $field;
     }
     $configuration['default_sort'] = $request->request->get('default_sort');
     $configuration['stemming_enabled'] = (int) (bool) $request->request->get('stemming_enabled');
     $this->saveConfiguration($configuration);
     return $app->redirectPath('admin_searchengine_get');
 }
Ejemplo n.º 21
0
 public function getGlobals(Application $app, Request $request)
 {
     $form = $app['registry.manipulator']->createForm($app['conf']);
     if ('POST' === $request->getMethod()) {
         $form->bind($request);
         if ($form->isValid()) {
             $app['conf']->set('registry', $app['registry.manipulator']->getRegistryData($form));
             return $app->redirectPath('setup_display_globals');
         }
     }
     return $app['twig']->render('admin/setup.html.twig', ['form' => $form->createView()]);
 }
Ejemplo n.º 22
0
 /**
  * @param array  $conf
  * @param string $method
  * @param array  $extraHeaders
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 private function request(array $conf, $method = 'GET', array $extraHeaders = [])
 {
     $app = new Application('test');
     $app['phraseanet.configuration']['api_cors'] = $conf;
     $app['dispatcher']->addSubscriber(new ApiCorsSubscriber($app));
     $app->get('/api/v1/test-route', function () {
         return '';
     });
     $client = new Client($app);
     $client->request($method, '/api/v1/test-route', [], [], array_merge($extraHeaders, ['HTTP_Origin' => $this->origin]));
     return $client->getResponse();
 }
 /**
  * @dataProvider provideExceptionsAndCode
  */
 public function testErrorOnOtherRoutes($exception, $code, $contentType)
 {
     $app = new Application('test');
     unset($app['exception_handler']);
     $app['dispatcher']->addSubscriber(new ApiOauth2ErrorsSubscriber(PhraseaExceptionHandler::register(), $this->createTranslatorMock()));
     $app->get('/', function () use($exception) {
         throw $exception;
     });
     $client = new Client($app);
     $this->setExpectedException(get_class($exception));
     $client->request('GET', '/');
 }
 public function testItCanBeDisabled()
 {
     $app = new Application();
     $app['exception_handler'] = new PhraseaExceptionHandlerSubscriber(PhraseaExceptionHandler::register());
     $app->get('/', function () {
         throw new \Exception();
     });
     $app['exception_handler']->disable();
     $client = new Client($app);
     $this->setExpectedException('\\Exception');
     $client->request('GET', '/');
 }
Ejemplo n.º 25
0
 protected function goBackTo35()
 {
     $app = new Application(Application::ENV_TEST);
     $conn = $app->getApplicationBox()->get_connection();
     $this->uninstall();
     file_put_contents(__DIR__ . '/../../../../../config/config.inc', "<?php\n\$servername = 'http://local.phrasea';\n");
     file_put_contents(__DIR__ . '/../../../../../config/connexion.inc', "<?php\n\n\$hostname = '" . $conn->getHost() . "';\n\$port = '" . $conn->getPort() . "';\n\$user = '******';\n\$password = '******';\n\$dbname = '" . $conn->getDatabase() . "';\n            ");
     $this->tearDownHandlers[] = function () {
         @unlink(__DIR__ . '/../../../../../config/config.inc');
         @unlink(__DIR__ . '/../../../../../config/connexion.inc');
     };
 }
Ejemplo n.º 26
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $sql = "SHOW TABLE STATUS LIKE 'cache'";
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute();
     $row = $stmt->fetch(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     if ($row['Auto_increment']) {
         $sql = sprintf('ALTER TABLE Sessions AUTO_INCREMENT = %d', $row['Auto_increment']);
         $app->getApplicationBox()->get_connection()->exec($sql);
     }
     return true;
 }
Ejemplo n.º 27
0
 /**
  * Returns l'objet stockee dans le cache si i l existe sinon instancie
  * un nouveau objet dashboard_feed
  *
  * @param Application $app
  * @param integer     $sbasid
  * @param string      $sbas_coll
  * @param mixed       $dmin
  * @param mixed       $dmax
  */
 public static function getInstance(Application $app, $sbasid, $sbas_coll, $dmin, $dmax)
 {
     $cache_id = 'feed_' . md5($sbasid . '_' . $sbas_coll . '_' . $dmin . '_' . $dmax);
     try {
         $result = $app->getApplicationBox()->get_data_from_cache($cache_id);
         $result->setApplication($app);
         return $result;
     } catch (\Exception $e) {
     }
     $tmp = new self($app, $sbasid, $sbas_coll, $dmin, $dmax);
     $app->getApplicationBox()->set_data_to_cache($tmp, $cache_id);
     return $tmp;
 }
Ejemplo n.º 28
0
 private function updateRegistry(Application $app)
 {
     $sql = 'SELECT `value` FROM registry WHERE `key` = :key';
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute([':key' => 'GV_default_lng']);
     $row = $stmt->fetch(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     $locale = null !== $row ? $row['value'] : 'fr';
     $sql = 'UPDATE registry SET `value` = :value WHERE `key` = :key';
     $stmt = $app->getApplicationBox()->get_connection()->prepare($sql);
     $stmt->execute([':key' => 'GV_default_lng', ':value' => $this->extractLocale($locale)]);
     $stmt->closeCursor();
 }
 public function testErrorOnOtherExceptions()
 {
     $app = new Application('test');
     $app['bridge.account'] = $this->getMockBuilder('Bridge_Account')->disableOriginalConstructor()->getMock();
     unset($app['exception_handler']);
     $app['dispatcher']->addSubscriber(new BridgeExceptionSubscriber($app));
     $app->get('/', function () {
         throw new \InvalidArgumentException();
     });
     $client = new Client($app);
     $this->setExpectedException('\\InvalidArgumentException');
     $client->request('GET', '/');
 }
Ejemplo n.º 30
0
 /**
  * {@inheritdoc}
  */
 public function apply(base $appbox, Application $app)
 {
     $conn = $appbox->get_connection();
     $sql = 'SELECT sbas_id, record_id, id FROM BasketElements';
     $stmt = $conn->prepare($sql);
     $stmt->execute();
     $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     foreach ($result as $row) {
         $sbas_id = (int) $row['sbas_id'];
         try {
             $connbas = $app->findDataboxById($sbas_id)->get_connection();
             $connbas->connect();
         } catch (\Exception $e) {
             $conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']);
             $conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']);
             continue;
         }
         $sql = 'SELECT record_id FROM record WHERE record_id = :record_id';
         $stmt = $connbas->prepare($sql);
         $stmt->execute([':record_id' => $row['record_id']]);
         $rowCount = $stmt->rowCount();
         $stmt->closeCursor();
         if ($rowCount == 0) {
             $conn->exec('DELETE FROM ValidationDatas WHERE basket_element_id = ' . $row['id']);
             $conn->exec('DELETE FROM BasketElements WHERE id = ' . $row['id']);
         }
     }
     $dql = "SELECT b FROM Phraseanet:Basket b WHERE b.description != ''";
     $n = 0;
     $perPage = 100;
     $query = $app['orm.em']->createQuery($dql)->setFirstResult($n)->setMaxResults($perPage);
     $paginator = new Paginator($query, true);
     $count = count($paginator);
     while ($n < $count) {
         $query = $app['orm.em']->createQuery($dql)->setFirstResult($n)->setMaxResults($perPage);
         $paginator = new Paginator($query, true);
         foreach ($paginator as $basket) {
             $htmlDesc = $basket->getDescription();
             $description = trim(strip_tags(str_replace("<br />", "\n", $htmlDesc)));
             if ($htmlDesc == $description) {
                 continue;
             }
             $basket->setDescription($description);
         }
         $n += $perPage;
         $app['orm.em']->flush();
     }
     $app['orm.em']->flush();
     return true;
 }