public function testGet_id()
 {
     $this->feed_datas();
     $log_id = $this->object->get_id();
     $this->assertTrue(is_int($log_id));
     $sql = 'SELECT id FROM log
         WHERE sit_session = :ses_id AND usrid = :usr_id AND site = :site';
     $params = [':ses_id' => self::$DI['app']['session']->get('session_id'), ':usr_id' => self::$DI['app']['authentication']->getUser()->getId(), ':site' => self::$DI['app']['conf']->get(['main', 'key'])];
     $stmt = $this->databox->get_connection()->prepare($sql);
     $stmt->execute($params);
     $this->assertEquals(1, $stmt->rowCount());
     $row = $stmt->fetch(PDO::FETCH_ASSOC);
     $this->assertEquals($this->object->get_id(), $row['id']);
     $log_id = $this->object->get_id();
     $ses_id = self::$DI['app']['session']->get('session_id');
     $usr_id = self::$DI['app']['authentication']->getUser()->getId();
     $this->logout(self::$DI['app']);
     $sql = 'SELECT id FROM log
         WHERE sit_session = :ses_id AND usrid = :usr_id AND site = :site';
     $params = [':ses_id' => $ses_id, ':usr_id' => $usr_id, ':site' => self::$DI['app']['conf']->get(['main', 'key'])];
     $stmt = $this->databox->get_connection()->prepare($sql);
     $stmt->execute($params);
     $this->assertEquals(1, $stmt->rowCount());
     $row = $stmt->fetch(PDO::FETCH_ASSOC);
     $this->assertEquals($log_id, $row['id']);
 }
 /**
  * Returns true if a databox is available given a configuration.
  *
  * @param \databox $databox
  *
  * @return Boolean
  */
 public function isDataboxAvailable(\databox $databox)
 {
     if (!$this->isRestricted()) {
         return true;
     }
     return in_array($databox->get_sbas_id(), $this->cache->fetch('available_databoxes'), true);
 }
Exemple #3
0
 public function getBitPositionInDatabox(\databox $databox)
 {
     foreach ($databox->getStatusStructure() as $bit => $status) {
         $candidate_name = self::normalizeName($status['labelon']);
         if ($candidate_name === $this->name) {
             return (int) $status['bit'];
         }
     }
 }
 public function getStructure(\databox $databox)
 {
     if (false !== ($status = $this->cache->fetch($this->get_cache_key($databox->get_sbas_id())))) {
         return new StatusStructure($databox, new ArrayCollection(json_decode($status, true)));
     }
     $structure = $this->provider->getStructure($databox);
     $this->cache->save($this->get_cache_key($databox->get_sbas_id()), json_encode($structure->toArray()));
     return $structure;
 }
 /**
  * Get the status structure according to the given databox
  *
  * @param \databox $databox
  *
  * @return StatusStructure
  */
 public function getStructure(\databox $databox)
 {
     $databox_id = $databox->get_sbas_id();
     if (isset($this->statusStructure[$databox_id])) {
         return $this->statusStructure[$databox_id];
     }
     $this->statusStructure[$databox_id] = $this->provider->getStructure($databox);
     return $this->statusStructure[$databox_id];
 }
 /**
  * Resets admin rights on a databox.
  *
  * @param \ACL     $acl
  * @param \databox $databox
  */
 private function doResetAdminRightsOnDatabox(\ACL $acl, \databox $databox)
 {
     $collections = $databox->get_collections();
     $acl->update_rights_to_sbas($databox->get_sbas_id(), ['bas_manage' => '1', 'bas_modify_struct' => '1', 'bas_modif_th' => '1', 'bas_chupub' => '1']);
     $acl->give_access_to_base(array_map(function (\collection $collection) {
         return $collection->get_base_id();
     }, $collections));
     foreach ($collections as $collection) {
         $this->doResetRightsOnCollection($acl, $collection);
     }
 }
 public function log(\databox $databox, $query, $answers, array $coll_ids)
 {
     $conn = $databox->get_connection();
     $sql = "INSERT INTO log_search\n           (id, log_id, date, search, results, coll_id )\n           VALUES\n           (null, :log_id, :date, :query, :nbresults, :colls)";
     $stmt = $conn->prepare($sql);
     $stmt->execute([':log_id' => $this->app['phraseanet.logger']($databox)->get_id(), ':date' => date("Y-m-d H:i:s"), ':query' => $query, ':nbresults' => $answers, ':colls' => implode(',', array_map(function ($coll_id) {
         return (int) $coll_id;
     }, $coll_ids))]);
     $stmt->closeCursor();
     return $this;
 }
 public function findElementsByDatabox(\databox $databox)
 {
     $dql = 'SELECT e
         FROM Phraseanet:BasketElement e
         JOIN e.basket b
         LEFT JOIN b.validation s
         LEFT JOIN s.participants p
         WHERE e.sbas_id = :sbas_id';
     $params = ['sbas_id' => $databox->get_sbas_id()];
     $query = $this->_em->createQuery($dql);
     $query->setParameters($params);
     return $query->getResult();
 }
Exemple #9
0
 public function tearDown()
 {
     if ($this->object_mono instanceof databox_field) {
         $this->object_mono->delete();
     }
     if ($this->object_multi instanceof databox_field) {
         $this->object_multi->delete();
     }
     $extra = $this->databox->get_meta_structure()->get_element_by_name('Bonoboyoyo');
     if ($extra instanceof databox_field) {
         $extra->delete();
     }
     parent::tearDown();
 }
 private function generateSubdefPathname(\record_adapter $record, \databox_subdef $subdef, $oldVersion = null)
 {
     if ($oldVersion) {
         $pathdest = \p4string::addEndSlash(pathinfo($oldVersion, PATHINFO_DIRNAME));
     } else {
         $pathdest = \databox::dispatch($this->filesystem, $subdef->get_path());
     }
     return $pathdest . $record->get_record_id() . '_' . $subdef->get_name() . '.' . $this->getExtensionFromSpec($subdef->getSpecs());
 }
 /**
  * @param array                $row
  * @param \record_adapter|null $record
  * @return \record_adapter
  */
 private function mapRecordFromResultRow(array $row, \record_adapter $record = null)
 {
     if (null === $record) {
         $record = new \record_adapter($this->app, $this->databox->get_sbas_id(), $row['record_id'], null, false);
     }
     $record->mapFromData($row);
     $record->putInCache();
     return $record;
 }
 public function getStructure(\databox $databox)
 {
     $statusStructure = new StatusStructure($databox);
     $xmlPref = $databox->get_structure();
     $sxe = simplexml_load_string($xmlPref);
     if ($sxe === false) {
         throw new \Exception('Failed to load database XML structure');
     }
     foreach ($sxe->statbits->bit as $sb) {
         $bit = (int) $sb['n'];
         if ($bit < 4 && $bit > 31) {
             continue;
         }
         $status = [];
         $status['bit'] = $bit;
         $status['labeloff'] = (string) $sb['labelOff'];
         $status['labelon'] = (string) $sb['labelOn'];
         foreach ($this->locales as $code => $language) {
             $status['labels_on'][$code] = null;
             $status['labels_off'][$code] = null;
         }
         foreach ($sb->label as $label) {
             $status['labels_' . $label['switch']][(string) $label['code']] = (string) $label;
         }
         foreach ($this->locales as $code => $language) {
             $status['labels_on_i18n'][$code] = '' !== trim($status['labels_on'][$code]) ? $status['labels_on'][$code] : $status['labelon'];
             $status['labels_off_i18n'][$code] = '' !== trim($status['labels_off'][$code]) ? $status['labels_off'][$code] : $status['labeloff'];
         }
         $status['img_off'] = null;
         $status['img_on'] = null;
         if (is_file($statusStructure->getPath() . '-stat_' . $bit . '_0.gif')) {
             $status['img_off'] = $statusStructure->getUrl() . '-stat_' . $bit . '_0.gif?etag=' . md5_file($statusStructure->getPath() . '-stat_' . $bit . '_0.gif');
             $status['path_off'] = $statusStructure->getPath() . '-stat_' . $bit . '_0.gif';
         }
         if (is_file($statusStructure->getPath() . '-stat_' . $bit . '_1.gif')) {
             $status['img_on'] = $statusStructure->getUrl() . '-stat_' . $bit . '_1.gif?etag=' . md5_file($statusStructure->getPath() . '-stat_' . $bit . '_1.gif');
             $status['path_on'] = $statusStructure->getPath() . '-stat_' . $bit . '_1.gif';
         }
         $status['searchable'] = isset($sb['searchable']) ? (int) $sb['searchable'] : 0;
         $status['printable'] = isset($sb['printable']) ? (int) $sb['printable'] : 0;
         $statusStructure->setStatus($bit, $status);
     }
     return $statusStructure;
 }
 /**
  * @param \databox $databox
  * @param string   $token
  * @param int      $record_id
  * @param string   $subdef
  * @return \record_adapter
  */
 private function retrieveRecord(\databox $databox, $token, $record_id, $subdef)
 {
     try {
         $record = new \record_adapter($this->app, $databox->get_sbas_id(), $record_id);
         $subDefinition = new \media_subdef($this->app, $record, $subdef);
         $permalink = new \media_Permalink_Adapter($this->app, $databox, $subDefinition);
     } catch (\Exception $exception) {
         throw new NotFoundHttpException('Wrong token.', $exception);
     }
     if (!$permalink->get_is_activated()) {
         throw new NotFoundHttpException('This token has been disabled.');
     }
     /** @var FeedItemRepository $feedItemsRepository */
     $feedItemsRepository = $this->app['repo.feed-items'];
     if (in_array($subdef, [\databox_subdef::CLASS_PREVIEW, \databox_subdef::CLASS_THUMBNAIL]) && $feedItemsRepository->isRecordInPublicFeed($databox->get_sbas_id(), $record_id)) {
         return $record;
     } elseif ($permalink->get_token() == (string) $token) {
         return $record;
     }
     throw new NotFoundHttpException('Wrong token.');
 }
 private function createDB(Connection $dbConn = null, $template)
 {
     $template = new \SplFileInfo(__DIR__ . '/../../../conf.d/data_templates/' . $template . '-simple.xml');
     $databox = \databox::create($this->app, $dbConn, $template);
     $this->app['acl']->get($this->app['authentication']->getUser())->give_access_to_sbas([$databox->get_sbas_id()])->update_rights_to_sbas($databox->get_sbas_id(), ['bas_manage' => 1, 'bas_modify_struct' => 1, 'bas_modif_th' => 1, 'bas_chupub' => 1]);
     $collection = \collection::create($this->app, $databox, $this->app['phraseanet.appbox'], 'test', $this->app['authentication']->getUser());
     $this->app['acl']->get($this->app['authentication']->getUser())->give_access_to_base([$collection->get_base_id()]);
     $this->app['acl']->get($this->app['authentication']->getUser())->update_rights_to_base($collection->get_base_id(), ['canpush' => 1, 'cancmd' => 1, 'canputinalbum' => 1, 'candwnldhd' => 1, 'candwnldpreview' => 1, 'canadmin' => 1, 'actif' => 1, 'canreport' => 1, 'canaddrecord' => 1, 'canmodifrecord' => 1, 'candeleterecord' => 1, 'chgstatus' => 1, 'imgtools' => 1, 'manage' => 1, 'modify_struct' => 1, 'nowatermark' => 1]);
     foreach (['PhraseanetIndexer', 'Subdefs', 'WriteMetadata'] as $jobName) {
         $job = $this->app['task-manager.job-factory']->create($jobName);
         $this->app['manipulator.task']->create($job->getName(), $job->getJobId(), $job->getEditor()->getDefaultSettings($this->app['conf']), $job->getEditor()->getDefaultPeriod());
     }
 }
Exemple #15
0
 /**
  * Return a maximum of 100 recods without UUIDs
  *
  * @param  \databox $databox
  * @return array
  */
 protected function getNullUUIDs(\databox $databox)
 {
     $sql = 'SELECT r.coll_id, r.type, r.record_id, s.path, s.file, r.xml
             FROM record r, subdef s
                     WHERE ISNULL(uuid)
                     AND s.record_id = r.record_id AND s.name="document"
                     AND parent_record_id = 0 LIMIT 100';
     $stmt = $databox->get_connection()->prepare($sql);
     $stmt->execute();
     $rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     return $rs;
 }
 public function createDatabox()
 {
     $this->createDatabase();
     $connexion = self::$DI['app']['phraseanet.configuration']['main']['database'];
     try {
         $conn = self::$DI['app']['dbal.provider']->get(['host' => $connexion['host'], 'port' => $connexion['port'], 'user' => $connexion['user'], 'password' => $connexion['password'], 'dbname' => 'unit_test_db']);
         $conn->connect();
     } catch (DBALException $e) {
         $this->markTestSkipped('Could not reach DB');
     }
     $databox = \databox::create(self::$DI['app'], $conn, new \SplFileInfo(self::$DI['app']['root.path'] . '/lib/conf.d/data_templates/fr-simple.xml'));
     self::$createdDataboxes[] = $databox;
     $rights = ['bas_manage' => '1', 'bas_modify_struct' => '1', 'bas_modif_th' => '1', 'bas_chupub' => '1'];
     self::$DI['app']['acl']->get(self::$DI['app']['authentication']->getUser())->update_rights_to_sbas($databox->get_sbas_id(), $rights);
     $databox->registerAdmin(self::$DI['app']['authentication']->getUser());
     return $databox;
 }
 public function substitute(\record_adapter $record, $name, MediaInterface $media)
 {
     $newfilename = $record->get_record_id() . '_0_' . $name . '.' . $media->getFile()->getExtension();
     $subdef_def = false;
     if ($name == 'document') {
         $baseprefs = $record->get_databox()->get_sxml_structure();
         $pathhd = \p4string::addEndSlash((string) $baseprefs->path);
         $filehd = $record->get_record_id() . "_document." . strtolower($media->getFile()->getExtension());
         $pathhd = \databox::dispatch($this->fs, $pathhd);
         $this->fs->copy($media->getFile()->getRealPath(), $pathhd . $filehd, true);
         $subdefFile = $pathhd . $filehd;
         $meta_writable = true;
     } else {
         $type = $record->isStory() ? 'image' : $record->get_type();
         $subdef_def = $record->get_databox()->get_subdef_structure()->get_subdef($type, $name);
         if ($record->has_subdef($name) && $record->get_subdef($name)->is_physically_present()) {
             $path_file_dest = $record->get_subdef($name)->get_pathfile();
             $record->get_subdef($name)->remove_file();
             $record->clearSubdefCache($name);
         } else {
             $path = \databox::dispatch($this->fs, $subdef_def->get_path());
             $this->fs->mkdir($path, 0750);
             $path_file_dest = $path . $newfilename;
         }
         try {
             $this->alchemyst->turnInto($media->getFile()->getRealPath(), $path_file_dest, $subdef_def->getSpecs());
         } catch (MediaAlchemystException $e) {
             return;
         }
         $subdefFile = $path_file_dest;
         $meta_writable = $subdef_def->meta_writeable();
     }
     $this->fs->chmod($subdefFile, 0760);
     $media = $this->mediavorus->guess($subdefFile);
     \media_subdef::create($this->app, $record, $name, $media);
     $record->delete_data_from_cache(\record_adapter::CACHE_SUBDEFS);
     if ($meta_writable) {
         $record->write_metas();
     }
     if ($name == 'document') {
         $record->rebuild_subdefs();
     }
     $this->dispatcher->dispatch(RecordEvents::MEDIA_SUBSTITUTED, new RecordMediaSubstitutedEvent($record));
 }
Exemple #18
0
 public static function insertClient(Application $app, \databox $databox)
 {
     $connbas = $databox->get_connection();
     $sql = 'SELECT site_id FROM clients WHERE site_id = :site_id';
     $stmt = $connbas->prepare($sql);
     $stmt->execute([':site_id' => $app['conf']->get('servername')]);
     $rowCount = $stmt->rowCount();
     $stmt->closeCursor();
     if ($rowCount > 0) {
         return;
     }
     $sql = 'INSERT INTO clients (site_id) VALUES (:site_id)';
     $stmt = $connbas->prepare($sql);
     $stmt->execute([':site_id' => $app['conf']->get('servername')]);
     $stmt->closeCursor();
     return;
 }
 private function getNbRowLogs(\databox $databox)
 {
     $stmt = $databox->get_connection()->prepare('SELECT COUNT(l.id) as nb_log FROM log_docs l WHERE l.action = "download"');
     $stmt->execute();
     $row = $stmt->fetch();
     $stmt->closeCursor();
     unset($stmt);
     return $row['nb_log'];
 }
Exemple #20
0
 public function delete_injected_rights_sbas(databox $databox)
 {
     $sql = 'DELETE FROM collusr WHERE usr_id = :usr_id AND site = :site';
     $params = [':usr_id' => $this->user->getId(), ':site' => $this->app['conf']->get(['main', 'key'])];
     $stmt = $databox->get_connection()->prepare($sql);
     $stmt->execute($params);
     $stmt->closeCursor();
     return $this;
 }
 public function submitDatabaseStructureAction(Request $request, $databox_id)
 {
     if (!$this->getAclForUser()->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
         $this->app->abort(403);
     }
     if (null === ($structure = $request->request->get('structure'))) {
         $this->app->abort(400, $this->app->trans('Missing "structure" parameter'));
     }
     $errors = \databox::get_structure_errors($this->app['translator'], $structure);
     $domst = new \DOMDocument('1.0', 'UTF-8');
     $domst->preserveWhiteSpace = false;
     $domst->formatOutput = true;
     if (count($errors) == 0 && $domst->loadXML($structure)) {
         $databox = $this->findDataboxById($databox_id);
         $databox->saveStructure($domst);
         return $this->app->redirectPath('database_display_stucture', ['databox_id' => $databox_id, 'success' => 1]);
     }
     return $this->app->redirectPath('database_display_stucture', ['databox_id' => $databox_id, 'success' => 0, 'error' => 'struct']);
 }
Exemple #22
0
 public static function load(Application $app, databox $databox)
 {
     if (!$app['authentication']->isAuthenticated()) {
         throw new Exception_Session_LoggerNotFound('Not authenticated');
     }
     $sql = 'SELECT id FROM log
         WHERE site = :site AND sit_session = :ses_id';
     $params = [':site' => $app['conf']->get(['main', 'key']), ':ses_id' => $app['session']->get('session_id')];
     $stmt = $databox->get_connection()->prepare($sql);
     $stmt->execute($params);
     $row = $stmt->fetch(PDO::FETCH_ASSOC);
     $stmt->closeCursor();
     if (!$row) {
         throw new Exception_Session_LoggerNotFound('Logger not found');
     }
     return new self($databox, $row['id']);
 }
Exemple #23
0
 protected function doExecute(InputInterface $input, OutputInterface $output)
 {
     $interactive = !$input->getOption('yes');
     $dialog = $this->getHelperSet()->get('dialog');
     if (!$this->container['phraseanet.configuration']->isSetup()) {
         throw new RuntimeException(sprintf('Phraseanet is not setup. You can run <info>bin/setup system::install</info> command to install Phraseanet.'));
     }
     // get dbs
     $conf = $this->container['phraseanet.configuration']->getConfig();
     $dbs = array('ab' => $conf['main']['database']['dbname'], 'dbs' => array(), 'setup_dbs' => array());
     foreach ($this->container->getDataboxes() as $databox) {
         $dbs['dbs'][] = $databox;
     }
     if (count($dbs['dbs']) > 1) {
         if ($input->getOption('db-name')) {
             $dbName = $input->getOption('db-name');
         } else {
             $dialog = $this->getHelperSet()->get('dialog');
             $dbName = $dialog->ask($output, _('Please enter the databox name to reset or create'));
         }
     } else {
         if ($input->getOption('db-name')) {
             $dbName = $input->getOption('db-name');
         } else {
             $dbName = current($dbs['dbs'])->get_dbname();
         }
     }
     $continue = 'y';
     if (count($dbs['dbs']) > 1 && in_array($dbName, array_map(function ($db) {
         return $db->get_dbname();
     }, $dbs['dbs']))) {
         if ($interactive) {
             do {
                 $continue = mb_strtolower($dialog->ask($output, '<question>' . $dbName . ' database is going to be truncated, do you want to continue ? (Y/n)</question>', 'Y'));
             } while (!in_array($continue, array('y', 'n')));
         }
     }
     if ('y' !== $continue) {
         return;
     }
     $unmountedDbs = $dbToMount = array_diff(array_map(function ($db) {
         return $db->get_dbname();
     }, $dbs['dbs']), array($dbName));
     if (count($unmountedDbs) > 1 && $interactive) {
         array_unshift($unmountedDbs, 'all');
         $selected = $dialog->select($output, 'Choose Dbs to mount', $unmountedDbs, 0, false, 'Invalid choice', true);
         $dbToMount = array_map(function ($c) use($unmountedDbs) {
             return $unmountedDbs[$c];
         }, $selected);
     }
     if ($input->getOption('dependencies') || !SemVer::eq($this->container->getApplicationBox()->get_version(), $this->container['phraseanet.version']->getNumber())) {
         $this->getApplication()->find('dependencies:all')->run(new ArrayInput(array('command' => 'dependencies:all')), $output);
     }
     // get data paths
     $dataPath = $this->container['conf']->get(['main', 'storage', 'subdefs'], $this->container['root.path'] . '/datas');
     $schema = $this->container['orm.em']->getConnection()->getSchemaManager();
     $output->writeln('Creating database "' . $dbs['ab'] . '"...<info>OK</info>');
     $schema->dropAndCreateDatabase($dbs['ab']);
     $output->writeln('Creating database "' . $dbName . '"...<info>OK</info>');
     $schema->dropAndCreateDatabase($dbName);
     // inject v3.1 fixtures
     if ($input->getOption('run-patches')) {
         $content = file_get_contents($this->container['root.path'] . '/resources/hudson/connexion.inc');
         $content = str_replace('{{dbname}}', $conf['main']['database']['dbname'], $content);
         $content = str_replace('{{hostname}}', $conf['main']['database']['host'], $content);
         $content = str_replace('{{port}}', $conf['main']['database']['port'], $content);
         $content = str_replace('{{user}}', $conf['main']['database']['user'], $content);
         $content = str_replace('{{password}}', $conf['main']['database']['password'], $content);
         $tmpFile = tempnam(sys_get_temp_dir(), 'connexion.inc-v3.1-');
         $this->container['filesystem']->dumpFile($tmpFile, $content);
         $this->container['filesystem']->copy($tmpFile, $this->container['root.path'] . '/config/connexion.inc');
         $this->container['filesystem']->copy($this->container['root.path'] . '/resources/hudson/_GV.php', $this->container['root.path'] . '/config/_GV.php');
         $content = file_get_contents($this->container['root.path'] . '/resources/hudson/fixtures.sql');
         $content = str_replace('{{APPLICATION_BOX}}', $dbs['ab'], $content);
         $content = str_replace('{{DATA_BOX}}', $dbName, $content);
         $content = str_replace('{{DB_HOST}}', $conf['main']['database']['host'], $content);
         $content = str_replace('{{DB_PORT}}', $conf['main']['database']['port'], $content);
         $content = str_replace('{{DB_USER}}', $conf['main']['database']['user'], $content);
         $content = str_replace('{{DB_PASSWORD}}', $conf['main']['database']['password'], $content);
         $content = str_replace('{{DATA_BOX}}', $dbName, $content);
         $content = str_replace('{{USER_EMAIL}}', $input->getOption('email'), $content);
         $content = str_replace('{{USER_PASSWORD}}', hash('sha256', $input->getOption('password')), $content);
         $tmpFile = tempnam(sys_get_temp_dir(), 'fixtures-v3.1-');
         $this->container['filesystem']->dumpFile($tmpFile, $content);
         $verbosity = $output->getVerbosity();
         $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
         $this->getApplication()->find('dbal:import')->run(new ArrayInput(array('command' => 'dbal:import', 'file' => $tmpFile)), $output);
         $output->setVerbosity($verbosity);
         $output->writeln('Importing Phraseanet v3.1 fixtures...<info>OK</info>');
     } else {
         $this->getApplication()->find('system:uninstall')->run(new ArrayInput(array('command' => 'system:uninstall')), $output);
         $cmd = sprintf('php ' . __DIR__ . '/../../../../../bin/setup system:install --email=%s --password=%s --db-user=%s --db-template=%s --db-password=%s --databox=%s --appbox=%s --server-name=%s --db-host=%s --db-port=%s -y', $input->getOption('email'), $input->getOption('password'), $conf['main']['database']['user'], 'en', $conf['main']['database']['password'], $dbName, $dbs['ab'], $conf['servername'], $conf['main']['database']['host'], $conf['main']['database']['port']);
         $process = new Process($cmd);
         $process->setTimeout(300);
         $process->run(function ($type, $buffer) {
             if ('err' === $type) {
                 echo 'ERR > ' . $buffer;
             }
         });
         if (false === $process->isSuccessful()) {
             $output->writeln('<error>Failed to execute the following command "' . $cmd . '"</error>');
             return 1;
         }
         $output->writeln("<info>Install successful !</info>");
     }
     foreach ($dbs['dbs'] as $databox) {
         if (!in_array($databox->get_dbname(), $dbToMount) && !in_array('all', $dbToMount)) {
             continue;
         }
         $credentials = $databox->get_connection()->get_credentials();
         \databox::mount($this->container, $credentials['hostname'], $credentials['port'], $credentials['user'], $credentials['password'], $databox->get_dbname());
         $output->writeln('Mounting database "' . $databox->get_dbname() . '"...<info>OK</info>');
     }
     if ($input->getOption('run-patches') || false === $this->container['phraseanet.configuration']->isUpToDate()) {
         $version = new Version();
         if ($input->getOption('run-patches')) {
             $output->write(sprintf('Upgrading... from version <info>3.1.21</info> to <info>%s</info>', $version->getNumber()), true);
         } else {
             $output->write(sprintf('Upgrading... from version <info>%s</info> to <info>%s</info>', $this->app->getApplicationBox()->get_version(), $version->getNumber()), true);
         }
         $cmd = 'php ' . __DIR__ . '/../../../../../bin/setup system:upgrade -y -f -v';
         $process = new Process($cmd);
         $process->setTimeout(600);
         $process->run(function ($type, $buffer) {
             if ('err' === $type) {
                 echo 'ERR > ' . $buffer;
             }
         });
         if (false === $process->isSuccessful()) {
             $output->writeln('<error>Failed to execute the following command "' . $cmd . '"</error>');
             return 1;
         }
     }
     if (!$input->getOption('no-setup-dbs')) {
         // create setup dbs
         $command = $this->getApplication()->find('ini:setup-tests-dbs');
         $input = new ArrayInput(array('command' => 'ini:setup-tests-dbs'));
         $command->run($input, $output);
     }
     $this->container['conf']->set(['main', 'storage', 'subdefs'], $dataPath);
     return 0;
 }
 /**
  * Return unique integer key for a databox
  *
  * @param  \databox $databox
  * @return int
  */
 public function CRCdatabox(\databox $databox)
 {
     return sprintf("%u", crc32(str_replace(['.', '%'], '_', sprintf('%s_%s_%s_%s', $databox->get_host(), $databox->get_port(), $databox->get_user(), $databox->get_dbname()))));
 }
 /**
  * @covers \Alchemy\Phrasea\Controller\Admin\Database::deleteLogoPdf
  */
 public function testDeleteLogoPdf()
 {
     $this->setAdmin(true);
     if ('' === trim(\databox::getPrintLogo(self::$DI['collection']->get_sbas_id()))) {
         $this->markTestSkipped('No logo setted');
     }
     $this->XMLHTTPRequest('POST', '/admin/databox/' . self::$DI['collection']->get_sbas_id() . '/logo/delete/');
     $json = $this->getJson(self::$DI['client']->getResponse());
     $this->assertTrue($json->success);
     $this->assertEmpty(\databox::getPrintLogo(self::$DI['collection']->get_sbas_id()));
 }
 public function findByDatabox(Application $app, \databox $databox)
 {
     $dql = 'SELECT s FROM Phraseanet:StoryWZ s WHERE s.sbas_id = :sbas_id';
     $query = $this->_em->createQuery($dql);
     $query->setParameters(['sbas_id' => $databox->get_sbas_id()]);
     $stories = $query->getResult();
     foreach ($stories as $key => $story) {
         try {
             $story->getRecord($app);
         } catch (NotFoundHttpException $e) {
             $this->getEntityManager()->remove($story);
             $this->getEntityManager()->flush();
             unset($stories[$key]);
         }
     }
     return $stories;
 }
Exemple #27
0
 /**
  * Mount a databox
  *
  * @param  Application      $app     The silex application
  * @param  Request          $request The current HTTP request
  * @return RedirectResponse
  */
 public function databaseMount(Application $app, Request $request)
 {
     if ('' === ($dbName = trim($request->request->get('new_dbname', '')))) {
         return $app->redirectPath('admin_databases', ['success' => 0, 'error' => 'no-empty']);
     }
     if (\p4string::hasAccent($dbName)) {
         return $app->redirectPath('admin_databases', ['success' => 0, 'error' => 'special-chars']);
     }
     if (null === $request->request->get('new_settings')) {
         try {
             $connexion = $app['conf']->get(['main', 'database']);
             $hostname = $connexion['host'];
             $port = $connexion['port'];
             $user = $connexion['user'];
             $password = $connexion['password'];
             $app['phraseanet.appbox']->get_connection()->beginTransaction();
             $base = \databox::mount($app, $hostname, $port, $user, $password, $dbName);
             $base->registerAdmin($app['authentication']->getUser());
             $app['phraseanet.appbox']->get_connection()->commit();
             return $app->redirectPath('admin_database', ['databox_id' => $base->get_sbas_id(), 'success' => 1, 'reload-tree' => 1]);
         } catch (\Exception $e) {
             $app['phraseanet.appbox']->get_connection()->rollBack();
             return $app->redirectPath('admin_databases', ['success' => 0, 'error' => 'mount-failed']);
         }
     }
     if (null !== $request->request->get('new_settings') && null !== ($hostname = $request->request->get('new_hostname')) && null !== ($port = $request->request->get('new_port')) && null !== ($userDb = $request->request->get('new_user')) && null !== ($passwordDb = $request->request->get('new_password'))) {
         try {
             $app['phraseanet.appbox']->get_connection()->beginTransaction();
             $base = \databox::mount($app, $hostname, $port, $userDb, $passwordDb, $dbName);
             $base->registerAdmin($app['authentication']->getUser());
             $app['phraseanet.appbox']->get_connection()->commit();
             return $app->redirectPath('admin_database', ['databox_id' => $base->get_sbas_id(), 'success' => 1, 'reload-tree' => 1]);
         } catch (\Exception $e) {
             $app['phraseanet.appbox']->get_connection()->rollBack();
             return $app->redirectPath('admin_databases', ['success' => 0, 'error' => 'mount-failed']);
         }
     }
 }
Exemple #28
0
 public function delete_data_from_cache($option = null)
 {
     return $this->databox->delete_data_from_cache($this->get_cache_key($option));
 }
Exemple #29
0
 public static function purge()
 {
     self::$_xpath_thesaurus = self::$_dom_thesaurus = self::$_thesaurus = self::$_sxml_thesaurus = [];
 }
Exemple #30
0
 public function connect(Application $app)
 {
     $app['controller.admin.root'] = $this;
     $controllers = $app['controllers_factory'];
     $app['firewall']->addMandatoryAuthentication($controllers);
     $controllers->before(function (Request $request) use($app) {
         $app['firewall']->requireAccessToModule('admin');
     });
     $controllers->get('/', function (Application $app, Request $request) {
         try {
             \Session_Logger::updateClientInfos($app, 3);
         } catch (SessionNotFound $e) {
             return $app->redirectPath('logout');
         }
         $section = $request->query->get('section', false);
         $available = ['connected', 'registrations', 'taskmanager', 'base', 'bases', 'collection', 'user', 'users'];
         $feature = 'connected';
         $featured = false;
         $position = explode(':', $section);
         if (count($position) > 0) {
             if (in_array($position[0], $available)) {
                 $feature = $position[0];
                 if (isset($position[1])) {
                     $featured = $position[1];
                 }
             }
         }
         $databoxes = $off_databoxes = [];
         foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) {
             try {
                 if (!$app['acl']->get($app['authentication']->getUser())->has_access_to_sbas($databox->get_sbas_id())) {
                     continue;
                 }
                 $databox->get_connection();
             } catch (\Exception $e) {
                 $off_databoxes[] = $databox;
                 continue;
             }
             $databoxes[] = $databox;
         }
         $params = ['feature' => $feature, 'featured' => $featured, 'databoxes' => $databoxes, 'off_databoxes' => $off_databoxes];
         return $app['twig']->render('admin/index.html.twig', ['module' => 'admin', 'events' => $app['events-manager'], 'module_name' => 'Admin', 'notice' => $request->query->get("notice"), 'feature' => $feature, 'featured' => $featured, 'databoxes' => $databoxes, 'off_databoxes' => $off_databoxes, 'tree' => $app['twig']->render('admin/tree.html.twig', $params)]);
     })->bind('admin');
     $controllers->get('/tree/', function (Application $app, Request $request) {
         try {
             \Session_Logger::updateClientInfos($app, 3);
         } catch (SessionNotFound $e) {
             return $app->redirectPath('logout');
         }
         $available = ['connected', 'registrations', 'taskmanager', 'base', 'bases', 'collection', 'user', 'users'];
         $feature = 'connected';
         $featured = false;
         $position = explode(':', $request->query->get('position', false));
         if (count($position) > 0) {
             if (in_array($position[0], $available)) {
                 $feature = $position[0];
                 if (isset($position[1])) {
                     $featured = $position[1];
                 }
             }
         }
         $databoxes = $off_databoxes = [];
         foreach ($app['phraseanet.appbox']->get_databoxes() as $databox) {
             try {
                 if (!$app['acl']->get($app['authentication']->getUser())->has_access_to_sbas($databox->get_sbas_id())) {
                     continue;
                 }
                 $databox->get_connection();
             } catch (\Exception $e) {
                 $off_databoxes[] = $databox;
                 continue;
             }
             $databoxes[] = $databox;
         }
         $params = ['feature' => $feature, 'featured' => $featured, 'databoxes' => $databoxes, 'off_databoxes' => $off_databoxes];
         return $app['twig']->render('admin/tree.html.twig', $params);
     })->bind('admin_display_tree');
     $controllers->get('/test-paths/', function (Application $app, Request $request) {
         if (!$request->isXmlHttpRequest() || !array_key_exists($request->getMimeType('json'), array_flip($request->getAcceptableContentTypes()))) {
             $app->abort(400, $app->trans('Bad request format, only JSON is allowed'));
         }
         if (0 !== count($tests = $request->query->get('tests', []))) {
             $app->abort(400, $app->trans('Missing tests parameter'));
         }
         if (null !== ($path = $request->query->get('path'))) {
             $app->abort(400, $app->trans('Missing path parameter'));
         }
         foreach ($tests as $test) {
             switch ($test) {
                 case 'writeable':
                     if (!is_writable($path)) {
                         $result = false;
                     }
                     break;
                 case 'readable':
                 default:
                     if (!is_readable($path)) {
                         $result = true;
                     }
                     break;
             }
         }
         return $app->json(['results' => $result]);
     })->bind('admin_test_paths');
     $controllers->get('/structure/{databox_id}/', function (Application $app, Request $request, $databox_id) {
         if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
             $app->abort(403);
         }
         $databox = $app['phraseanet.appbox']->get_databox((int) $databox_id);
         $structure = $databox->get_structure();
         $errors = \databox::get_structure_errors($app['translator'], $structure);
         if ($updateOk = !!$request->query->get('success', false)) {
             $updateOk = true;
         }
         if (false !== ($errorsStructure = $request->query->get('error', false))) {
             $errorsStructure = true;
         }
         return $app['twig']->render('admin/structure.html.twig', ['databox' => $databox, 'errors' => $errors, 'structure' => $structure, 'errorsStructure' => $errorsStructure, 'updateOk' => $updateOk]);
     })->assert('databox_id', '\\d+')->bind('database_display_stucture');
     $controllers->post('/structure/{databox_id}/', function (Application $app, Request $request, $databox_id) {
         if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
             $app->abort(403);
         }
         if (null === ($structure = $request->request->get('structure'))) {
             $app->abort(400, $app->trans('Missing "structure" parameter'));
         }
         $errors = \databox::get_structure_errors($app['translator'], $structure);
         $domst = new \DOMDocument('1.0', 'UTF-8');
         $domst->preserveWhiteSpace = false;
         $domst->formatOutput = true;
         if (count($errors) == 0 && $domst->loadXML($structure)) {
             $databox = $app['phraseanet.appbox']->get_databox($databox_id);
             $databox->saveStructure($domst);
             return $app->redirectPath('database_display_stucture', ['databox_id' => $databox_id, 'success' => 1]);
         } else {
             return $app->redirectPath('database_display_stucture', ['databox_id' => $databox_id, 'success' => 0, 'error' => 'struct']);
         }
     })->assert('databox_id', '\\d+')->bind('database_submit_stucture');
     $controllers->get('/statusbit/{databox_id}/', function (Application $app, Request $request, $databox_id) {
         if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
             $app->abort(403);
         }
         return $app['twig']->render('admin/statusbit.html.twig', ['databox' => $app['phraseanet.appbox']->get_databox($databox_id)]);
     })->assert('databox_id', '\\d+')->bind('database_display_statusbit');
     $controllers->get('/statusbit/{databox_id}/status/{bit}/', function (Application $app, Request $request, $databox_id, $bit) {
         if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
             $app->abort(403);
         }
         $databox = $app['phraseanet.appbox']->get_databox($databox_id);
         $status = $databox->get_statusbits();
         switch ($errorMsg = $request->query->get('error')) {
             case 'rights':
                 $errorMsg = $app->trans('You do not enough rights to update status');
                 break;
             case 'too-big':
                 $errorMsg = $app->trans('File is too big : 64k max');
                 break;
             case 'upload-error':
                 $errorMsg = $app->trans('Status icon upload failed : upload error');
                 break;
             case 'wright-error':
                 $errorMsg = $app->trans('Status icon upload failed : can not write on disk');
                 break;
             case 'unknow-error':
                 $errorMsg = $app->trans('Something wrong happend');
                 break;
         }
         if (isset($status[$bit])) {
             $status = $status[$bit];
         } else {
             $status = ["labeloff" => '', "labelon" => '', "img_off" => '', "img_on" => '', "path_off" => '', "path_on" => '', "searchable" => false, "printable" => false];
             foreach ($app['locales.available'] as $code => $language) {
                 $status['labels_on'][$code] = null;
                 $status['labels_off'][$code] = null;
             }
         }
         return $app['twig']->render('admin/statusbit/edit.html.twig', ['status' => $status, 'errorMsg' => $errorMsg]);
     })->assert('databox_id', '\\d+')->assert('bit', '\\d+')->bind('database_display_statusbit_form');
     $controllers->post('/statusbit/{databox_id}/status/{bit}/delete/', function (Application $app, Request $request, $databox_id, $bit) {
         if (!$request->isXmlHttpRequest() || !array_key_exists($request->getMimeType('json'), array_flip($request->getAcceptableContentTypes()))) {
             $app->abort(400, $app->trans('Bad request format, only JSON is allowed'));
         }
         if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
             $app->abort(403);
         }
         $error = false;
         try {
             \databox_status::deleteStatus($app, $app['phraseanet.appbox']->get_databox($databox_id), $bit);
         } catch (\Exception $e) {
             $error = true;
         }
         return $app->json(['success' => !$error]);
     })->bind('admin_statusbit_delete')->assert('databox_id', '\\d+')->assert('bit', '\\d+');
     $controllers->post('/statusbit/{databox_id}/status/{bit}/', function (Application $app, Request $request, $databox_id, $bit) {
         if (!$app['acl']->get($app['authentication']->getUser())->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
             $app->abort(403);
         }
         $properties = ['searchable' => $request->request->get('searchable') ? '1' : '0', 'printable' => $request->request->get('printable') ? '1' : '0', 'name' => $request->request->get('name', ''), 'labelon' => $request->request->get('label_on', ''), 'labeloff' => $request->request->get('label_off', ''), 'labels_on' => $request->request->get('labels_on', []), 'labels_off' => $request->request->get('labels_off', [])];
         \databox_status::updateStatus($app, $databox_id, $bit, $properties);
         if (null !== $request->request->get('delete_icon_off')) {
             \databox_status::deleteIcon($app, $databox_id, $bit, 'off');
         }
         if (null !== ($file = $request->files->get('image_off'))) {
             try {
                 \databox_status::updateIcon($app, $databox_id, $bit, 'off', $file);
             } catch (AccessDeniedHttpException $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'rights']);
             } catch (\Exception_InvalidArgument $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'unknow-error']);
             } catch (\Exception_Upload_FileTooBig $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'too-big']);
             } catch (\Exception_Upload_Error $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'upload-error']);
             } catch (\Exception_Upload_CannotWriteFile $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'wright-error']);
             } catch (\Exception $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'unknow-error']);
             }
         }
         if (null !== $request->request->get('delete_icon_on')) {
             \databox_status::deleteIcon($app, $databox_id, $bit, 'on');
         }
         if (null !== ($file = $request->files->get('image_on'))) {
             try {
                 \databox_status::updateIcon($app, $databox_id, $bit, 'on', $file);
             } catch (AccessDeniedHttpException $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'rights']);
             } catch (\Exception_InvalidArgument $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'unknow-error']);
             } catch (\Exception_Upload_FileTooBig $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'too-big']);
             } catch (\Exception_Upload_Error $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'upload-error']);
             } catch (\Exception_Upload_CannotWriteFile $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'wright-error']);
             } catch (\Exception $e) {
                 return $app->redirectPath('database_display_statusbit_form', ['databox_id' => $databox_id, 'bit' => $bit, 'error' => 'unknow-error']);
             }
         }
         return $app->redirectPath('database_display_statusbit', ['databox_id' => $databox_id, 'success' => 1]);
     })->assert('databox_id', '\\d+')->assert('bit', '\\d+')->bind('database_submit_statusbit');
     return $controllers;
 }