public static function apache_tokenize(PropertyAccess $conf, $file) { $ret = false; if ($conf->get(['registry', 'executables', 'h264-streaming-enabled']) && is_file($file)) { if (mb_strpos($file, $conf->get(['registry', 'executables', 'auth-token-directory-path'])) === false) { return false; } $server = new system_server(); if ($server->is_nginx()) { $fileToProtect = mb_substr($file, mb_strlen($conf->get(['registry', 'executables', 'auth-token-directory-path']))); $secret = $conf->get(['registry', 'executables', 'auth-token-passphrase']); $protectedPath = p4string::addFirstSlash(p4string::delEndSlash($conf->get(['registry', 'executables', 'auth-token-directory']))); $hexTime = strtoupper(dechex(time() + 3600)); $token = md5($protectedPath . $fileToProtect . '/' . $secret . '/' . $hexTime); $url = $protectedPath . $fileToProtect . '/' . $token . '/' . $hexTime; $ret = $url; } elseif ($server->is_apache()) { $fileToProtect = mb_substr($file, mb_strlen($conf->get(['registry', 'executables', 'auth-token-directory-path']))); $secret = $conf->get(['registry', 'executables', 'auth-token-passphrase']); // Same as AuthTokenSecret $protectedPath = p4string::addEndSlash(p4string::delFirstSlash($conf->get(['registry', 'executables', 'auth-token-directory']))); // Same as AuthTokenPrefix $hexTime = dechex(time()); // Time in Hexadecimal $token = md5($secret . $fileToProtect . $hexTime); // We build the url $url = '/' . $protectedPath . $token . "/" . $hexTime . $fileToProtect; $ret = $url; } } return $ret; }
/** * Download a set of documents * * @param Application $app * @param Request $request * @param String $token * * @return Response */ public function downloadDocuments(Application $app, Request $request, $token) { $datas = $app['tokens']->helloToken($token); if (false === ($list = @unserialize((string) $datas['datas']))) { $app->abort(500, 'Invalid datas'); } $exportName = $list['export_name']; if ($list['count'] === 1) { $file = end($list['files']); $subdef = end($file['subdefs']); $exportName = sprintf('%s%s.%s', $file['export_name'], $subdef['ajout'], $subdef['exportExt']); $exportFile = \p4string::addEndSlash($subdef['path']) . $subdef['file']; $mime = $subdef['mime']; $list['complete'] = true; } else { $exportFile = $app['root.path'] . '/tmp/download/' . $datas['value'] . '.zip'; $mime = 'application/zip'; } if (!$app['filesystem']->exists($exportFile)) { $app->abort(404, 'Download file not found'); } $app['dispatcher']->addListener(KernelEvents::TERMINATE, function (PostResponseEvent $event) use($list, $app) { \set_export::log_download($app, $list, $event->getRequest()->request->get('type'), null !== $event->getRequest()->request->get('anonymous') ? true : false, isset($list['email']) ? $list['email'] : ''); }); return $app['phraseanet.file-serve']->deliverFile($exportFile, $exportName, DeliverDataInterface::DISPOSITION_ATTACHMENT, $mime); }
protected function dump_base(base $base, InputInterface $input, OutputInterface $output) { $date_obj = new DateTime(); $filename = sprintf('%s%s_%s.sql', p4string::addEndSlash($input->getArgument('directory')), $base->get_dbname(), $date_obj->format('Y_m_d_H_i_s')); $command = sprintf('mysqldump %s %s %s %s %s %s --default-character-set=utf8', '--host=' . escapeshellarg($base->get_host()), '--port=' . escapeshellarg($base->get_port()), '--user='******'--password='******'--databases', escapeshellarg($base->get_dbname())); if ($input->getOption('gzip')) { $filename .= '.gz'; $command .= ' | gzip -9'; } elseif ($input->getOption('bzip')) { $filename .= '.bz2'; $command .= ' | bzip2 -9'; } $output->write(sprintf('Generating <info>%s</info> ... ', $filename)); $command .= ' > ' . escapeshellarg($filename); $process = new Process($command); $process->setTimeout((int) $input->getOption('timeout')); $process->run(); if (!$process->isSuccessful()) { $output->writeln('<error>Failed</error>'); return 1; } if (file_exists($filename) && filesize($filename) > 0) { $output->writeln('OK'); return 0; } else { $output->writeln('<error>Failed</error>'); return 1; } }
protected function buildResult(Application $app, $rs) { $i = 0; foreach ($rs as $row) { if ($i >= $this->nb_record) { break; } foreach ($this->champ as $key => $value) { if ($row[$value]) { if ($value == 'date') { $this->result[$i][$value] = $this->pretty_string ? $app['date-formatter']->getPrettyString(new DateTime($row[$value])) : $row[$value]; } elseif ($value == 'size') { $this->result[$i][$value] = p4string::format_octets($row[$value]); } else { $this->result[$i][$value] = $row[$value]; } } else { if ($value == 'comment') { $this->result[$i][$value] = ' '; } else { $this->result[$i][$value] = '<i>' . $this->app->trans('report:: non-renseigne') . '</i>'; } } } $i++; } }
public function testFormat_seconds() { $this->assertEquals('07:38', p4string::format_seconds(458)); $this->assertEquals('15:46:31', p4string::format_seconds(56791)); $this->assertEquals('2737:59:51', p4string::format_seconds(9856791)); $this->assertEquals('00:00', p4string::format_seconds(0)); $this->assertEquals('', p4string::format_seconds(-15)); }
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()); }
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)); }
/** * * @param SubdefType $type * @param SimpleXMLElement $sd * * @return databox_subdef */ public function __construct(SubdefType $type, SimpleXMLElement $sd, TranslatorInterface $translator) { $this->subdef_group = $type; $this->class = (string) $sd->attributes()->class; $this->translator = $translator; foreach ($sd->devices as $device) { $this->devices[] = (string) $device; } $this->name = strtolower($sd->attributes()->name); $this->downloadable = p4field::isyes($sd->attributes()->downloadable); $this->path = trim($sd->path) !== '' ? p4string::addEndSlash(trim($sd->path)) : ''; $this->write_meta = p4field::isyes((string) $sd->meta); foreach ($sd->label as $label) { $lang = trim((string) $label->attributes()->lang); if ($lang) { $this->labels[$lang] = (string) $label; } } switch ((string) $sd->mediatype) { default: case SubdefSpecs::TYPE_IMAGE: $this->subdef_type = $this->buildImageSubdef($sd); break; case SubdefSpecs::TYPE_AUDIO: $this->subdef_type = $this->buildAudioSubdef($sd); break; case SubdefSpecs::TYPE_VIDEO: $this->subdef_type = $this->buildVideoSubdef($sd); break; case SubdefSpecs::TYPE_ANIMATION: $this->subdef_type = $this->buildGifSubdef($sd); break; case SubdefSpecs::TYPE_FLEXPAPER: $this->subdef_type = $this->buildFlexPaperSubdef($sd); break; } return $this; }
/** * Update a record with a UUID * * @param \databox $databox * @param array $record */ protected function updateRecordUUID(\databox $databox, array $record) { $pathfile = \p4string::addEndSlash($record['path']) . $record['file']; $uuid = Uuid::uuid4(); try { $media = $this->app['mediavorus']->guess($pathfile); $collection = \collection::get_from_coll_id($this->{$app}, $databox, (int) $record['coll_id']); $file = new File($this->app, $media, $collection); $uuid = $file->getUUID(true, true); $sha256 = $file->getSha256(); $this->app['monolog']->addInfo(sprintf("Upgrading record %d with uuid %s", $record['record_id'], $uuid)); } catch (\Exception $e) { $this->app['monolog']->addError(sprintf("Uuid upgrade for record %s failed", $record['record_id'])); } $sql = 'UPDATE record SET uuid = :uuid, sha256 = :sha256 WHERE record_id = :record_id'; $params = [':uuid' => $uuid, 'sha256' => $sha256, ':record_id' => $record['record_id']]; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute($params); $stmt->closeCursor(); }
/** * 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']); } } }
private function formatResult($column, $value, $i) { if ($value) { if ($column == 'coll_id') { $this->result[$i][$column] = $this->formatCollId($value); } elseif ($column == 'ddate') { $this->result[$i][$column] = $this->formatDateValue($value); } elseif ($column == 'size') { $this->result[$i][$column] = p4string::format_octets($value); } else { $this->result[$i][$column] = $value; } } else { if ($column == 'comment') { $this->result[$i][$column] = ''; } else { $this->result[$i][$column] = $this->formatEmptyValue(); } } }
public function exportTopics(Application $app, Request $request) { $lng = $app['locale']; $obr = explode(';', $request->get('obr')); $t_lng = []; if ($request->get('ofm') == 'tofiles') { $t_lng = array_map(function ($code) { $lng_code = explode('_', $code); return $lng_code[0]; }, array_keys($app['locales.available'])); } else { $t_lng[] = $request->get('piv'); } switch ($request->get('obrf')) { case 'from_itf_closable': $default_display = 'closed'; $opened_display = 'opened'; break; case 'from_itf_static': $default_display = 'closed'; $opened_display = 'static'; break; case 'all_opened_closable': $default_display = 'opened'; $opened_display = ''; break; case 'all_opened_static': $default_display = 'static'; $opened_display = ''; break; case 'all_closed': $default_display = 'closed'; $opened_display = ''; break; } $now = date('YmdHis'); $lngs = []; try { $databox = $app['phraseanet.appbox']->get_databox((int) $request->get("bid")); if ($request->get("typ") == "TH") { $domth = $databox->get_dom_thesaurus(); } else { $domth = $databox->get_dom_cterms(); } if ($domth) { $xpathth = new \DOMXPath($domth); if ($request->get("id") == "T") { $q = "/thesaurus"; } elseif ($request->get("id") == "C") { $q = "/cterms"; } else { $q = "//te[@id='" . $request->get("id") . "']"; } if ($request->get('ofm') == 'toscreen') { printf("<pre style='font-size: 12px;'>\n"); } foreach ($t_lng as $lng) { $dom = new \DOMDocument("1.0", "UTF-8"); $dom->standalone = true; $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $root = $dom->appendChild($dom->createElementNS('www.phraseanet.com', 'phraseanet:topics')); $root->appendChild($dom->createComment($app->trans('thesaurus:: fichier genere le %date%', ['%date%' => $now]))); $root->appendChild($dom->createElement('display'))->appendChild($dom->createElement('defaultview'))->appendChild($dom->createTextNode($default_display)); $this->export0Topics($app, $xpathth->query($q)->item(0), $dom, $root, $lng, $request->get("srt"), $request->get("sth"), $request->get("sand"), $opened_display, $obr); if ($request->get("ofm") == 'toscreen') { $lngs[$lng] = str_replace(['&', '<', '>'], ['&', '<', '>'], $dom->saveXML()); } elseif ($request->get("ofm") == 'tofiles') { $fname = 'topics_' . $lng . '.xml'; @rename($app['root.path'] . '/config/topics/' . $fname, $app['root.path'] . '/config/topics/topics_' . $lng . '_BKP_' . $now . '.xml'); if ($dom->save($app['root.path'] . '/config/topics/' . $fname)) { $lngs[$lng] = \p4string::MakeString($app->trans('thesaurus:: fichier genere : %filename%', ['%filename%' => $fname])); } else { $lngs[$lng] = \p4string::MakeString($app->trans('thesaurus:: erreur lors de l\'enregsitrement du fichier')); } } } } } catch (\Exception $e) { } return $app['twig']->render('thesaurus/export-topics.html.twig', ['lngs' => $lngs, 'ofm' => $request->get('ofm')]); }
/** * Download a set of documents * * @param Application $app * @param Request $request * @param Token $token * * @return Response */ public function downloadDocuments(Application $app, Request $request, Token $token) { if (false === ($list = @unserialize($token->getData()))) { $app->abort(500, 'Invalid datas'); } if (!is_array($list)) { $app->abort(500, 'Invalid datas'); } foreach (['export_name', 'files'] as $key) { if (!isset($list[$key])) { $app->abort(500, 'Invalid datas'); } } $exportName = $list['export_name']; if ($list['count'] === 1) { $file = end($list['files']); $subdef = end($file['subdefs']); $exportName = sprintf('%s%s.%s', $file['export_name'], $subdef['ajout'], $subdef['exportExt']); $exportFile = \p4string::addEndSlash($subdef['path']) . $subdef['file']; $mime = $subdef['mime']; $list['complete'] = true; } else { $exportFile = $app['tmp.download.path'] . '/' . $token->getValue() . '.zip'; $mime = 'application/zip'; } if (!$app['filesystem']->exists($exportFile)) { $app->abort(404, 'Download file not found'); } $app['dispatcher']->addListener(KernelEvents::RESPONSE, function (FilterResponseEvent $event) use($list, $app) { \set_export::log_download($app, $list, $event->getRequest()->get('type'), !!$event->getRequest()->get('anonymous', false), isset($list['email']) ? $list['email'] : ''); }); return $app['phraseanet.file-serve']->deliverFile($exportFile, $exportName, DeliverDataInterface::DISPOSITION_ATTACHMENT, $mime); }
/** * * @return string */ public function get_duration() { return p4string::format_seconds($this->entry->getVideoDuration()); }
public static function dispatch(Filesystem $filesystem, $repository_path, $date = false) { if (!$date) { $date = date('Y-m-d H:i:s'); } $repository_path = p4string::addEndSlash($repository_path); $year = date('Y', strtotime($date)); $month = date('m', strtotime($date)); $day = date('d', strtotime($date)); $n = 0; $comp = $year . DIRECTORY_SEPARATOR . $month . DIRECTORY_SEPARATOR . $day . DIRECTORY_SEPARATOR; $pathout = $repository_path . $comp; while (($pathout = $repository_path . $comp . self::addZeros($n)) && is_dir($pathout) && iterator_count(new \DirectoryIterator($pathout)) > 100) { $n++; } $filesystem->mkdir($pathout, 0750); return $pathout . DIRECTORY_SEPARATOR; }
/** * * @param Application $app * @param String $token * @param Array $list * @param string $zipFile * * @return string */ public static function build_zip(Application $app, $token, array $list, $zipFile) { if (isset($list['complete']) && $list['complete'] === true) { return; } $files = $list['files']; $list['complete'] = false; $app['tokens']->updateToken($token, serialize($list)); $toRemove = []; $archiveFiles = []; foreach ($files as $record) { if (isset($record["subdefs"])) { foreach ($record["subdefs"] as $o => $obj) { $path = p4string::addEndSlash($obj["path"]) . $obj["file"]; if (is_file($path)) { $name = $obj["folder"] . $record["export_name"] . $obj["ajout"] . '.' . $obj["exportExt"]; $archiveFiles[$app['unicode']->remove_diacritics($name)] = $path; if ($o == 'caption') { if (!in_array(dirname($path), $toRemove)) { $toRemove[] = dirname($path); } $toRemove[] = $path; } } } } } $app['zippy']->create($zipFile, $archiveFiles); $list['complete'] = true; $app['tokens']->updateToken($token, serialize($list)); $app['filesystem']->remove($toRemove); $app['filesystem']->chmod($zipFile, 0760); return $zipFile; }
/** * Get the deail of download by users * * @param array $tab config for the html table * @param String $on * * @return array */ public function getDetailDownload($tab = false, $on = "") { empty($on) ? $on = "user" : ""; //by default always report on user //set title $this->title = $this->app->trans('report:: Detail des telechargements'); $sqlBuilder = new module_report_sql($this->app, $this); $filter = $sqlBuilder->getFilters()->getReportFilter(); $params = array_merge([], $filter['params']); $sql = "\n SELECT tt.usrid, TRIM(" . $on . ") AS " . $on . ", tt.final, sum(1) AS nb, sum(size) AS poid\n FROM (\n SELECT DISTINCT(log.id), TRIM(" . $on . ") AS " . $on . ", log_docs.record_id, log_docs.final, log.usrid\n FROM log_docs\n INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_docs.log_id)\n INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id)\n INNER JOIN record ON (record.record_id = log_docs.record_id)\n WHERE (" . $filter['sql'] . ")\n AND (log_docs.action = 'download' OR log_docs.action = 'mail')\n ) AS tt\n LEFT JOIN subdef FORCE INDEX (unicite) ON (tt.record_id = subdef.record_id)\n WHERE subdef.name = tt.final\n GROUP BY " . $on . ", usrid\n ORDER BY nb DESC;"; $stmt = $sqlBuilder->getConnBas()->prepare($sql); $stmt->execute($params); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $save_user = ""; $i = -1; $total = ['nbdoc' => 0, 'poiddoc' => 0, 'nbprev' => 0, 'poidprev' => 0]; $this->setChamp($rs); $this->setDisplay($tab); foreach ($rs as $row) { $user = $row[$on]; if ($save_user != $user && !is_null($user) && !empty($user)) { if ($i >= 0) { if ($this->result[$i]['nbprev'] + $this->result[$i]['nbdoc'] == 0 || $this->result[$i]['poiddoc'] + $this->result[$i]['poidprev'] == 0) { unset($this->result[$i]); } if (isset($this->result[$i]['poiddoc']) && isset($this->result[$i]['poidprev'])) { $this->result[$i]['poiddoc'] = p4string::format_octets($this->result[$i]['poiddoc']); $this->result[$i]['poidprev'] = p4string::format_octets($this->result[$i]['poidprev']); } } $i++; $this->result[$i]['nbprev'] = 0; $this->result[$i]['poidprev'] = 0; $this->result[$i]['nbdoc'] = 0; $this->result[$i]['poiddoc'] = 0; } //doc info if ($row['final'] == 'document' && !is_null($user) && !is_null($row['usrid'])) { $this->result[$i]['nbdoc'] = !is_null($row['nb']) ? $row['nb'] : 0; $this->result[$i]['poiddoc'] = !is_null($row['poid']) ? $row['poid'] : 0; $this->result[$i]['user'] = empty($row[$on]) ? "<i>" . $this->app->trans('report:: non-renseigne') . "</i>" : $row[$on]; $total['nbdoc'] += $this->result[$i]['nbdoc']; $total['poiddoc'] += !is_null($row['poid']) ? $row['poid'] : 0; $this->result[$i]['usrid'] = $row['usrid']; } //preview info if (($row['final'] == 'preview' || $row['final'] == 'thumbnail') && !is_null($user) && !is_null($row['usrid'])) { $this->result[$i]['nbprev'] += !is_null($row['nb']) ? $row['nb'] : 0; $this->result[$i]['poidprev'] += !is_null($row['poid']) ? $row['poid'] : 0; $this->result[$i]['user'] = empty($row[$on]) ? "<i>" . $this->app->trans('report:: non-renseigne') . "</i>" : $row[$on]; $total['nbprev'] += !is_null($row['nb']) ? $row['nb'] : 0; $total['poidprev'] += !is_null($row['poid']) ? $row['poid'] : 0; $this->result[$i]['usrid'] = $row['usrid']; } $save_user = $user; } unset($this->result[$i]); $nb_row = $i + 1; $this->total = $nb_row; if ($this->total > 0) { $this->result[$nb_row]['user'] = '******'; $this->result[$nb_row]['nbdoc'] = '<b>' . $total['nbdoc'] . '</b>'; $this->result[$nb_row]['poiddoc'] = '<b>' . p4string::format_octets($total['poiddoc']) . '</b>'; $this->result[$nb_row]['nbprev'] = '<b>' . $total['nbprev'] . '</b>'; $this->result[$nb_row]['poidprev'] = '<b>' . p4string::format_octets($total['poidprev']) . '</b>'; } $this->total = sizeof($this->result); $this->calculatePages(); $this->setDisplayNav(); $this->setReport(); return $this->report; }
private static function drawTopics($topics, $depth = 0, $triid = '', $defaultview) { $n = 0; $out = ''; foreach ($topics->topic as $subtopic) { $tid = $triid . '_' . $n; $s = $subtopic->label; $l = p4string::MakeString($s, 'html'); $l = '<span class=\'topic_' . $depth . '\'>' . $l . '</span>'; if ($subtopic->query) { $q = str_replace(["\\", "\"", "'", "\r", "\n"], ["\\\\", """, "\\'", "\\r", "\\n"], $subtopic->query); $q = '<a href="javascript:void();" onClick="doSpecialSearch(\'' . $q . '\',true);">' . $l . '</a>'; } else { $q = $l; } if (self::hastopics($subtopic)) { $view = mb_strtolower($subtopic['view']); if (!$view) { $view = $defaultview; } switch ($view) { case 'opened': $out .= '<li><a id=\'TOPIC_TRI' . $tid . '\' class="opened" href="javascript:void();" onclick="clktri(\'' . $tid . '\');return(false);"></a> ' . $q . '</li>' . "\n"; $out .= "<ul id='TOPIC_UL{$tid}' class='opened'>\n"; $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); $out .= "</ul>\n<div style='height:1px;'></div>\n"; break; case 'closed': $out .= '<li><a id=\'TOPIC_TRI' . $tid . '\' class="closed" href="javascript:void();" onclick="clktri(\'' . $tid . '\');return(false);"></a> ' . $q . '</li>' . "\n"; $out .= "<ul id='TOPIC_UL{$tid}' class='closed'>\n"; $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); $out .= "</ul>\n<div style='height:1px;'></div>\n"; break; case 'static': default: $out .= '<li><span id=\'TOPIC_TRI' . $tid . '\' class="static"> </span> ' . $q . '</li>' . "\n"; $out .= "<ul id='TOPIC_UL{$tid}' class='static'>\n"; $out .= self::drawTopics($subtopic->topics, $depth + 1, $tid, $defaultview); $out .= "</ul>\n<div style='height:1px;'></div>\n"; break; } } else { $out .= '<li><span id=\'TOPIC_TRI' . $tid . '\' class="none"> </span> ' . $q . '</li>' . "\n"; } $n++; } return $out; }
public function calcSQL(Application $app, $sxtask, $playTest = false) { $sbas_id = (int) $sxtask['sbas_id']; $ret = ['name' => $sxtask['name'] ? (string) $sxtask['name'] : 'sans nom', 'name_htmlencoded' => \p4string::MakeString($sxtask['name'] ? $sxtask['name'] : 'sans nom', 'html'), 'active' => trim($sxtask['active']) === '1', 'sbas_id' => $sbas_id, 'basename' => '', 'basename_htmlencoded' => '', 'action' => strtoupper($sxtask['action']), 'sql' => null, 'err' => '', 'err_htmlencoded' => '']; try { $dbox = $app['phraseanet.appbox']->get_databox($sbas_id); $ret['basename'] = $dbox->get_label($app['locale']); $ret['basename_htmlencoded'] = htmlentities($ret['basename']); switch ($ret['action']) { case 'UPDATE': $ret['sql'] = $this->calcUPDATE($app, $sbas_id, $sxtask, $playTest); break; case 'DELETE': $ret['sql'] = $this->calcDELETE($app, $sbas_id, $sxtask, $playTest); $ret['deletechildren'] = (int) $sxtask['deletechildren']; break; default: $ret['err'] = "bad action '" . $ret['action'] . "'"; $ret['err_htmlencoded'] = htmlentities($ret['err']); break; } } catch (\Exception $e) { $ret['err'] = "bad sbas '" . $sbas_id . "'"; $ret['err_htmlencoded'] = htmlentities($ret['err']); } return $ret; }
/** * Render the html upload form * * @param Application $app A Silex application * @param Request $request The current request * * @return Response */ public function getUploadForm(Application $app, Request $request) { $maxFileSize = $this->getUploadMaxFileSize(); return $app['twig']->render('prod/upload/upload.html.twig', ['collections' => $this->getGrantedCollections($app['acl']->get($app['authentication']->getUser())), 'maxFileSize' => $maxFileSize, 'maxFileSizeReadable' => \p4string::format_octets($maxFileSize)]); }
public function connect(SilexApplication $app) { $app['controller.api.v1'] = $this; $controllers = $app['controllers_factory']; /** * @var API_OAuth2_Token */ $app['token'] = null; /** * Api Service * @var Closure */ $app['api'] = function () use($app) { return new \API_V1_adapter($app); }; /** * oAuth token verification process * - Check if oauth_token exists && is valid * - Check if request comes from phraseanet Navigator && phraseanet Navigator * is enbale on current instance * - restore user session * * @ throws \API_V1_exception_unauthorized * @ throws \API_V1_exception_forbidden */ $controllers->before(function ($request) use($app) { $context = new Context(Context::CONTEXT_OAUTH2_TOKEN); $app['dispatcher']->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context)); $app['dispatcher']->dispatch(PhraseaEvents::API_OAUTH2_START, new ApiOAuth2StartEvent()); $oauth2_adapter = new \API_OAuth2_Adapter($app); $oauth2_adapter->verifyAccessToken(); $app['token'] = \API_OAuth2_Token::load_by_oauth_token($app, $oauth2_adapter->getToken()); $oAuth2App = $app['token']->get_account()->get_application(); /* @var $oAuth2App \API_OAuth2_Application */ if ($oAuth2App->get_client_id() == \API_OAuth2_Application_Navigator::CLIENT_ID && !$app['conf']->get(['registry', 'api-clients', 'navigator-enabled'])) { throw new \API_V1_exception_forbidden('The use of phraseanet Navigator is not allowed'); } if ($oAuth2App->get_client_id() == \API_OAuth2_Application_OfficePlugin::CLIENT_ID && !$app['conf']->get(['registry', 'api-clients', 'office-enabled'])) { throw new \API_V1_exception_forbidden('The use of Office Plugin is not allowed.'); } if ($app['authentication']->isAuthenticated()) { $app['dispatcher']->dispatch(PhraseaEvents::API_OAUTH2_END, new ApiOAuth2EndEvent()); return; } $user = $app['manipulator.user']->getRepository()->find($oauth2_adapter->get_usr_id()); $app['authentication']->openAccount($user); $oauth2_adapter->remember_this_ses_id($app['session']->get('session_id')); $app['dispatcher']->dispatch(PhraseaEvents::API_OAUTH2_END, new ApiOAuth2EndEvent()); return; }); /** * OAuth log process * * Parse the requested route to fetch * - the ressource (databox, basket, record etc ..) * - general action (list, add, search) * - the action (setstatus, setname etc..) * - the aspect (collections, related, content etc..) * * @return array */ $parseRoute = function ($route, Response $response) { $ressource = $general = $aspect = $action = null; $exploded_route = explode('/', \p4string::delFirstSlash(\p4string::delEndSlash($route))); if (sizeof($exploded_route) > 0 && $response->isOk()) { $ressource = $exploded_route[0]; if (sizeof($exploded_route) == 2 && (int) $exploded_route[1] == 0) { $general = $exploded_route[1]; } else { switch ($ressource) { case \API_V1_Log::DATABOXES_RESSOURCE: if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3) { $aspect = $exploded_route[2]; } break; case \API_V1_Log::RECORDS_RESSOURCE: if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 4) { if (!isset($exploded_route[3])) { $aspect = "record"; } elseif (preg_match("/^set/", $exploded_route[3])) { $action = $exploded_route[3]; } else { $aspect = $exploded_route[3]; } } break; case \API_V1_Log::BASKETS_RESSOURCE: if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3) { if (preg_match("/^set/", $exploded_route[2]) || preg_match("/^delete/", $exploded_route[2])) { $action = $exploded_route[2]; } else { $aspect = $exploded_route[2]; } } break; case \API_V1_Log::FEEDS_RESSOURCE: if ((int) $exploded_route[1] > 0 && sizeof($exploded_route) == 3) { $aspect = $exploded_route[2]; } break; } } } return ['ressource' => $ressource, 'general' => $general, 'aspect' => $aspect, 'action' => $action]; }; /** * Log occurs in after filter */ $controllers->after(function (Request $request, Response $response) use($app, $parseRoute) { $account = $app['token']->get_account(); $pathInfo = $request->getPathInfo(); $route = $parseRoute($pathInfo, $response); \API_V1_Log::create($app, $account, $request->getMethod() . " " . $pathInfo, $response->getStatusCode(), $response->headers->get('content-type'), $route['ressource'], $route['general'], $route['aspect'], $route['action']); }); $controllers->after(function () use($app) { $app['authentication']->closeAccount(); }); /** * Method Not Allowed Closure */ $bad_request_exception = function () { throw new \API_V1_exception_badrequest(); }; /** * Check wether the current user is Admin or not */ $mustBeAdmin = function (Request $request) use($app) { $user = $app['token']->get_account()->get_user(); if (!$app['acl']->get($user)->is_admin()) { throw new \API_V1_exception_unauthorized('You are not authorized'); } }; /** * Get scheduler informations * * Route : /monitor/scheduler/ * * Method : GET * * Parameters : * */ $controllers->get('/monitor/scheduler/', function (SilexApplication $app, Request $request) { return $app['api']->get_scheduler($app)->get_response(); })->before($mustBeAdmin); /** * Get all tasks information * * Route : /monitor/tasks/ * * Method : GET * * Parameters : * */ $controllers->get('/monitor/tasks/', function (SilexApplication $app, Request $request) { return $app['api']->get_task_list($app)->get_response(); })->before($mustBeAdmin); /** * Get task informations * * Route : /monitor/task/{task}/ * * Method : GET * * Parameters : * */ $controllers->get('/monitor/task/{task}/', function (SilexApplication $app, Request $request, $task) { return $app['api']->get_task($app, $task)->get_response(); })->convert('task', [$app['converter.task'], 'convert'])->before($mustBeAdmin)->assert('task', '\\d+'); /** * Start task * * Route : /monitor/task/{task}/ * * Method : POST * * Parameters : * - name (string) change the name of the task * - autostart (boolean) start task when scheduler starts */ $controllers->post('/monitor/task/{task}/', function (SilexApplication $app, Request $request, $task) { return $app['api']->set_task_property($app, $task)->get_response(); })->convert('task', [$app['converter.task'], 'convert'])->before($mustBeAdmin)->assert('task', '\\d+'); /** * Start task * * Route : /monitor/task/{task}/start/ * * Method : POST * * Parameters : * */ $controllers->post('/monitor/task/{task}/start/', function (SilexApplication $app, Request $request, $task) { return $app['api']->start_task($app, $task)->get_response(); })->convert('task', [$app['converter.task'], 'convert'])->before($mustBeAdmin); /** * Stop task * * Route : /monitor/task/{task}/stop/ * * Method : POST * * Parameters : * */ $controllers->post('/monitor/task/{task}/stop/', function (SilexApplication $app, Request $request, $task) { return $app['api']->stop_task($app, $task)->get_response(); })->convert('task', [$app['converter.task'], 'convert'])->before($mustBeAdmin); /** * Get some information about phraseanet * * Route : /monitor/phraseanet/ * * Method : GET * * Parameters : * */ $controllers->get('/monitor/phraseanet/', function (SilexApplication $app, Request $request) { return $app['api']->get_phraseanet_monitor($app)->get_response(); })->before($mustBeAdmin); /** * Route : /databoxes/list/ * * Method : GET * * Parameters : * */ $controllers->get('/databoxes/list/', function (SilexApplication $app, Request $request) { return $app['api']->get_databoxes($request)->get_response(); }); /** * Route /databoxes/DATABOX_ID/collections/ * * Method : GET * * Parameters ; * DATABOX_ID : required INT */ $controllers->get('/databoxes/{databox_id}/collections/', function (SilexApplication $app, $databox_id) { return $app['api']->get_databox_collections($app['request'], $databox_id)->get_response(); })->assert('databox_id', '\\d+'); $controllers->get('/databoxes/{any_id}/collections/', $bad_request_exception); /** * Route /databoxes/DATABOX_ID/status/ * * Method : GET * * Parameters ; * DATABOX_ID : required INT * */ $controllers->get('/databoxes/{databox_id}/status/', function (SilexApplication $app, $databox_id) { return $app['api']->get_databox_status($app['request'], $databox_id)->get_response(); })->assert('databox_id', '\\d+'); $controllers->get('/databoxes/{any_id}/status/', $bad_request_exception); /** * Route /databoxes/DATABOX_ID/metadatas/ * * Method : GET * * Parameters ; * DATABOX_ID : required INT */ $controllers->get('/databoxes/{databox_id}/metadatas/', function (SilexApplication $app, $databox_id) { return $app['api']->get_databox_metadatas($app['request'], $databox_id)->get_response(); })->assert('databox_id', '\\d+'); $controllers->get('/databoxes/{any_id}/metadatas/', $bad_request_exception); /** * Route /databoxes/DATABOX_ID/termsOfUse/ * * Method : GET * * Parameters ; * DATABOX_ID : required INT */ $controllers->get('/databoxes/{databox_id}/termsOfUse/', function (SilexApplication $app, $databox_id) { return $app['api']->get_databox_terms($app['request'], $databox_id)->get_response(); })->assert('databox_id', '\\d+'); $controllers->get('/databoxes/{any_id}/termsOfUse/', $bad_request_exception); $controllers->get('/quarantine/list/', function (SilexApplication $app, Request $request) { return $app['api']->list_quarantine($app, $request)->get_response(); }); $controllers->get('/quarantine/item/{lazaret_id}/', function ($lazaret_id, SilexApplication $app, Request $request) { return $app['api']->list_quarantine_item($lazaret_id, $app, $request)->get_response(); }); /** * Route : /records/add/ * * Method : POST * * Parameters : * */ $controllers->post('/records/add/', function (SilexApplication $app, Request $request) { return $app['api']->add_record($app, $request)->get_response(); }); /** * Route : /search/ * * Method : GET or POST * * Parameters : * bases[] : array * status[] : array * fields[] : array * record_type : boolean * media_type : string * * Response : * Array containing an array of records and stories collection * */ $controllers->match('/search/', function () use($app) { return $app['api']->search($app['request'])->get_response(); }); /** * Route : /records/search/ * * Method : GET or POST * * Parameters : * bases[] : array * status[] : array * fields[] : array * record_type : boolean * media_type : string * * Response : * Array of record objects * */ $controllers->match('/records/search/', function (SilexApplication $app) { return $app['api']->search_records($app['request'])->get_response(); }); $controllers->get('/records/{databox_id}/{record_id}/caption/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->caption_records($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->get('/records/{any_id}/{anyother_id}/caption/', $bad_request_exception); /** * Route : /records/DATABOX_ID/RECORD_ID/metadatas/ * * Method : GET * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->get('/records/{databox_id}/{record_id}/metadatas/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->get_record_metadatas($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->get('/records/{any_id}/{anyother_id}/metadatas/', $bad_request_exception); /** * Route : /records/DATABOX_ID/RECORD_ID/status/ * * Method : GET * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->get('/records/{databox_id}/{record_id}/status/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->get_record_status($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->get('/records/{any_id}/{anyother_id}/status/', $bad_request_exception); /** * Route : /records/DATABOX_ID/RECORD_ID/related/ * * Method : GET * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->get('/records/{databox_id}/{record_id}/related/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->get_record_related($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->get('/records/{any_id}/{anyother_id}/related/', $bad_request_exception); /** * Route : /records/DATABOX_ID/RECORD_ID/embed/ * * Method : GET * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->get('/records/{databox_id}/{record_id}/embed/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->get_record_embed($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->get('/records/{any_id}/{anyother_id}/embed/', $bad_request_exception); /** * Route : /records/DATABOX_ID/RECORD_ID/setmetadatas/ * * Method : POST * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->post('/records/{databox_id}/{record_id}/setmetadatas/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->set_record_metadatas($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->post('/records/{any_id}/{anyother_id}/setmetadatas/', $bad_request_exception); /** * Route : /records/DATABOX_ID/RECORD_ID/setstatus/ * * Method : POST * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->post('/records/{databox_id}/{record_id}/setstatus/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->set_record_status($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->post('/records/{any_id}/{anyother_id}/setstatus/', $bad_request_exception); /** * Route : /records/DATABOX_ID/RECORD_ID/setcollection/ * * Method : POST * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->post('/records/{databox_id}/{record_id}/setcollection/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->set_record_collection($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->post('/records/{wrong_databox_id}/{wrong_record_id}/setcollection/', $bad_request_exception); $controllers->get('/records/{databox_id}/{record_id}/', function (SilexApplication $app, $databox_id, $record_id) { return $app['api']->get_record($app['request'], $databox_id, $record_id)->get_response(); })->assert('databox_id', '\\d+')->assert('record_id', '\\d+'); $controllers->get('/records/{any_id}/{anyother_id}/', $bad_request_exception); /** * Route : /baskets/list/ * * Method : POST * * Parameters : * */ $controllers->get('/baskets/list/', function (SilexApplication $app) { return $app['api']->search_baskets($app['request'])->get_response(); }); /** * Route : /baskets/add/ * * Method : POST * * Parameters : * */ $controllers->post('/baskets/add/', function (SilexApplication $app) { return $app['api']->create_basket($app['request'])->get_response(); }); /** * Route : /baskets/BASKET_ID/content/ * * Method : GET * * Parameters : * BASKET_ID : required INT * */ $controllers->get('/baskets/{basket}/content/', function (SilexApplication $app, Basket $basket) { return $app['api']->get_basket($app['request'], $basket)->get_response(); })->before($app['middleware.basket.converter'])->before($app['middleware.basket.user-access'])->assert('basket', '\\d+'); $controllers->get('/baskets/{wrong_basket}/content/', $bad_request_exception); /** * Route : /baskets/BASKET_ID/settitle/ * * Method : GET * * Parameters : * BASKET_ID : required INT * */ $controllers->post('/baskets/{basket}/setname/', function (SilexApplication $app, Basket $basket) { return $app['api']->set_basket_title($app['request'], $basket)->get_response(); })->before($app['middleware.basket.converter'])->before($app['middleware.basket.user-is-owner'])->assert('basket', '\\d+'); $controllers->post('/baskets/{wrong_basket}/setname/', $bad_request_exception); /** * Route : /baskets/BASKET_ID/setdescription/ * * Method : POST * * Parameters : * BASKET_ID : required INT * */ $controllers->post('/baskets/{basket}/setdescription/', function (SilexApplication $app, Basket $basket) { return $app['api']->set_basket_description($app['request'], $basket)->get_response(); })->before($app['middleware.basket.converter'])->before($app['middleware.basket.user-is-owner'])->assert('basket', '\\d+'); $controllers->post('/baskets/{wrong_basket}/setdescription/', $bad_request_exception); /** * Route : /baskets/BASKET_ID/delete/ * * Method : POST * * Parameters : * BASKET_ID : required INT * */ $controllers->post('/baskets/{basket}/delete/', function (SilexApplication $app, Basket $basket) { return $app['api']->delete_basket($app['request'], $basket)->get_response(); })->before($app['middleware.basket.converter'])->before($app['middleware.basket.user-is-owner'])->assert('basket', '\\d+'); $controllers->post('/baskets/{wrong_basket}/delete/', $bad_request_exception); /** * Route : /feeds/list/ * * Method : POST * * Parameters : * */ $controllers->get('/feeds/list/', function (SilexApplication $app) { return $app['api']->search_publications($app['request'], $app['authentication']->getUser())->get_response(); }); $controllers->get('/feeds/content/', function (SilexApplication $app) { return $app['api']->get_publications($app['request'], $app['authentication']->getUser())->get_response(); }); $controllers->get('/feeds/entry/{entry_id}/', function (SilexApplication $app, $entry_id) { return $app['api']->get_feed_entry($app['request'], $entry_id, $app['authentication']->getUser())->get_response(); })->assert('entry_id', '\\d+'); $controllers->get('/feeds/entry/{entry_id}/', $bad_request_exception); /** * Route : /feeds/PUBLICATION_ID/content/ * * Method : GET * * Parameters : * PUBLICATION_ID : required INT * */ $controllers->get('/feeds/{feed_id}/content/', function (SilexApplication $app, $feed_id) { return $app['api']->get_publication($app['request'], $feed_id, $app['authentication']->getUser())->get_response(); })->assert('feed_id', '\\d+'); $controllers->get('/feeds/{wrong_feed_id}/content/', $bad_request_exception); /** * Route : /stories/DATABOX_ID/RECORD_ID/embed/ * * Method : GET * * Parameters : * DATABOX_ID : required INT * RECORD_ID : required INT * */ $controllers->get('/stories/{databox_id}/{story_id}/embed/', function ($databox_id, $story_id) use($app) { $result = $app['api']->get_story_embed($app['request'], $databox_id, $story_id); return $result->get_response(); })->assert('databox_id', '\\d+')->assert('story_id', '\\d+'); $controllers->get('/stories/{any_id}/{anyother_id}/embed/', $bad_request_exception); $controllers->get('/stories/{databox_id}/{story_id}/', function ($databox_id, $story_id) use($app) { $result = $app['api']->get_story($app['request'], $databox_id, $story_id); return $result->get_response(); })->assert('databox_id', '\\d+')->assert('story_id', '\\d+'); $controllers->get('/stories/{any_id}/{anyother_id}/', $bad_request_exception); $controllers->get('/stories/{databox_id}/{story_id}/', function ($databox_id, $story_id) use($app) { $result = $app['api']->get_story($app['request'], $databox_id, $story_id); return $result->get_response(); })->assert('databox_id', '\\d+')->assert('story_id', '\\d+'); $controllers->get('/stories/{any_id}/{anyother_id}/', $bad_request_exception); return $controllers; }
public function substitute_subdef($name, MediaInterface $media, Application $app, $adapt = true) { $newfilename = $this->record_id . '_0_' . $name . '.' . $media->getFile()->getExtension(); if ($name == 'document') { $baseprefs = $this->get_databox()->get_sxml_structure(); $pathhd = p4string::addEndSlash((string) $baseprefs->path); $filehd = $this->get_record_id() . "_document." . strtolower($media->getFile()->getExtension()); $pathhd = databox::dispatch($app['filesystem'], $pathhd); $app['filesystem']->copy($media->getFile()->getRealPath(), $pathhd . $filehd, true); $subdefFile = $pathhd . $filehd; $meta_writable = true; } else { $type = $this->isStory() ? 'image' : $this->get_type(); $subdef_def = $this->get_databox()->get_subdef_structure()->get_subdef($type, $name); if ($this->has_subdef($name) && $this->get_subdef($name)->is_physically_present()) { $path_file_dest = $this->get_subdef($name)->get_pathfile(); $this->get_subdef($name)->remove_file(); $this->clearSubdefCache($name); } else { $path = databox::dispatch($app['filesystem'], $subdef_def->get_path()); $app['filesystem']->mkdir($path, 0750); $path_file_dest = $path . $newfilename; } if ($adapt) { try { $app['media-alchemyst']->turnInto($media->getFile()->getRealPath(), $path_file_dest, $subdef_def->getSpecs()); } catch (\MediaAlchemyst\Exception\ExceptionInterface $e) { return $this; } $subdefFile = $path_file_dest; } else { $app['filesystem']->copy($media->getFile()->getRealPath(), $path_file_dest); $subdefFile = $path_file_dest; } $meta_writable = $subdef_def->meta_writeable(); } $app['filesystem']->chmod($subdefFile, 0760); $media = $app->getMediaFromUri($subdefFile); $subdef = media_subdef::create($app, $this, $name, $media); $subdef->set_substituted(true); $this->delete_data_from_cache(self::CACHE_SUBDEFS); if ($meta_writable) { $this->write_metas(); } if ($name == 'document' && $adapt) { $this->rebuild_subdefs(); } return $this; }
public function getUploadForm() { $maxFileSize = $this->getUploadMaxFileSize(); return $this->render('prod/upload/upload.html.twig', ['collections' => $this->getGrantedCollections($this->getAclForUser()), 'maxFileSize' => $maxFileSize, 'maxFileSizeReadable' => \p4string::format_octets($maxFileSize)]); }
protected function doExport(Application $app, Task $task, FtpExport $export) { $settings = simplexml_load_string($task->getSettings()); $proxy = (string) $settings->proxy; $proxyport = (string) $settings->proxyport; $state = ""; $ftp_server = $export->getAddr(); $ftp_user_name = $export->getLogin(); $ftp_user_pass = $export->getPwd(); $ftpLog = $ftp_user_name . "@" . \p4string::addEndSlash($ftp_server) . $export->getDestfolder(); if ($export->getCrash() == 0) { $line = $this->translator->trans('task::ftp:Etat d\'envoi FTP vers le serveur "%server%" avec le compte "%username%" et pour destination le dossier : "%directory%"', ['%server%' => $ftp_server, '%username%' => $ftp_user_name, '%directory%' => $export->getDestfolder()]) . PHP_EOL; $state .= $line; $this->log('debug', $line); } $state .= $line = $this->translator->trans("task::ftp:TENTATIVE no %number%, %date%", ['%number%' => $export->getCrash() + 1, '%date%' => " (" . date('r') . ")"]) . PHP_EOL; $this->log('debug', $line); try { $ssl = $export->isSsl(); $ftp_client = $app['phraseanet.ftp.client']($ftp_server, 21, 300, $ssl, $proxy, $proxyport); $ftp_client->login($ftp_user_name, $ftp_user_pass); if ($export->isPassif()) { try { $ftp_client->passive(true); } catch (\Exception $e) { $this->log('debug', $e->getMessage()); } } if (trim($export->getDestfolder()) != '') { try { $ftp_client->chdir($export->getDestFolder()); $export->setDestfolder('/' . $export->getDestfolder()); } catch (\Exception $e) { $this->log('debug', $e->getMessage()); } } else { $export->setDestfolder('/'); } if (trim($export->getFoldertocreate()) != '') { try { $ftp_client->mkdir($export->getFoldertocreate()); } catch (\Exception $e) { $this->log('debug', $e->getMessage()); } try { $new_dir = $ftp_client->add_end_slash($export->getDestfolder()) . $export->getFoldertocreate(); $ftp_client->chdir($new_dir); } catch (\Exception $e) { $this->log('debug', $e->getMessage()); } } $obj = []; $basefolder = ''; if (!in_array(trim($export->getDestfolder()), ['.', './', ''])) { $basefolder = \p4string::addEndSlash($export->getDestfolder()); } $basefolder .= $export->getFoldertocreate(); if (in_array(trim($basefolder), ['.', './', ''])) { $basefolder = '/'; } foreach ($export->getElements() as $exportElement) { if ($exportElement->isDone()) { continue; } $base_id = $exportElement->getBaseId(); $record_id = $exportElement->getRecordId(); $subdef = $exportElement->getSubdef(); $localfile = null; try { $sbas_id = \phrasea::sbasFromBas($app, $base_id); $record = new \record_adapter($app, $sbas_id, $record_id); $sdcaption = $app['serializer.caption']->serialize($record->get_caption(), CaptionSerializer::SERIALIZE_XML, $exportElement->isBusinessfields()); $remotefile = $exportElement->getFilename(); if ($subdef == 'caption') { $desc = $app['serializer.caption']->serialize($record->get_caption(), CaptionSerializer::SERIALIZE_XML, $exportElement->isBusinessfields()); $localfile = sys_get_temp_dir() . '/' . md5($desc . time() . mt_rand()); if (file_put_contents($localfile, $desc) === false) { throw new \Exception('Impossible de creer un fichier temporaire'); } } elseif ($subdef == 'caption-yaml') { $desc = $app['serializer.caption']->serialize($record->get_caption(), CaptionSerializer::SERIALIZE_YAML, $exportElement->isBusinessfields()); $localfile = sys_get_temp_dir() . '/' . md5($desc . time() . mt_rand()); if (file_put_contents($localfile, $desc) === false) { throw new \Exception('Impossible de creer un fichier temporaire'); } } else { $sd = $record->get_subdefs(); if (!$sd || !isset($sd[$subdef])) { continue; } $localfile = $sd[$subdef]->get_pathfile(); if (!file_exists($localfile)) { throw new \Exception('Le fichier local n\'existe pas'); } } $current_folder = rtrim(str_replace('//', '/', $basefolder . $exportElement->getFolder()), '/'); if ($ftp_client->pwd() != $current_folder) { try { $ftp_client->chdir($current_folder); } catch (\Exception $e) { $this->log('debug', $e->getMessage()); } } $ftp_client->put($remotefile, $localfile); $obj[] = ["name" => $subdef, "size" => filesize($localfile), "shortXml" => $sdcaption ? $sdcaption : '']; if ($subdef == 'caption') { unlink($localfile); } $exportElement->setDone(true)->setError(false); $app['EM']->persist($exportElement); $app['EM']->flush(); $this->logexport($app, $record, $obj, $ftpLog); } catch (\Exception $e) { $state .= $line = $this->translator->trans('task::ftp:File "%file%" (record %record_id%) de la base "%basename%" (Export du Document) : Transfert cancelled (le document n\'existe plus)', ['%file%' => basename($localfile), '%record_id%' => $record_id, '%basename%' => \phrasea::sbas_labels(\phrasea::sbasFromBas($app, $base_id), $app)]) . "\n<br/>"; $this->log('debug', $line); // One failure max $exportElement->setDone($exportElement->isError())->setError(true); $app['EM']->persist($exportElement); $app['EM']->flush(); } } if ($export->isLogfile()) { $this->log('debug', "logfile "); $date = new DateTime(); $buffer = '#transfert finished ' . $date->format(DATE_ATOM) . "\n\n"; foreach ($export->getElements() as $exportElement) { if (!$exportElement->isDone() || $exportElement->isError()) { continue; } $filename = $exportElement->getFilename(); $folder = $exportElement->getFilename(); $root = $export->getFoldertocreate(); $buffer .= $root . '/' . $folder . $filename . "\n"; } $tmpfile = sys_get_temp_dir() . '/tmpftpbuffer' . $date->format('U') . '.txt'; file_put_contents($tmpfile, $buffer); $remotefile = $date->format('U') . '-transfert.log'; $ftp_client->chdir($export->getDestFolder()); $ftp_client->put($remotefile, $tmpfile); unlink($tmpfile); } $ftp_client->close(); } catch (\Exception $e) { $state .= $line = $e . "\n"; $this->log('debug', $line); $export->incrementCrash(); $app['EM']->persist($export); $app['EM']->flush(); } $this->finalize($app, $export); }
/** * * @param record_adapter $record * @return array */ private function check_record_constraints(record_adapter $record) { $errors = []; if (!$record->get_hd_file() instanceof \SplFileInfo) { $errors["file_size"] = $this->translator->trans("Le record n'a pas de fichier physique"); } //Record must rely on real file if ($record->get_duration() > self::AUTH_VIDEO_DURATION) { $errors["duration"] = $this->translator->trans("La taille maximale d'une video est de %duration% minutes.", ['%duration%' => self::AUTH_VIDEO_DURATION / 60]); } if ($record->get_technical_infos('size') > self::AUTH_VIDEO_SIZE) { $errors["size"] = $this->translator->trans("Le poids maximum d'un fichier est de %size%", ['%size%' => p4string::format_octets(self::AUTH_VIDEO_SIZE)]); } return $errors; }
private function serializeJSON(\caption_record $caption, $includeBusinessFields) { return \p4string::jsonencode($this->toArray($caption, $includeBusinessFields)); }
/** * get duration formatted as xx:xx:xx * * @return string */ public function get_formated_duration() { return p4string::format_seconds($this->get_duration()); }
public function testGet_duration() { $this->assertEquals(p4string::format_seconds(80), $this->object->get_duration()); $this->assertInternalType(PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $this->object->get_duration()); }
public function reset_stamp($record_id = null) { $sql = 'SELECT path, file FROM record r INNER JOIN subdef s USING(record_id) WHERE r.coll_id = :coll_id AND r.type="image" AND s.name IN ("preview", "document")'; $params = [':coll_id' => $this->get_coll_id()]; if ($record_id) { $sql .= ' AND record_id = :record_id'; $params[':record_id'] = $record_id; } $stmt = $this->get_connection()->prepare($sql); $stmt->execute($params); while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) { @unlink(p4string::addEndSlash($row2['path']) . 'stamp_' . $row2['file']); } $stmt->closeCursor(); return $this; }
/** * {@inheritdoc} */ protected function doJob(JobData $data) { $app = $data->getApplication(); $settings = simplexml_load_string($data->getTask()->getSettings()); $proxy = (string) $settings->proxy; $proxyport = (string) $settings->proxyport; $localPath = (string) $settings->localpath; $ftpPath = (string) $settings->ftppath; $host = (string) $settings->host; $port = (string) $settings->port; $user = (string) $settings->user; $password = (string) $settings->password; $ssl = (bool) (string) $settings->ssl; $passive = (bool) (string) $settings->passive; foreach (['localpath' => $localPath, 'host' => $host, 'port' => $host, 'user' => $user, 'password' => $password, 'ftppath' => $ftpPath] as $name => $value) { if (trim($value) === '') { // maybe throw an exception to consider the job as failing ? $this->log('error', sprintf('setting `%s` must be set', $name)); throw new RuntimeException(sprintf('`%s` setting is empty', $name)); } } $app['filesystem']->mkdir($localPath, 0750); if (!is_dir($localPath)) { $this->log('error', sprintf('`%s` does not exists', $localPath)); throw new RuntimeException(sprintf('`%s` does not exists', $localPath)); } if (!is_writeable($localPath)) { $this->log('error', sprintf('`%s` is not writeable', $localPath)); throw new RuntimeException(sprintf('`%s` is not writeable', $localPath)); } $ftp = $app['phraseanet.ftp.client']($host, $port, 90, $ssl, $proxy, $proxyport); $ftp->passive($passive); $ftp->login($user, $password); $ftp->chdir($ftpPath); $list_1 = $ftp->list_directory(true); $done = 0; $this->log('debug', "attente de 25sec pour avoir les fichiers froids..."); $this->pause(25); if (!$this->isStarted()) { $ftp->close(); $this->log('debug', "Stopping"); return; } $list_2 = $ftp->list_directory(true); foreach ($list_1 as $filepath => $timestamp) { $done++; if (!isset($list_2[$filepath])) { $this->log('debug', "le fichier {$filepath} a disparu...\n"); continue; } if ($list_2[$filepath] !== $timestamp) { $this->log('debug', "le fichier {$filepath} a ete modifie depuis le dernier passage..."); continue; } $finalpath = \p4string::addEndSlash($localPath) . ($filepath[0] == '/' ? mb_substr($filepath, 1) : $filepath); $this->log('debug', "Rappatriement de {$filepath} vers {$finalpath}\n"); if (file_exists($finalpath)) { $this->log('debug', "Un fichier du meme nom ({$finalpath}) existe deja, skipping"); continue; } $this->log('debug', "Create " . dirname($finalpath) . ""); $app['filesystem']->mkdir(dirname($finalpath), 0750); $this->log('debug', "Get {$filepath} to {$finalpath}"); $ftp->get($finalpath, $filepath); $this->log('debug', "Remove {$filepath}"); $ftp->delete($filepath); } $ftp->close(); }