public function __invoke(Request $req, Response $res) { $school = $req->getAttribute('school'); $appForm = $this->appFormService->findSchoolApplicationForm($school->id); if (null === $appForm) { return $res->withStatus(404); } $html = $this->view->fetch('application_form/pdf.twig', ['school' => $school, 'appForm' => $appForm, 'logo' => base64_encode(file_get_contents(__DIR__ . '/../../public/img/application_form/minedu_logo.jpg')), 'style' => file_get_contents(__DIR__ . '/../../public/css/application_form/pdf.css')]); $pdf = new \Dompdf\Dompdf(['default_paper_size' => 'A4', 'default_font' => 'DejaVu Sans', 'isHtml5ParserEnabled' => true, 'is_remote_enabled' => false]); $pdf->loadHtml($html); $pdf->render(); $filename = 'edulabs_app_form_' . $appForm['id'] . '.pdf'; $str = $pdf->output(); $length = mb_strlen($str, '8bit'); return $res->withHeader('Cache-Control', 'private')->withHeader('Content-type', 'application/pdf')->withHeader('Content-Length', $length)->withHeader('Content-Disposition', 'attachment; filename=' . $filename)->withHeader('Accept-Ranges', $length)->write($str); }
public function __invoke(Request $req, Response $res) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $teacherId = $req->getParam('teacher_id'); $teacher = $this->staffService->getTeacherById($teacherId); if ($teacher['school_id'] !== $school->id) { return $res->withStatus(403, 'No school'); } if ($req->isPost()) { $inputFilter = $this->inputFilter; $result = $inputFilter($req->getParams()); if (!$result['is_valid']) { $res = $res->withStatus(422); $res = $res->withJson($result); return $res; } $this->service->saveAnswers($teacherId, $result['values']); } $data = $this->service->getAnswers($teacherId); $res = $res->withJson($data); return $res; }
public function writeUnauthorized() { $this->response = $this->response->withStatus(401); $apiResponse = new ApiResponse(); $apiResponse->setStatusFail(); $apiResponse->setData("Unauthorized"); $this->body->write($apiResponse->toJSON()); }
public function __invoke(Request $req, Response $res) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $this->service->setTotalTeachers($school->id, (int) $req->getParam('total_teachers', 0)); return $res->withStatus(204); }
public function __invoke(Request $request, Response $response, $next) { $this->request = $request; $this->response = $response; $dsn = sprintf(self::PDO_DSN, $this->type, $this->name, $this->server); try { $this->connection = new PDO($dsn, $this->username, $this->password); } catch (PDOException $e) { $this->response->withStatus(500, $e->getMessage()); } $next($request, $response); return $response; }
public function dispatch(Request $request, Response $response, $args) { if ($request->isPost()) { $speaker = new Speaker(null, $request->getParam('first_name'), $request->getParam('last_name'), new Email($request->getParam('email')), new Twitter($request->getParam('twitter'))); $msg = []; try { $this->speakersRepository->save($speaker); $msg['id'] = $speaker->id; } catch (\Exception $e) { return $response->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode(['error' => $e->getMessage()])); } return $response->withStatus(201)->withHeader('Content-Type', 'application/json')->write(json_encode($msg)); } }
/** * Execute the middleware. * * @param \Slim\Http\Request $req * @param \Slim\Http\Response $res * @param callable $next * @return \Slim\Http\Response */ public function __invoke(Request $req, Response $res, callable $next) { $uri = $req->getUri(); $path = $this->filterTrailingSlash($uri); if ($uri->getPath() !== $path) { return $res->withStatus(301)->withHeader('Location', $path)->withBody($req->getBody()); } // if ($this->filterBaseurl($uri)) { // return $res->withStatus(301) // ->withHeader('Location', (string) $uri) // ->withBody($req->getBody()); // } $server = $req->getServerParams(); if (!isset($server['REQUEST_TIME_FLOAT'])) { $server['REQUEST_TIME_FLOAT'] = microtime(true); } $uri = $uri->withPath($path); $req = $this->filterRequestMethod($req->withUri($uri)); $res = $next($req, $res); $res = $this->filterPrivateRoutes($uri, $res); // Only provide response calculation time in non-production env, tho. if ($this->settings['mode'] !== 'production') { $time = (microtime(true) - $server['REQUEST_TIME_FLOAT']) * 1000; $res = $res->withHeader('X-Response-Time', sprintf('%2.3fms', $time)); } return $res; }
public function product_youtubePostAdd(Request $req, Response $res, $attr = []) { $container = $this->slim->getContainer(); $db = $container->medoo; $postBody = $req->getParsedBody(); // $insertParams = $this->adapterParams($postBody); $insertParams = []; $insertParams["product_id"] = $attr["product_id"]; $insertParams["type"] = "youtube"; $insertParams["youtube_id"] = $postBody["youtube_id"]; $insertParams["sort_order"] = $db->max("product_media", "sort_order", ["AND" => ["product_id" => $attr["product_id"]]]) + 1; if (!$db->insert("product_media", $insertParams)) { return $res->withStatus(500)->withHeader('Content-Type', 'application/json')->write(json_encode(["error" => true])); } return $res->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode(["success" => true])); }
public function __invoke(Request $req, Response $res, array $args = []) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $params = $req->getParams(); $id = $params['id']; $params['school_id'] = $school->id; if (isset($params['lessons']) && !is_array($params['lessons'])) { $params['lessons'] = explode(',', $params['lessons']); } unset($params['id']); try { if ($id) { $lab = $this->labservice->updateLab($params, $id); $res = $res->withStatus(200); } else { $lab = $this->labservice->createLab($params); $res = $res->withStatus(201); } $res = $res->withJson($lab); } catch (Exception $ex) { $res = $res->withStatus(500, $ex->getMessage()); } return $res; }
public function __invoke(Request $req, Response $res) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $lab_id = $req->getParam('lab_id', false); if (!$lab_id) { return $res->withStatus(404, 'No lab id'); } $lab = $this->labService->getLabForSchool($school->id, $lab_id); try { $this->labService->removeLabAttachment($lab['id']); return $res->withStatus(204); } catch (Exception $ex) { return $res->withStatus(500, $ex->getMessage()); } }
public function dispatch(Request $request, Response $response, $args) { $meetupID = $request->getAttribute('meetup_id', null); $eventInfo = $this->eventService->getInfoByMeetupID($meetupID); if ($eventInfo->eventExists()) { $this->flash->addMessage('event', 'Event already exists. Check its status.'); return $response->withStatus(302)->withHeader('Location', 'event-details/' . $meetupID); } if (!$eventInfo->isRegistered() && !is_null($meetupID)) { $this->flash->addMessage('event', 'No event found for meetupID provided. Please create a new event.'); return $response->withStatus(302)->withHeader('Location', 'create-event'); } $form = new CreateEventForm($this->eventManager, $this->eventService); if ($eventInfo->isRegistered()) { $form->setEventInfo($eventInfo); } $data = ['form' => $form, 'errors' => $this->flash->getMessage('event') ?? [], 'defaultTime' => $this->eventsConfig->defaultStartTime]; if ($request->isPost()) { $form->populate($request->getParams()); if (!$form->isValid()) { // return response $data['errors'] = $form->getErrors(); $data = array_merge($data, $this->getCsrfValues($request)); $response->withStatus(304); $this->view->render($response, 'admin/create-event.twig', $data); return $response; } try { $event = EventFactory::getEvent($form->getTalkTitle(), $form->getTalkDescription(), $form->getEventDate(), $form->getSpeaker(), $form->getVenue(), $form->getSupporter(), $this->eventsConfig->title, $this->eventsConfig->description); $createEventInfo = $this->eventService->createMainEvents($event, $this->auth->getUserId(), $meetupID); if (!is_null($createEventInfo['joindin_message'])) { $this->flash->addMessage('event', $createEventInfo['joindin_message']); } return $response->withStatus(302)->withHeader('Location', 'event-details?meetup_id=' . $createEventInfo['meetup_id']); } catch (\Exception $e) { $this->logger->debug($e->getMessage()); $this->logger->debug(print_r($data['errors'], true)); $data['errors'] = array_merge($data['errors'], [$e->getMessage()]); } } $data = array_merge($data, $this->getCsrfValues($request)); $this->view->render($response, 'admin/create-event.twig', $data); return $response; }
public function __invoke(Request $request, Response $response, $args) { $this->request =& $request; if ($this->execute($args)) { $responder = new $this->responder($response, $this->responseInfo); return $responder(); } else { return $response->withStatus(self::STATUS_NOT_FOUND); } }
/** * @param Request $req * @param Response $res * @param $args * @throws \BadMethodCallException * @return Response */ public function declineFriendshipRequest(Request $req, Response $res, $args) { $toUserId = (int) $args['userId']; $fromUserId = (int) $req->getParam('fromUserId'); if (empty($fromUserId)) { throw new \BadMethodCallException("POST param 'fromUserId' is required"); } $this->friendship->declineFriendshipRequest($fromUserId, $toUserId); return $res->withStatus(200); }
public function __invoke(Request $req, Response $res, array $args = []) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $staff = $this->staffService->getTeachersBySchoolId($school->id); return $this->view->render($res, 'schools/staff.twig', ['school' => $school, 'staff' => $staff, 'branches' => array_map(function ($branch) { return ['value' => $branch['id'], 'label' => $branch['name']]; }, $this->staffService->getBranches())]); }
/** * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Slim\Http\Response $response * * @return \Slim\Http\Response * @throws \livetyping\hermitage\app\exceptions\BadRequestException */ public function __invoke(Request $request, Response $response) : Response { $mime = (string) current($request->getHeader('Content-Type')); $binary = (string) $request->getBody(); if (empty($mime) || empty($binary) || !in_array($mime, Util::supportedMimeTypes())) { throw new BadRequestException('Invalid mime-type or body.'); } $command = new StoreImageCommand($mime, $binary); $this->bus->handle($command); return $response->withStatus(201)->withJson(['filename' => $command->getPath()]); }
public function p(Request $request, Response $response, $args) { /* @var \App\models\Photo $photo */ $photo = $this->model->load('Photo'); $output = $photo->filter(['id' => $args['id'], 'user_id' => $this->user['id']])->fetch(); if (!$output) { $this->flash->addError('home', 'Photo not exists.'); return $response->withStatus(302)->withHeader('Location', $this->router->pathFor('home')); } return $this->renderer->render($response, 'p.html', $output); }
public function dispatch(Request $request, Response $response, $args) { if (isset($args['callback']) && $args['callback'] === 'joindin') { // if logged in if ($this->auth->isLoggedIn() && strlen($request->getParam('access_token', '')) > 0) { // store token $this->fileRepository->save($this->auth->getUserId() . '_joindin', $request->getParam('access_token')); } } return $response->withStatus(302)->withHeader('Location', '/'); }
/** * @param string $repo * @param string $file * @param int $width * @param bool $archived * @param \Slim\Http\Response $response * @return mixed */ function thumb($repo, $file, $width, $archived, $response, $format) { $md5 = md5($file); $file = $md5[0] . '/' . $md5[0] . $md5[1] . '/' . $file; $path = $repo . ($archived ? 'archive/' : '') . $file; if (is_readable($path)) { $path = realpath($path); $pathParts = pathinfo($path); if (strpos($pathParts['dirname'], $repo) === 0) { $cacheDir = $repo . 'thumb/' . ($archived ? 'archive/' : '') . $file; if (!is_dir($cacheDir)) { if (!mkdir($cacheDir, 0777, true)) { return $response->withStatus(403); } } if ($format != 'jpg') { $cacheFile = $cacheDir . '/' . $width . 'px-' . $pathParts['basename']; } else { $cacheFile = $cacheDir . '/' . $width . 'px-' . $pathParts['filename'] . '.jpg'; } if (!is_readable($cacheFile)) { $image = new ImageResize($path); if ($width > $image->getSourceWidth()) { return $response->withRedirect('/images/' . $file); } else { $image->resizeToWidth($width); if ($format != 'jpg') { $image->save($cacheFile); } else { $image->save($cacheFile, IMAGETYPE_JPEG); } } } $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $cacheFile); $stream = new \GuzzleHttp\Psr7\LazyOpenStream($cacheFile, 'r'); return $response->withHeader('Content-type', $type)->withBody($stream); } } return $response->withStatus(404); }
public function __invoke(Request $req, Response $res) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $lab_id = $req->getParam('lab_id', false); if (!$lab_id) { return $res->withStatus(404, 'No lab id'); } $lab = $this->labService->getLabForSchool($school->id, $lab_id); if ($lab['attachment'] && is_readable($this->uploadDir . '/' . $lab['attachment'])) { $contents = file_get_contents($this->uploadDir . '/' . $lab['attachment']); $contentType = $lab['attachment_mime'] ? $lab['attachment_mime'] : 'application/octet-stream'; $res = $res->withHeader('Content-Type', $contentType); $res = $res->withHeader('Content-Disposition', 'filename="' . basename($lab['attachment']) . '"'); $res->getBody()->write($contents); } else { $res->withStatus(404, 'No attachment'); } return $res; }
/** * withJson * support JSONP * * @return void */ public static function withJson(Response $response, $data, $status = 200, $encodingOptions = 0) { $body = $response->getBody(); $body->rewind(); $s = json_encode($data, $encodingOptions); $type = "application/json"; // check jsonp callback if (!empty($_GET) && !empty($_GET['callback'])) { $s = $_GET['callback'] . "({$s});"; $type = "text/javascript"; } $body->write($s); return $response->withStatus($status)->withHeader('Content-Type', $type . ';charset=utf-8'); }
public function dispatch(Request $request, Response $response, $args) { // ONLY WHEN CALLED THROUGH CLI if (PHP_SAPI !== 'cli') { return $response->withStatus(404)->withHeader('Location', '/404'); } if (!$request->getParam('event')) { return $response->withStatus(404)->withHeader('Location', '/404'); } // Default UserID for the required auth token $userID = 1; // Create talks for approved events try { $result = $this->eventsService->manageApprovedEvents($userID); $this->logger->info(__CLASS__ . ' :: ' . $result); echo $result; echo PHP_EOL; } catch (\Exception $e) { echo __CLASS__ . ' :: ERROR :: ' . $e->getMessage() . PHP_EOL; $this->logger->alert(__CLASS__ . ' :: ' . $e->getMessage()); } exit; }
public function __invoke(Request $req, Response $res, array $args = []) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $labs = $this->labservice->getLabsBySchoolId($school->id); $software = $this->softwareService->getSoftwareBySchoolId($school->id); $categories = $this->softwareService->getSoftwareCategories(); return $this->view->render($res, 'schools/software.twig', ['school' => $school, 'labs' => array_map(function ($lab) { return ['value' => $lab['id'], 'label' => $lab['name']]; }, $labs), 'softwareArray' => $software, 'categories' => array_map(function ($category) { return ['value' => $category['id'], 'label' => $category['name']]; }, $categories)]); }
public function __invoke(Request $req, Response $res, array $args = []) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $assets = $this->schoolAssetsService->getAssetsForSchool($school->id); $itemCategories = $this->assetsService->getAllItemCategories(); $labs = $this->labService->getLabsBySchoolId($school->id); return $this->view->render($res, 'schools/assets.twig', ['school' => $school, 'assets' => $assets, 'item_categories' => array_map(function ($category) { return ['value' => $category['id'], 'label' => $category['name']]; }, $itemCategories), 'labs' => array_map(function ($lab) { return ['value' => $lab['id'], 'label' => $lab['name']]; }, array_filter($labs, function ($lab) { return $lab['is_new'] !== "1"; }))]); }
public function __invoke(Request $req, Response $res) { $identity = $this->authService->getIdentity(); if (null === $identity) { return $res; } $user = R::load('user', $identity->id); if (!$user->school_id) { return $res; } $school_id = $user->school_id; $sync = $this->syncFromInventory; $result = $sync($school_id); if (false === $result) { return $res->withStatus(500); } return $res->withJson($result); }
public function __invoke(Request $req, Response $res) { $school = $req->getAttribute('school', false); if (!$school->id) { return $res->withStatus(403, 'No school'); } $id = $req->getParam('id', false); if (!$id) { $res = $res->withStatus(404); return $res; } try { $this->schoolAssetsService->removeAssetFromSchool($school->id, $id); $res = $res->withStatus(204); } catch (Exception $ex) { $res = $res->withStatus(500, $ex->getMessage()); } return $res; }
public function __invoke(Request $req, Response $res, array $args = []) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $labs = $this->labService->getLabsBySchoolId($school->id); return $this->view->render($res, 'schools/labs.twig', ['school' => $school, 'labs' => $labs, 'staff' => array_map(function ($teacher) { return ['value' => $teacher['id'], 'label' => $teacher['fullname']]; }, $this->staffService->getTeachersBySchoolId($school->id)), 'network_options' => array_map(function ($option) { return ['value' => $option, 'label' => $option]; }, $this->labService->getHasNetworkValues()), 'server_options' => array_map(function ($option) { return ['value' => $option, 'label' => $option]; }, $this->labService->getHasServerValues()), 'lab_types' => array_map(function ($type) { return ['value' => $type['id'], 'label' => $type['name']]; }, $this->labService->getLabTypes()), 'lessons_options' => array_map(function ($lesson) { return ['value' => $lesson['id'], 'label' => $lesson['name']]; }, $this->labService->getLessons())]); }
/** * Invoke middleware. * * @param RequestInterface $req PSR7 request object * @param ResponseInterface $res PSR7 response object * @param callable $next Next middleware callable * * @return ResponseInterface PSR7 response object */ public function __invoke(Request $req, Response $res, callable $next) { if (!$req->getAttribute('route')) { return $res->withStatus(404); } $isAllowed = false; if ($this->acl->hasResource('route' . $req->getAttribute('route')->getPattern())) { $isAllowed = $isAllowed || $this->acl->isAllowed($this->currentUserRole, 'route' . $req->getAttribute('route')->getPattern(), strtolower($req->getMethod())); } if (is_string($req->getAttribute('route')->getCallable()) && $this->acl->hasResource('callable/' . $req->getAttribute('route')->getCallable())) { $isAllowed = $isAllowed || $this->acl->isAllowed($this->currentUserRole, 'callable/' . $req->getAttribute('route')->getCallable()); } if (!$isAllowed && $this->currentUserRole === $this->defaultRole) { return $res->withRedirect($this->loginUrl); } if (!$isAllowed) { $res = $res->withStatus(403, $this->currentUserRole . ' is not allowed access to this location.'); $res->getBody()->write('Forbidden'); return $res; } return $next($req, $res); }
public function dispatch(Request $request, Response $response, $args) { // CSRF token name and value $nameKey = $this->csrf->getTokenNameKey(); $valueKey = $this->csrf->getTokenValueKey(); $name = $request->getAttribute($nameKey); $value = $request->getAttribute($valueKey); $email = ''; $msg = ''; if ($request->isPost()) { $email = $request->getParam('email'); $password = $request->getParam('password'); if ($this->auth->isValid($email, $password)) { $this->auth->store(); return $response->withStatus(302)->withHeader('Location', '/'); } else { $msg = 'Incorrect email or password.'; } } $this->view->render($response, 'login.twig', ['nameKey' => $nameKey, 'valueKey' => $valueKey, 'name' => $name, 'value' => $value, 'email' => $email, 'msg' => $msg]); return $response; }
public function __invoke(Request $req, Response $res, array $args = []) { $school = $req->getAttribute('school', false); if (!$school) { return $res->withStatus(403, 'No school'); } $params = $req->getParams(); $id = $params['id']; unset($params['id']); try { if ($id) { $asset = $this->schoolAssetsService->updateAssetForSchool($school->id, $params, $id); $res = $res->withStatus(200); } else { $asset = $this->schoolAssetsService->addAssetForSchool($school->id, $params); $res = $res->withStatus(201); } $res = $res->withJson($asset); } catch (Exception $ex) { $res = $res->withStatus(500, $ex->getMessage()); } return $res; }
public function __invoke(Request $req, Response $res) { $school = $req->getAttribute('school', false); if (!$school->id) { return $res->withStatus(403, 'No school'); } $id = $req->getParam('id', false); if (!$id) { $res = $res->withStatus(404); return $res; } $software = $this->softwareService->getSoftwareById($id); if ($software['school_id'] != $school->id) { $res = $res->withStatus(403, 'Schools not match'); return $res; } try { $this->softwareService->removeSoftware($id); $res = $res->withStatus(204); } catch (Exception $ex) { $res = $res->withStatus(500, $ex->getMessage()); } return $res; }