public function loginAction(Request $request, Application $app) { $username = $app->escape($request->get('username')); $password = $app->escape($request->get('password')); $rememberMe = $app->escape($request->get('rememberMe')); if (!$username || !$password) { $app->abort(Response::HTTP_BAD_REQUEST, 'Missing parameters'); } $user = $app['repository.user']->findByUsername($username); if (!$user) { $app->abort(Response::HTTP_NOT_FOUND, 'User not found'); } if (password_verify($password, $user->getPassword())) { $user->setLastSeen(new \DateTime('now')); $user->setLastIP($request->headers->get('referer')); $user->setFailedLogins(0); $app['repository.user']->save($user); //$access_query = 'SELECT user_level FROM users_access WHERE user_id = ' . $account['id']; //$access = $app['db']->fetchAssoc($access_query); $permissions = []; //foreach ($access as $accessLevel) { // array_push($permissions, $app['api.accessLevels'][$accessLevel]); //} $exp = $rememberMe ? time() + 60 * 60 * 24 * 30 : time() + 60 * 60 * 24; // expire in 30 days or 24h $user = ['id' => $user->getId(), 'username' => $user->getUsername(), 'permissions' => $permissions, 'rememberMe' => $rememberMe]; $token = $app['jwt']->createToken($request, $exp, $user); } else { $user->setFailedLogins($user->getFailedLogins() + 1); $app['repository.user']->save($user); $app->abort(Response::HTTP_FORBIDDEN, 'Wrong password'); } return json_encode(['token' => $token], JSON_NUMERIC_CHECK); }
public function view(Application $app, $folder = '', $scriptName = '', $runType = 'test') { if (!file_exists("Api/Library/Shared/Script/{$folder}/{$scriptName}.php")) { $app->abort(404, $this->website->base); // this terminates PHP } else { $userId = (string) $app['session']->get('user_id'); if (!RightsHelper::hasSiteRight($userId, Domain::PROJECTS + Operation::DELETE)) { $app->abort(403, 'You have insufficient privileges to run scripts'); // this terminates PHP } else { try { $className = "Api\\Library\\Shared\\Script\\{$folder}\\{$scriptName}"; $script = new $className(); $this->data['scriptname'] = $className . '->run()'; $this->data['insert'] = ''; $this->data['output'] = ''; if (strtolower($folder) == 'control' and strtolower($scriptName) == 'panel') { $this->data['insert'] .= $script->run($userId, $runType); } else { if ($runType != 'run') { $this->data['output'] .= "--------------- THIS IS A TEST RUN - The database should not be modified ----------------\n\n"; } $this->data['output'] .= $script->run($userId, $runType); } return $this->renderPage($app, 'textoutput'); } catch (\Exception $e) { $app->abort(500, "Looks like there was a problem with the script {$className}"); // this terminates PHP } } } }
public function getDevFile(Request $request, Application $app, $lang, $fileName) { global $rfExampleConfig; if (!isset($rfExampleConfig['devStaticPaths'][$lang])) { $app->abort(404, "Cannot find language files"); } $filePath = $rfExampleConfig['devStaticPaths'][$lang] . $fileName; if (!file_exists($filePath)) { $app->abort(404, "Cannot find file"); } $arr = explode(".", $fileName); $extension = array_pop($arr); $mime = "text/plain"; if ($extension === "css") { $mime = "text/css"; } else { if ($extension === "js") { $mime = "application/javascript"; } else { if ($extension === "html") { $mime = "text/html"; } } } return $app->sendFile($filePath, 200, array('Content-Type' => $mime)); }
protected function build($siteid, $slug, Request $request, Application $app) { $this->parameters = array('group' => null, 'venue' => null, 'country' => null); $sr = new SiteRepository(); $this->parameters['site'] = $sr->loadById($siteid); if (!$this->parameters['site']) { $app->abort(404); } $er = new EventRepository(); $this->parameters['event'] = $er->loadBySlug($this->parameters['site'], $slug); $this->parameters['eventisduplicateof'] = $this->parameters['event']->getIsDuplicateOfId() ? $er->loadById($this->parameters['event']->getIsDuplicateOfId()) : null; if (!$this->parameters['event']) { $app->abort(404); } if ($this->parameters['event']->getGroupId()) { $gr = new GroupRepository(); $this->parameters['group'] = $gr->loadById($this->parameters['event']->getGroupId()); } if ($this->parameters['event']->getCountryID()) { $cr = new CountryRepository(); $this->parameters['country'] = $cr->loadById($this->parameters['event']->getCountryID()); } if ($this->parameters['event']->getVenueID()) { $cr = new VenueRepository(); $this->parameters['venue'] = $cr->loadById($this->parameters['event']->getVenueID()); } }
protected function build($siteid, $slug, Request $request, Application $app) { $this->parameters = array('user' => null, 'eventCreated' => null, 'eventDupe' => null); $sr = new SiteRepository(); $this->parameters['site'] = $sr->loadById($siteid); if (!$this->parameters['site']) { $app->abort(404); } $repo = new NewEventDraftRepository(); $this->parameters['draft'] = $repo->loadBySlugForSite($slug, $this->parameters['site']); if (!$this->parameters['draft']) { $app->abort(404); } if ($this->parameters['draft']->getUserAccountId()) { $ur = new UserAccountRepository(); $this->parameters['user'] = $ur->loadByID($this->parameters['draft']->getUserAccountId()); } if ($this->parameters['draft']->getEventId()) { $er = new EventRepository(); $this->parameters['eventCreated'] = $er->loadByID($this->parameters['draft']->getEventId()); } if ($this->parameters['draft']->getWasExistingEventId()) { $er = new EventRepository(); $this->parameters['eventDupe'] = $er->loadByID($this->parameters['draft']->getWasExistingEventId()); } }
function listing(Silex\Application $app, $contenttypeslug) { $contenttype = $app['storage']->getContentType($contenttypeslug); // First, get some content $page = !empty($_GET['page']) ? $_GET['page'] : 1; $amount = !empty($contenttype['listing_records']) ? $contenttype['listing_records'] : $app['config']['general']['listing_records']; $content = $app['storage']->getContent($contenttype['slug'], array('limit' => $amount, 'order' => 'datepublish desc', 'page' => $page)); if (!$content) { $app->abort(404, "Content for '{$contenttypeslug}' not found."); } // Then, select which template to use, based on our 'cascading templates rules' if (!empty($contenttype['listing_template'])) { $template = $contenttype['listing_template']; } else { $filename = $app['paths']['themepath'] . "/" . $contenttype['slug'] . ".twig"; if (file_exists($filename) && is_readable($filename)) { $template = $contenttype['slug'] . ".twig"; } else { $template = $app['config']['general']['listing_template']; } } // Fallback: If file is not OK, show an error page $filename = $app['paths']['themepath'] . "/" . $template; if (!file_exists($filename) || !is_readable($filename)) { $app->abort(404, "No template for '{$contenttypeslug}' defined. Tried to use '{$template}'."); } // $app['editlink'] = path('editcontent', array('contenttypeslug' => $contenttypeslug, 'id' => $content->id)); $body = $app['twig']->render($template, array('records' => $content, $contenttype['slug'] => $content)); return new Response($body, 200, array('Cache-Control' => 's-maxage=3600, public')); }
/** * Get record detailed view * * @param Application $app * @param Request $request * * @return JsonResponse */ public function getRecord(Application $app, Request $request) { if (!$request->isXmlHttpRequest()) { $app->abort(400); } $searchEngine = $options = null; $train = ''; if ('' === ($env = strtoupper($request->get('env', '')))) { $app->abort(400, '`env` parameter is missing'); } // Use $request->get as HTTP method can be POST or GET if ('RESULT' == ($env = strtoupper($request->get('env', '')))) { try { $options = SearchEngineOptions::hydrate($app, $request->get('options_serial')); $searchEngine = $app['phraseanet.SE']; } catch (\Exception $e) { $app->abort(400, 'Search-engine options are not valid or missing'); } } $pos = (int) $request->get('pos', 0); $query = $request->get('query', ''); $reloadTrain = !!$request->get('roll', false); $record = new \record_preview($app, $env, $pos < 0 ? 0 : $pos, $request->get('cont', ''), $searchEngine, $query, $options); if ($record->is_from_reg()) { $train = $app['twig']->render('prod/preview/reg_train.html.twig', ['record' => $record]); } if ($record->is_from_basket() && $reloadTrain) { $train = $app['twig']->render('prod/preview/basket_train.html.twig', ['record' => $record]); } if ($record->is_from_feed()) { $train = $app['twig']->render('prod/preview/feed_train.html.twig', ['record' => $record]); } return $app->json(["desc" => $app['twig']->render('prod/preview/caption.html.twig', ['record' => $record, 'highlight' => $query, 'searchEngine' => $searchEngine, 'searchOptions' => $options]), "html_preview" => $app['twig']->render('common/preview.html.twig', ['record' => $record]), "others" => $app['twig']->render('prod/preview/appears_in.html.twig', ['parents' => $record->get_grouping_parents(), 'baskets' => $record->get_container_baskets($app['EM'], $app['authentication']->getUser())]), "current" => $train, "history" => $app['twig']->render('prod/preview/short_history.html.twig', ['record' => $record]), "popularity" => $app['twig']->render('prod/preview/popularity.html.twig', ['record' => $record]), "tools" => $app['twig']->render('prod/preview/tools.html.twig', ['record' => $record]), "pos" => $record->get_number(), "title" => str_replace(['[[em]]', '[[/em]]'], ['<em>', '</em>'], $record->get_title($query, $searchEngine))]); }
/** * Bootstraps the application. * * This method is called after all services are registered * and should be used for "dynamic" configuration (whenever * a service must be requested). */ public function boot(Application $app) { $this->app = $app; $app->get($app["documentation.url"] . '/', function () use($app) { $subRequest = Request::create($app["documentation.url"], 'GET'); return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST); }); $app->get($app["documentation.url"], function () use($app) { $home = $app["documentation.dir"] . '/' . $app["documentation.home"] . '.' . $app["documentation.extension"]; if (is_file($home)) { if (is_readable($home)) { $content = file_get_contents($home); return $app["DocumentationRenderer"]->render($content); } else { $app->abort("403", "Forbidden"); } } else { $app->abort("404", "Documentation Page not Found "); } }); $app->get($app["documentation.url"] . "/{pagename}", function (Request $request) use($app) { $page = $app["documentation.dir"] . '/' . $request->get('pagename') . '.' . $app["documentation.extension"]; if (is_file($page)) { if (is_readable($page)) { $content = file_get_contents($page); return $app["DocumentationRenderer"]->render($content); } else { $app->abort("403", "Forbidden"); } } else { $app->abort("404", "Documentation Page not Found "); } })->assert('pagename', '[a-zA-Z0-9-/]*')->value("pagename", "index"); }
/** * Get entity class * * @param string $modelName * @return string */ public function getClass($modelName) { // Returns a string with the first character of str capitalized $modelName = ucfirst($modelName); $class = "\\{$this->app['config']['parameters']['db.models.namespace']}\\{$modelName}"; if (!class_exists($class)) { $this->app->abort(404, "Not declared class \"{$class}\""); } return $class; }
/** * Invalidate our database check by removing the timestamp file from cache. * * @return void */ public function invalidate() { $fileName = $this->getValidityTimestampFilename(); // delete the cached dbcheck-ts if (is_writable($fileName)) { unlink($fileName); } elseif (file_exists($fileName)) { $message = sprintf("The file '%s' exists, but couldn't be removed. Please remove this file manually, and try again.", $fileName); $this->app->abort(Response::HTTP_UNAUTHORIZED, $message); } }
/** * Действие для страницы категории * * @param string $url URL категории * * @throws \Symfony\Component\HttpKernel\Exception\HttpException * * @return string */ public function categoryAction($url) { $category = $this->catalogModel->getCategory($url); if (!$category) { $this->app->abort(404, "Категория c URL '{$url}' не найдена"); } $products = $this->catalogModel->getProductsByCategoryId($category['id']); foreach ($products as &$product) { $product['price'] = $this->catalogModel->convertPrice($product['price']); } return $this->view->render('catalog/category.phtml', array('category' => $category, 'products' => $products)); }
/** * Get service for ZF * * @param mixed $service * @return mixed */ public function get($service) { $method = 'get'; $service = strtolower($service); $arService = explode('_', $service); foreach ($arService as $item) { $method .= ucfirst($item); } if (method_exists($this, $method)) { return $this->{$method}(); } else { $this->app->abort(404, "Service {$service} not Found"); } }
protected function build($siteid, $fieldid, Request $request, Application $app) { $this->parameters = array(); $sr = new SiteRepository(); $this->parameters['site'] = $sr->loadById($siteid); if (!$this->parameters['site']) { $app->abort(404); } $repo = new EventCustomFieldDefinitionRepository(); $this->parameters['field'] = $repo->loadBySiteIDAndID($this->parameters['site']->getId(), $fieldid); if (!$this->parameters['field']) { $app->abort(404); } }
public function connect(Application $app) { $app['controller.rss-feeds'] = $this; $controllers = $app['controllers_factory']; $controllers->get('/feed/{id}/{format}/', function (Application $app, $id, $format) { $feed = $app['EM']->getRepository('Phraseanet:Feed')->find($id); if (null === $feed) { $app->abort(404, 'Feed not found'); } if (!$feed->isPublic()) { $app->abort(403, 'Forbidden'); } $request = $app['request']; $page = (int) $request->query->get('page'); $page = $page < 1 ? 1 : $page; return $app['feed.formatter-strategy']($format)->createResponse($app, $feed, $page); })->bind('feed_public')->assert('id', '\\d+')->assert('format', '(rss|atom)'); $controllers->get('/userfeed/{token}/{id}/{format}/', function (Application $app, $token, $id, $format) { $token = $app["EM"]->find('Phraseanet:FeedToken', $id); $request = $app['request']; $page = (int) $request->query->get('page'); $page = $page < 1 ? 1 : $page; return $app['feed.formatter-strategy']($format)->createResponse($app, $token->getFeed(), $page, $token->getUser()); })->bind('feed_user')->assert('id', '\\d+')->assert('format', '(rss|atom)'); $controllers->get('/userfeed/aggregated/{token}/{format}/', function (Application $app, $token, $format) { $token = $app['EM']->getRepository('Phraseanet:AggregateToken')->findOneBy(["value" => $token]); $user = $token->getUser(); $feeds = $app['EM']->getRepository('Phraseanet:Feed')->getAllForUser($app['acl']->get($user)); $aggregate = new Aggregate($app['EM'], $feeds, $token); $request = $app['request']; $page = (int) $request->query->get('page'); $page = $page < 1 ? 1 : $page; return $app['feed.formatter-strategy']($format)->createResponse($app, $aggregate, $page, $user); })->bind('feed_user_aggregated')->assert('format', '(rss|atom)'); $controllers->get('/aggregated/{format}/', function (Application $app, $format) { $feed = Aggregate::getPublic($app); $request = $app['request']; $page = (int) $request->query->get('page'); $page = $page < 1 ? 1 : $page; return $app['feed.formatter-strategy']($format)->createResponse($app, $feed, $page); })->bind('feed_public_aggregated')->assert('format', '(rss|atom)'); $controllers->get('/cooliris/', function (Application $app) { $feed = Aggregate::getPublic($app); $request = $app['request']; $page = (int) $request->query->get('page'); $page = $page < 1 ? 1 : $page; return $app['feed.formatter-strategy']('cooliris')->createResponse($app, $feed, $page, null, 'Phraseanet', $app); })->bind('feed_public_cooliris'); return $controllers; }
protected function build($siteid, $id, Request $request, Application $app) { $this->parameters = array(); $sr = new SiteRepository(); $this->parameters['site'] = $sr->loadById($siteid); if (!$this->parameters['site']) { $app->abort(404); } $sr = new UserGroupRepository(); $this->parameters['usergroup'] = $sr->loadByIdInSite($id, $this->parameters['site']); if (!$this->parameters['usergroup']) { $app->abort(404); } }
protected function build($siteid, $slug, Request $request, Application $app) { $this->parameters = array('group' => null); $sr = new SiteRepository(); $this->parameters['site'] = $sr->loadById($siteid); if (!$this->parameters['site']) { $app->abort(404); } $clr = new CuratedListRepository(); $this->parameters['curatedlist'] = $clr->loadBySlug($this->parameters['site'], $slug); if (!$this->parameters['curatedlist']) { $app->abort(404); } }
protected function build($siteid, $slug, Request $request, Application $app) { $this->parameters = array('group' => null); $sr = new SiteRepository(); $this->parameters['site'] = $sr->loadById($siteid); if (!$this->parameters['site']) { $app->abort(404); } $vr = new VenueRepository(); $this->parameters['venue'] = $vr->loadBySlug($this->parameters['site'], $slug); if (!$this->parameters['venue']) { $app->abort(404); } $this->parameters['venueisduplicateof'] = $this->parameters['venue']->getIsDuplicateOfId() ? $vr->loadById($this->parameters['venue']->getIsDuplicateOfId()) : null; }
public function index(Application $app, $firstChar, $page) { //Page number 0 or below if ($page <= 0) { $redirectUrl = "/a-z/{$firstChar}/1"; return $app->redirect($redirectUrl); } $data = $app['programme_api']->fetchPageData($firstChar, $page); $successfulRequest = $data[0]; if ($successfulRequest) { $pageData = $data[1]; $totalProgrammes = $pageData->atoz_programmes->count; if ($totalProgrammes == 0) { return $app['twig']->render('no-results.twig', array()); } $perPage = $pageData->atoz_programmes->per_page; $numberOfPages = ceil($totalProgrammes / $perPage); if ($page > $numberOfPages) { //Page number is past last page $redirectUrl = "/a-z/{$firstChar}/{$numberOfPages}"; return $app->redirect($redirectUrl); } else { $programmes = $pageData->atoz_programmes->elements; return $app['twig']->render('az.twig', array('firstChar' => $firstChar, 'numOfPages' => $numberOfPages, 'pageNo' => $page, 'programmes' => $programmes, 'imageSize' => '240x135')); } } else { $error = $data[1]; $app->abort(500, 'jooooo'); } }
public function register(Application $app) { $app['public-vendor.css'] = 'text/css'; $app['public-vendor.js'] = 'application/javascript'; $app['public-vendor.html'] = 'text/html'; $app['public-vendor.eot'] = 'application/vnd.ms-fontobject'; $app['public-vendor.svg'] = 'image/svg+xml'; $app['public-vendor.ttf'] = 'application/x-font-ttf'; $app['public-vendor.woff'] = 'application/font-woff'; $app['public-vendor.jpg'] = 'image/jpeg'; $app['public-vendor.png'] = 'image/png'; $app['public-vendor.jpeg'] = 'image/jpeg'; $app['public-vendor.gif'] = 'image/gif'; $app['public-vendor.ico'] = 'image/x-icon'; $app['public-vendor'] = $app->share(function () use($app) { return new Container(); }); $app['public-vendor.response'] = $app->protect(function ($file) use($app) { $name = 'public-vendor.' . strtolower(pathinfo($file, PATHINFO_EXTENSION)); if (!file_exists($file) || !isset($app[$name])) { $app->abort(404, "Not found"); } return $app->sendFile($file, 200, array('Content-type' => $app[$name])); }); }
/** * @param \Silex\Application $app * This function can return listing of node. */ public function show(Application $app) { header("Content-Type: text/html; charset=UTF-8"); $client = $app['elasticsearch']; $search = $_GET['recherche']; $params['index'] = 'elasticsearch_index_csoecsic_content'; $params['type'] = 'content'; $ret = $client->indices()->getMapping(array('index' => 'elasticsearch_index_csoecsic_content')); $params['body']['query']['match']['_all'] = $search; $result = $client->search($params); // If no result from node Elasticsearch. if ($result && $result['hits']['total'] === 0) { $app->abort(404, sprintf('Node %s does not exist.', $search)); } // If result from node Elasticsearch. if ($result['hits']['total'] > 0) { $nodes = $result['hits']['hits']; } else { print 'no result for this search'; } $output['title_doc'] = 'Le contenu le plus pertinent :' . $nodes[0]['_source']['title'] . ''; $output['score'] = 'Le meilleurs résultat de la recherche est :' . $nodes[0]['_score'] . ''; //return '<p>Le contenu le plus pertinent :' . $nodes[0]['_source']['title'] . '</p>' . '<p>Avec comme score :' . $nodes[0]['_score'] . '</p>'; /*return $app->render('template/result.php', array('node' => reset($output)));*/ return $app['twig']->render('index.html.twig', ['result' => $output]); }
/** * @param Application $app * * @return Response */ public function indexAction(Application $app) { if (!$app['security']->isGranted('ROLE_ADMIN')) { $app->abort(403); } return new Response($app['twig']->render('contents/members-area/statistics/index.html.twig')); }
/** * 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); }
public function detail(Request $request, Application $app, $hash) { if (!isset($hash)) { throw new Exception("Parâmetros inválidos", 1); } $share = $app['orm.em']->getRepository('Orcamentos\\Model\\Share')->findOneBy(array('hash' => $hash)); if (!$share) { $app->abort(404, "Compartilhamento não existente"); } $shareId = $share->getId(); $view = new ViewModel(); $view->setShare($share); $app['orm.em']->persist($view); $app['orm.em']->flush(); $quote = $share->getQuote(); $resourceCollection = $quote->getResourceQuoteCollection(); $shareCollection = $quote->getShareCollection(); $shareNotesCollection = array(); foreach ($shareCollection as $sc) { $notes = $sc->getShareNotesCollection(); foreach ($notes as $note) { $shareNotesCollection[] = $note; } } usort($shareNotesCollection, $app['sortCreated']); $city = $quote->getProject()->getCompany()->getCity(); $createdSignature = $this->createdSignature($quote->getCreated(), $city); return $app['twig']->render('share/detail.twig', array('quote' => $quote, 'resourceCollection' => $resourceCollection, 'createdSignature' => $createdSignature, 'shareNotesCollection' => $shareNotesCollection, 'shareId' => $shareId)); }
protected function build($id, Request $request, Application $app) { $this->parameters['extension'] = $app['extensions']->getExtensionById($id); if (!$this->parameters['extension']) { $app->abort(404); } }
/** * 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); }
public function connect(Application $app) { $route = $app['controllers_factory']; $route->get('{repo}/tree/{commitishPath}/', $treeController = function ($repo, $commitishPath = '') use($app) { $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo); if (!$commitishPath) { $commitishPath = $repository->getHead(); } list($branch, $tree) = $app['util.routing']->parseCommitishPathParam($commitishPath, $repo); list($branch, $tree) = $app['util.repository']->extractRef($repository, $branch, $tree); $files = $repository->getTree($tree ? "{$branch}:\"{$tree}\"/" : $branch); $breadcrumbs = $app['util.view']->getBreadcrumbs($tree); $parent = null; if (($slash = strrpos($tree, '/')) !== false) { $parent = substr($tree, 0, $slash); } elseif (!empty($tree)) { $parent = ''; } return $app['twig']->render('tree.twig', array('files' => $files->output(), 'repo' => $repo, 'branch' => $branch, 'path' => $tree ? $tree . '/' : $tree, 'parent' => $parent, 'breadcrumbs' => $breadcrumbs, 'branches' => $repository->getBranches(), 'tags' => $repository->getTags(), 'readme' => $app['util.repository']->getReadme($repository, $branch, $tree ? "{$tree}" : ""))); })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('commitishPath', $app['util.routing']->getCommitishPathRegex())->convert('commitishPath', 'escaper.argument:escape')->bind('tree'); $route->post('{repo}/tree/{branch}/search', function (Request $request, $repo, $branch = '', $tree = '') use($app) { $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo); if (!$branch) { $branch = $repository->getHead(); } $query = $request->get('query'); $breadcrumbs = array(array('dir' => 'Search results for: ' . $query, 'path' => '')); $results = $repository->searchTree($query, $branch); return $app['twig']->render('search.twig', array('results' => $results, 'repo' => $repo, 'branch' => $branch, 'path' => $tree, 'breadcrumbs' => $breadcrumbs, 'branches' => $repository->getBranches(), 'tags' => $repository->getTags(), 'query' => $query)); })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('branch', $app['util.routing']->getBranchRegex())->convert('branch', 'escaper.argument:escape')->bind('search'); $route->get('{repo}/{format}ball/{branch}', function ($repo, $format, $branch) use($app) { $repository = $app['git']->getRepositoryFromName($app['git.repos'], $repo); $tree = $repository->getBranchTree($branch); if (false === $tree) { return $app->abort(404, 'Invalid commit or tree reference: ' . $branch); } $file = $app['cache.archives'] . DIRECTORY_SEPARATOR . $repo . DIRECTORY_SEPARATOR . substr($tree, 0, 2) . DIRECTORY_SEPARATOR . substr($tree, 2) . '.' . $format; if (!file_exists($file)) { $repository->createArchive($tree, $file, $format); } /** * Generating name for downloading, lowercasing and removing all non * ascii and special characters */ $filename = strtolower($branch); $filename = preg_replace('#[^a-z0-9]#', '_', $filename); $filename = preg_replace('#_+#', '_', $filename); $filename = $filename . '.' . $format; $response = new BinaryFileResponse($file); $response->setContentDisposition('attachment', $filename); return $response; })->assert('format', '(zip|tar)')->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('branch', $app['util.routing']->getBranchRegex())->convert('branch', 'escaper.argument:escape')->bind('archive'); $route->get('{repo}/{branch}/', function ($repo, $branch) use($app, $treeController) { return $treeController($repo, $branch); })->assert('repo', $app['util.routing']->getRepositoryRegex())->assert('branch', $app['util.routing']->getBranchRegex())->convert('branch', 'escaper.argument:escape')->bind('branch'); $route->get('{repo}/', function ($repo) use($app, $treeController) { return $treeController($repo); })->assert('repo', $app['util.routing']->getRepositoryRegex())->bind('repository'); return $route; }
public function checkIfTokenIsPresentAndLikeAVirgin(Request $request) { // Authorization shouldn't being able to be retrieve here, but rewrite magic happen in vhost configuration $authorizationHeader = $request->headers->get('Authorization'); if ($authorizationHeader == null) { $this->app->abort(Response::HTTP_UNAUTHORIZED, 'No authorization header sent'); } // $authorizationHeader should be in that form: Bearer THE_TOKEN $token = explode(' ', $authorizationHeader)[1]; try { $this->decodedToke = JWT::decode($token, $this->secretKey, array('HS256')); } catch (UnexpectedValueException $ex) { $this->app->abort(Response::HTTP_UNAUTHORIZED, 'Invalid token'); } return $decoded_token; }
public function editGoodsClassAjaxAction(Request $request, Application $app) { $goodsClassId = $request->query->get('goodsClassId'); $goodsClass = new GoodsClass(); $goodsClass->setId($goodsClassId); $resultFindById = $app['repository.goodsClass']->findById($goodsClass); if (!$resultFindById) { $app->abort(404, '没有找到此资源大类'); } $form = $app['form.factory']->create(new SaveGoodsClassType(), $resultFindById); $form->handleRequest($request); if ($request->isMethod('POST')) { if ($form->isValid()) { $resultSave = $app['repository.goodsClass']->save($resultFindById); if ($resultSave) { $msg = '修改成功。'; $url = '/admin/goodsClassList'; CommonFunc::alertHref($msg, $url); return; } else { $msg = '修改失败,请重试。'; CommonFunc::alertBack($msg); return; } } } $data = array('form' => $form->createview(), 'title' => '资源大类修改'); return $app['twig']->render('admin/saveGoodsClass.html.twig', $data); }
public function generateAction(Application $app, Request $req, $arguments) { $expectedWidth = $arguments['width']; $expectedHeight = $arguments['height']; $largestSide = max($expectedWidth, $expectedHeight); $base = ImageWorkshop::initFromPath($arguments['file']); $base->cropMaximumInPixel(0, 0, "MM"); $base->resizeInPixel($largestSide, $largestSide); $base->cropInPixel($expectedWidth, $expectedHeight, 0, 0, 'MM'); $fileName = basename($arguments['file']); if (!$arguments['on_the_fly']) { $folder = $arguments['web_root'] . $arguments['mount'] . '/' . $arguments['width'] . 'x' . $arguments['height']; $base->save($folder, $fileName, true); $arguments['logger'](Logger::DEBUG, "File saved in '{$folder}/{$fileName}'"); } $ext = strtolower(pathinfo($arguments['file'], PATHINFO_EXTENSION)); if ($ext == 'jpg') { $ext = 'jpeg'; } $mimeType = 'image/' . $ext; $func = 'image' . $ext; if (!function_exists($func)) { $arguments['logger'](Logger::CRITICAL, "How this possible?"); $app->abort(404); } //I don't know any way to pass an image resource to symfony Response object. ob_start(); $func($base->getResult()); $result = ob_get_clean(); return new Response($result, 200, array('Content-Type' => $mimeType, 'Content-Disposition' => 'filename="' . $fileName . '"')); }
/** * Save the model to the database. * * @param boolean $validate Set to true or false depending on if you want the validators to run or not * @return array */ public function saveModel($validate = true) { if (!$this->save($validate)) { $strErr = implode("<br>\n", $this->errors->full_messages()); $this->app->abort(405, "Failed to save record \"{$strErr}\""); } }