private function request($method, $path, $data = array(), $optionalHeaders = array()) { // Capture STDOUT ob_start(); $options = array('REQUEST_METHOD' => strtoupper($method), 'PATH_INFO' => $path, 'SERVER_NAME' => 'local.dev'); if ($method === 'get') { $options['QUERY_STRING'] = http_build_query($data); } elseif (is_array($data)) { $options['slim.input'] = http_build_query($data); } else { $options['slim.input'] = $data; } // Prepare a mock environment Slim\Environment::mock(array_merge($options, $optionalHeaders)); $env = Slim\Environment::getInstance(); $this->app->router = new NoCacheRouter($this->app->router); $this->app->request = new Slim\Http\Request($env); // Custom headers $this->app->request->headers = new Slim\Http\Headers($env); $this->app->response = new Slim\Http\Response(); // Establish some useful references to the slim app properties $this->request = $this->app->request(); $this->response = $this->app->response(); // Execute our app $this->app->run(); // Return the application output. Also available in `response->body()` return ob_get_clean(); }
/** * A group of Twig functions for use in view templates * * @param Twig_Environment $env * @param Slim $app * @return void */ function initialize(Twig_Environment $env, Slim $app) { $env->addExtension(new TwigExtension()); $env->addFunction(new Twig_SimpleFunction('urlFor', function ($routeName, $params = array()) use($app) { $url = $app->urlFor($routeName, $params); return $url; })); $env->addFunction(new Twig_SimpleFunction('hash', function ($value) { return md5($value); })); $env->addFunction(new Twig_SimpleFunction('gravatar', function ($email_hash, $size = 40) { $size = (int) $size == 0 ? 20 : (int) $size; $url = 'https://secure.gravatar.com/avatar/' . $email_hash . '?d=mm&s=' . $size; if (empty($email_hash)) { $url .= '&f=y'; } return $url; })); $env->addFunction(new Twig_SimpleFunction('getCurrentUrl', function () { return $_SERVER['REQUEST_URI']; })); $env->addFunction(new Twig_SimpleFunction('urlForTalk', function ($eventSlug, $talkSlug, $params = array()) use($app) { return $app->urlFor('talk', array('eventSlug' => $eventSlug, 'talkSlug' => $talkSlug)); })); $env->addFunction(new Twig_SimpleFunction('shortUrlForTalk', function ($talkStub) use($app) { $scheme = $app->request()->getScheme(); $host = $app->request()->headers('host'); return "{$scheme}://{$host}" . $app->urlFor('talk-quicklink', array('talkStub' => $talkStub)); })); $env->addFunction(new Twig_SimpleFunction('shortUrlForEvent', function ($eventStub) use($app) { $scheme = $app->request()->getScheme(); $host = $app->request()->headers('host'); return "{$scheme}://{$host}" . $app->urlFor('event-quicklink', array('stub' => $eventStub)); })); $env->addFunction(new Twig_SimpleFunction('dateRange', function ($start, $end, $format = 'd.m.Y', $separator = ' - ') use($app) { $formatter = new \Org_Heigl\DateRange\DateRangeFormatter(); $formatter->setFormat($format); $formatter->setSeparator($separator); if (!$start instanceof \DateTimeInterface) { $start = new \DateTime($start); } if (!$end instanceof \DateTimeInterface) { $end = new \DateTime($end); } return $formatter->getDateRange($start, $end); })); /** * wrapped Slim request function getPath() */ $env->addFunction(new Twig_SimpleFunction('currentPath', function () use($app) { $request = $app->request; $params = $app->request->get(); $queryString = http_build_query($params); if ($queryString) { return $request->getPath() . urlencode('?' . $queryString); } else { return $request->getPath(); } })); }
/** * constructor */ final function __construct() { self::$app || (self::$app = \Slim\Slim::getInstance()); $this->request = self::$app->request(); $this->response = self::$app->response(); $this->config = self::$app->config; $this->validator = self::$app->validator; $this->init(); }
/** * Decode json data from request * @return mixed|null */ protected function jsonRequest() { $input = null; try { $input = Json::decode(trim($this->app->request()->getBody()), true); } catch (JsonException $ex) { $input = null; } return $input; }
public function action_update(Slim $app, $setupId, $fitId) { if (!$app->user->isLoggedin()) { return false; } $newFit = $app->request()->post('fit'); $newDesc = $app->request()->post('description'); $newQuantity = $app->request()->post('quantity'); $app->evefit->updateFit($newFit, $newDesc, $newQuantity, $setupId, $fitId); }
/** * PUT /feed/:id * * @param int $id */ public function editFeed($id) { $feed = new Feed(); if ($feed->read($id)) { $feed->setArray(json_decode($this->app->request()->getBody(), true)); $this->app->render($feed->save() ? 200 : 500, ['response' => $feed->id]); } else { $this->app->render(404); } }
public function edit($key) { $config = new Config(); if (!$config->readKey($key)) { $this->app->render(404); return; } $config->setArray(json_decode($this->app->request()->getBody(), true)); if ($config->save()) { $this->app->render(200, ['response' => $config->id]); } else { $this->app->render(500); } }
public function __construct(Slim $app, array $params = array()) { $this->app = $app; $this->request = $app->request(); $this->response = $app->response(); $this->params = $this->buildParams($params); }
/** * POST /:key/mail/account/:id/send * * @param string $key * @param int $id */ public function sendMail($key, $id) { $smtpAccount = $this->mcryptAccount->one($key, $id)->getSmtp(); $mailData = json_decode($this->app->request()->getBody(), true); $mail = new PHPMailer(true); $mail->isSMTP(); $mail->CharSet = 'utf-8'; $mail->setFrom($smtpAccount->email, $smtpAccount->realName); $mail->Host = $smtpAccount->host; $mail->Port = $smtpAccount->port; $mail->SMTPAuth = $smtpAccount->auth; $mail->Username = $smtpAccount->userName; $mail->Password = $smtpAccount->password; $mail->Subject = trim($mailData['subject']); $mail->Body = trim($mailData['body']); if (isset($mailData['to']) && !empty($mailData['to'])) { $mail->addAddress($mailData['to']); } if (isset($mailData['cc']) && !empty($mailData['cc'])) { $mail->addCC($mailData['cc']); } if (isset($mailData['bcc']) && !empty($mailData['bcc'])) { $mail->addBCC($mailData['bcc']); } try { $this->app->render(200, ['response' => $mail->send()]); } catch (\phpmailerException $e) { $this->app->render(500, ['error' => $e->getMessage()]); } }
/** * Constructor * * @param Slim $app */ public function __construct(Slim $app, array $config = []) { $this->app = $app; $this->dic = $app->dic; $this->request = $app->request(); $this->response = $app->response(); $this->config = $config; }
/** * Handle the subscription form request */ public function subscribeAction() { try { $this->subscribeForm->validate($this->app->request()->params()); } catch (FormValidationException $e) { $this->session->flash('message', 'Oh no, you have entered invalid data. Please correct your input and try again.'); $this->session->flash('errors', $e->getErrors()); $this->session->flash('input', $this->app->request()->params()); $this->app->response->redirect($this->app->urlFor('home')); return; } // // TODO: Subscribe the client to your newsletter list... or stuff // $this->session->flash('message', 'Thanks for your request. You have successfully subscribed for our newsletter.'); $this->app->response->redirect($this->app->urlFor('home')); }
/** * Call this class as a function. * * @return void */ public function __invoke() { $request = MessageBridge::newOAuth2Request($this->slim->request()); $response = new OAuth2\Response(); $isValid = $this->server->validateAuthorizeRequest($request, $response); if (!$isValid) { MessageBridge::mapResponse($response, $this->slim->response()); return; } $authorized = $this->slim->request()->params('authorized'); if (empty($authorized)) { $this->slim->render($this->template, ['client_id' => $request->query('client_id', false)]); return; } //@TODO implement user_id $this->server->handleAuthorizeRequest($request, $response, $authorized === 'yes'); MessageBridge::mapResponse($response, $this->slim->response()); }
public function request($method, $path, $options = array()) { ob_start(); Environment::mock(array_merge(array('PATH_INFO' => $path, 'SERVER_NAME' => 'slim-test.dev', 'REQUEST_METHOD' => $method), $options)); $app = new Slim(); $this->app = $app; $this->request = $app->request(); $this->response = $app->response(); return ob_get_clean(); }
/** * PUT /password/:key/:id * * @param string $key * @param int $id */ public function edit($key, $id) { $container = new Container(); if ($container->read($id)) { $rawData = $this->app->request()->getBody(); $container->setContainer($this->crypto->encrypt($rawData, $key)); $this->app->render($container->save() ? 200 : 500, ['response' => $id]); } else { $this->app->render(404); } }
public function request($method, $path, $options = array()) { // Capture STDOUT ob_start(); // Prepare a mock environment Environment::mock(array_merge(array('REQUEST_METHOD' => $method, 'PATH_INFO' => $path, 'SERVER_NAME' => 'mock.matrix42.com'), $options)); $app = new Slim(); $this->app = $app; $this->request = $app->request(); $this->response = $app->response(); // Return STDOUT return ob_get_clean(); }
/** * Detail page * * @param \Slim\Slim $app */ public function action_index(Slim $app, $setupId) { if (!$app->user->isLoggedin()) { return false; } $setup = $app->evefit->getSetup($setupId); $tour = $app->rulechecker->getTournament(); if ($app->request()->isAjax()) { $app->render('setup/setupDetails.twig', array('setup' => $setup, 'tournament' => $tour, 'user' => $app->user)); } else { $app->render('setup/details.twig', array('setup' => $setup, 'tournament' => $tour, 'user' => $app->user)); } }
public function register(Slim $app) { $app->container->singleton('cache', function () { return new FilesystemCache('tmp/cache/db'); }); $app->container->singleton('connection', function () { $dbOptions = (require 'config/connection.config.php'); $config = new Configuration(); return DriverManager::getConnection($dbOptions, $config); }); $app->container->singleton('log', function () { $logger = new Logger('echale-gas'); $logger->pushHandler(new StreamHandler('tmp/logs/app.log', LogLevel::DEBUG)); return $logger; }); $app->container->singleton('paginator', function () use($app) { return new PagerfantaPaginator($app->config('defaultPageSize')); }); $app->container->singleton('paginatorFactory', function () use($app) { return new PaginatorFactory($app->paginator); }); $app->container->singleton('proxiesConfiguration', function () use($app) { $config = new ProxyConfiguration(); $config->setProxiesTargetDir('tmp/cache/proxies'); spl_autoload_register($config->getProxyAutoloader()); return $config; }); $app->urlHelper = new TwigExtension(); $app->container->singleton('twig', function () use($app) { $twig = new Twig(); $twig->parserOptions = ['charset' => 'utf-8', 'cache' => realpath('tmp/cache/twig'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true]; $twig->parserExtensions = [$app->urlHelper, new HalRendererExtension()]; return $twig; }); $app->container->singleton('controllerEvents', function () use($app) { $eventManager = new EventManager(); // Ensure rendering is performed at the end by assigning a very low priority $eventManager->attach('postDispatch', new RenderResourceListener($app->twig), -100); $eventManager->attach('renderErrors', new RenderErrorsListener($app->twig), -100); return $eventManager; }); $app->container->singleton('controller', function () use($app) { $controller = new RestController($app->request(), $app->response()); $factory = new RestControllerProxyFactory($app->proxiesConfiguration, $app->controllerEvents); $controller = $factory->createProxy($controller); $factory->addEventManagement($controller); return $controller; }); $app->view($app->twig); }
/** * Creates a new empty setup with the given name and description and * adds it to the user session * * @param Slim $app */ public function action_add(Slim $app) { if (!$app->user->isLoggedin()) { return false; } $name = $app->request()->post('name'); $desc = $app->request()->post('description'); $setup = new \eveATcheck\lib\evefit\lib\setup(null, $name, $desc, $app->user->getId(), $app->user->getName()); $app->evefit->addSetup($setup, false); // If this is a quickAdd submission gather the submitted ships and add them to the setup. if ($app->request()->post('quickAdd')) { foreach ($app->request()->post() as $name => $value) { if (preg_match('/ship_([0-9]+$)/', $name, $match)) { $idx = $match[1]; $shipName = $app->request()->post('ship_' . $idx); $shipQty = $app->request()->post('ship_' . $idx . '_qty'); $app->evefit->addFit("[{$shipName}, {$setup->getName()}_{$shipName}]", "auto-generated", $shipQty, $setup->getId(), false); } } } $app->evefit->save(); return; }
public function action_admin(\Slim\Slim $app) { if (!$app->user->isLoggedin()) { return false; } if (!$app->user->isAdmin()) { return false; } $userId = $app->request()->get('user', null); if ($userId != null) { $app->model->getModel('user')->toggleValid($userId); } $users = $app->model->getModel('user')->getAll(); $app->render('user/admin.twig', array('users' => $users, 'user' => $app->user)); }
public function checkRequirements() { $paths = Utils::getPaths(SW_PATH . "/engine/Shopware/Components/Check/Data/Path.xml"); clearstatcache(); $systemCheckPathResults = Utils::checkPaths($paths, SW_PATH); foreach ($systemCheckPathResults as $value) { if (!$value['result']) { $fileName = SW_PATH . '/' . $value['name']; @mkdir($fileName, 0777, true); @chmod($fileName, 0777); } } clearstatcache(); $systemCheckPathResults = Utils::checkPaths($paths, SW_PATH); $hasErrors = false; foreach ($systemCheckPathResults as $value) { if (!$value['result']) { $hasErrors = true; } } $directoriesToDelete = ['engine/Library/Mpdf/tmp' => false, 'engine/Library/Mpdf/ttfontdata' => false]; CommonUtils::clearOpcodeCache(); $results = []; foreach ($directoriesToDelete as $directory => $deleteDirecory) { $result = true; $filePath = SW_PATH . '/' . $directory; Utils::deleteDir($filePath, $deleteDirecory); if ($deleteDirecory && is_dir($filePath)) { $result = false; $hasErrors = true; } if ($deleteDirecory) { $results[$directory] = $result; } } if (!$hasErrors && $this->app->request()->get("force") !== "1") { // No errors, skip page except if force parameter is set $this->app->redirect($this->app->urlFor("dbmigration")); } $isSkippableCheck = $this->app->config('skippable.check'); if ($isSkippableCheck && $this->app->request()->get("force") !== "1") { // No errors, skip page except if force parameter is set $this->app->redirect($this->app->urlFor("dbmigration")); } $this->app->render('checks.php', ['systemCheckResultsWritePermissions' => $systemCheckPathResults, 'filesToDelete' => $results, 'error' => $hasErrors]); }
/** * This function adds the clickable labels with alternate formats to the results webpage * * @return void */ protected function prepareWebResultView() { // mime type buttons // TODO: // get mimetypes of the current route and // only output the buttons for the allowed mimetypes of that route // $currentRouteAcceptableMimeTypes = $this->app->router()->getCurrentRoute(); // $formats = (isset($this->routeInfo->mimeTypes) ? $this->routeInfo->mimeTypes : $this->mimeLabels); $formats = $this->mimeLabels; // we are viewing a html page, so remove this result format // unset($formats['text/html']); $this->app->view()->set('alternate_formats', $formats); //set the current selected mime type $this->app->view()->set('current_mime', $this->mimeBest); // inject javascript $this->app->view()->set('javascript', '<script src="' . $this->app->request()->getRootUri() . '/assets/js/web-result.js" type="text/javascript"></script>'); }
/** * @SWG\Property(name="station_id",type="integer",description="Unique identifier of the gas station") * @SWG\Property(name="name",type="string",description="Name of the gas station") * @SWG\Property(name="social_reason",type="string",description="Official name of the gas station") * @SWG\Property(name="address_line_1",type="string",description="Street name and number of the gas station") * @SWG\Property(name="address_line_2",type="string",description="Neighborhood name of the gas station") * @SWG\Property(name="location",type="string",description="State and city name where the gas station is located") * @SWG\Property(name="latitude",type="double",description="Latitude coordinate") * @SWG\Property(name="longitude",type="double",description="Longitude coordinate") * @SWG\Property(name="created_at",type="string",format="date-format",description="Registration date of the gas station") * @SWG\Property(name="last_updated_at",type="string",format="date-format",description="Most recent date in which the gas station was edited") */ public function register(Slim $app) { $app->container->singleton('station', function () use($app) { return new Model($app->stationTable, $app->stationValidator, $app->paginatorFactory); }); $app->container->singleton('stationFormatter', function () use($app) { return new ResourceFormatter($app->urlHelper, 'station', 'station_id'); }); $app->container->singleton('stationsFormatter', function () use($app) { return new CollectionFormatter($app->urlHelper, 'stations', $app->stationFormatter); }); $app->container->singleton('stationEvents', function () use($app) { $eventManager = new EventManager(); $specification = new ChainedSpecification(); $specification->addSpecification(new PaginationSpecification($app->config('defaultPageSize'))); $specification->addSpecification(new GeolocationSpecification()); $eventManager->attach('postFindAll', new QuerySpecificationListener($specification)); $eventManager->attachAggregate(new HasTimestampListener()); $eventManager->attachAggregate(new CacheListener($app->cache, $app->request()->getPathInfo())); return $eventManager; }); $app->container->singleton('stationTable', function () use($app) { $stationTable = new StationTable('stations', $app->connection); $factory = new TableProxyFactory($app->proxiesConfiguration, $app->stationEvents); $stationTable = $factory->createProxy($stationTable); $factory->addEventManagement($stationTable); return $stationTable; }); $app->container->singleton('stationValidator', function () use($app) { return new ValitronValidator(require 'config/validations/stations.config.php'); }); $app->container->singleton('stationController', function () use($app) { $app->controller->setModel($app->station); $app->controllerEvents->attach('postDispatch', new FormatResourceListener($app->stationFormatter)); return $app->controller; }); $app->container->singleton('stationsController', function () use($app) { $app->controller->setModel($app->station); $app->controllerEvents->attach('postDispatch', new FormatResourceListener($app->stationsFormatter)); return $app->controller; }); }
$v->setData('thumb_format', $fmts['thumb']); $remote_infos = $conf->getRemoteInfos(); if ($remote_infos !== false) { $v->setData('remote_method', $remote_infos['method']); $v->setData('remote_uri', $remote_infos['uri']); } }); //set default conditions Route::setDefaultConditions(array('image' => '.+\\.[a-zA-Z]{3,4}', 'series' => '.+', 'format' => 'full|' . implode('|', array_keys($conf->getFormats())))); //404 handler $app->notFound(function () use($app) { $app->render('404.html.twig'); }); //custom error handler $app->error(function (\Exception $e) use($app, $conf, $app_base_url) { $resuUri = $app->request()->getResourceUri(); $etype = get_class($e); Analog::error('exception \'' . $etype . '\' with message \'' . $e->getMessage() . '\' in ' . $e->getFile() . ':' . $e->getLine() . "\nStack trace:\n" . $e->getTraceAsString()); if ((substr($resuUri, 0, 10) === '/ajax/img/' || substr($resuUri, 0, 21) === '/ajax/representative/') && APP_DEBUG !== true) { $format = 'default'; preg_match('/.*\\/format\\/(.*)/', $resuUri, $matches); if (isset($matches[1])) { $format = $matches[1]; } $picture = new Picture($conf, DEFAULT_PICTURE, $app_base_url); $display = $picture->getDisplay($format); $response = $app->response(); foreach ($display['headers'] as $key => $header) { $response[$key] = $header; } $response->body($display['content']);
/** * A group of Twig functions for use in view templates * * @param Twig_Environment $env * @param Slim $app * @return void */ function initialize(Twig_Environment $env, Slim $app) { $env->addExtension(new TwigExtension()); $env->addFunction(new Twig_SimpleFunction('urlFor', function ($routeName, $params = array()) use($app) { $url = $app->urlFor($routeName, $params); return $url; })); $env->addFunction(new Twig_SimpleFunction('hash', function ($value) { return md5($value); })); $env->addFunction(new Twig_SimpleFunction('gravatar', function ($email_hash, $size = 40) { $size = (int) $size == 0 ? 20 : (int) $size; $url = 'https://secure.gravatar.com/avatar/' . $email_hash . '?d=mm&s=' . $size; if (empty($email_hash)) { $url .= '&f=y'; } return $url; })); $env->addFunction(new Twig_SimpleFunction('getCurrentRoute', function () use($app) { return $app->router->getCurrentRoute()->getName(); })); $env->addFunction(new Twig_SimpleFunction('getCurrentUrl', function ($fullyQualified = false) use($app) { $url = $_SERVER['REQUEST_URI']; if ($fullyQualified) { $scheme = $app->request()->getScheme(); $host = $app->request()->headers('host'); $url = "{$scheme}://{$host}{$url}"; } return $url; })); $env->addFunction(new Twig_SimpleFunction('urlForTalk', function ($eventSlug, $talkSlug, $params = array()) use($app) { return $app->urlFor('talk', array('eventSlug' => $eventSlug, 'talkSlug' => $talkSlug)); })); $env->addFunction(new Twig_SimpleFunction('shortUrlForTalk', function ($talkStub) use($app) { $scheme = $app->request()->getScheme(); $host = $app->request()->headers('host'); return "{$scheme}://{$host}" . $app->urlFor('talk-quicklink', array('talkStub' => $talkStub)); })); $env->addFunction(new Twig_SimpleFunction('shortUrlForEvent', function ($eventStub) use($app) { $scheme = $app->request()->getScheme(); $host = $app->request()->headers('host'); return "{$scheme}://{$host}" . $app->urlFor('event-quicklink', array('stub' => $eventStub)); })); $env->addFunction(new Twig_SimpleFunction('dateRange', function ($start, $end, $format = 'd.m.Y', $separator = ' - ') use($app) { $formatter = new \Org_Heigl\DateRange\DateRangeFormatter(); $formatter->setFormat($format); $formatter->setSeparator($separator); if (!$start instanceof \DateTimeInterface) { $start = new \DateTime($start); } if (!$end instanceof \DateTimeInterface) { $end = new \DateTime($end); } return $formatter->getDateRange($start, $end); })); /** * Convert a number of minutes into a prettier textual string. * * e.g. * - 60 minutes converts to "1 hour" * - 120 minutes converts to "2 hours" * - 126 minutes converts to "2 hours, 6 minutes" */ $env->addFunction(new Twig_SimpleFunction('prettyDuration', function ($duration) { $duration = (int) $duration; if ($duration < 60) { return "{$duration} minutes"; } if ($duration == 60) { return "1 hour"; } $hours = (int) ($duration / 60); $minutes = $duration - $hours * 60; if (!$minutes) { return "{$hours} hours"; } return "{$hours} hours, {$minutes} minutes"; })); /** * wrapped Slim request function getPath() */ $env->addFunction(new Twig_SimpleFunction('currentPath', function () use($app) { $request = $app->request; $params = $app->request->get(); $queryString = http_build_query($params); if ($queryString) { return $request->getPath() . urlencode('?' . $queryString); } else { return $request->getPath(); } })); /** * Create link to log in with Facebook */ $env->addFunction(new Twig_SimpleFunction('facebookLoginUrl', function () use($app) { if (!$app->config('facebook') || empty($app->config('facebook')['app_id'])) { // app_id isn't configured return ''; } $req = $app->request(); $redirectUrl = $req->getUrl(); $redirectUrl .= $app->urlFor('facebook-callback'); $url = 'https://www.facebook.com/dialog/oauth?'; $url .= http_build_query(['scope' => 'email', 'client_id' => $app->config('facebook')['app_id'], 'redirect_uri' => $redirectUrl]); return $url; }, ['is_safe' => ['html']])); }
/** * Retrieve the current application request. * * @return Request */ public function request() { return $this->app->request(); }
include 'db.php'; require 'codeguy-Slim/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); use Slim\Slim; // create new Slim instance $app = new Slim(); $app->get("/f2", function () { echo "<h1>f2 lms service alisha</h1>"; }); $app->get('/f3/:name', function ($name) { echo "Hello, {$name}"; }); $app->post('/logout', function () use($app) { try { $request = $app->request(); $userIdObj = json_decode($request->getBody()); $userId = $userIdObj->userId; try { unset($_SESSION['SESSION_KEY']); } catch (PDOException $e) { //error_log($e->getMessage(), 3, '/var/tmp/php.log'); echo '{"error":{"text":' . $e->getMessage() . '}}'; } } catch (PDOException $e) { //error_log($e->getMessage(), 3, '/var/tmp/php.log'); echo '{"error":{"text":' . $e->getMessage() . '}}'; } }); $app->post('/myordersnew', function () use($app) { try {
/** * @param string $routeName * @param string $tableName * @param callable $customCRUDFunction * @param string $displayName */ public function add($routeName, $customCRUDFunction = null, $tableName = null, $displayName = null) { if ($tableName == null) { $tableName = $routeName; } $this->tableList[$routeName] = $tableName; $this->tableDisplayName[$routeName] = $displayName; $this->routeNameList[] = $routeName; /* * Page Group (ListView, CreateView, EditView) */ $this->slim->group("/" . $this->groupName . "/" . $routeName, function () use($routeName, $customCRUDFunction, $tableName) { $this->slim->get("/", function () use($routeName) { $this->slim->redirectTo("_louisCRUD_" . $routeName); }); /* * ListView */ $this->slim->get("/list(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->renderListView(); } })->name("_louisCRUD_" . $routeName); /* * Create */ $this->slim->get("/create(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->createFunction != null) { $createFunction = $this->createFunction; $result = $createFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force Hide ID field $this->field("id")->hide(); if ($this->isEnabledCreate()) { $this->renderCreateView(); } }); /* * Edit */ $this->slim->get("/edit/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean first $this->loadBean($id); // ID must be hidden $this->field("id")->hide(); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // If user show the ID field, force set it to readonly $this->field("id")->setReadOnly(true); if ($this->isEnabledEdit()) { $this->renderEditView(); } }); /* * Export Excel */ $this->slim->map("/export(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->exportFunction != null) { $exportFunction = $this->exportFunction; $result = $exportFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // TODO: isEnabledExport(); $this->renderExcel(); })->via('GET', 'POST'); }); /* * API Group, RESTful style. */ $this->slim->group("/" . $this->apiGroupName . "/" . $routeName, function () use($routeName, $customCRUDFunction, $tableName) { /* * JSON for Listview */ $this->slim->map("/list(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { $this->enableJSONResponse(); // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->getJSONList(); } return; })->via('GET', 'POST'); /* * For Datatables */ $this->slim->map("/datatables(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { $this->enableJSONResponse(); // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->listviewFunction != null) { $listviewFunction = $this->listviewFunction; $result = $listviewFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledListView()) { $this->getListViewJSONString(); } return; })->via('GET', 'POST'); /* * View a bean * PUT /api/{tableName}/{id} */ $this->slim->get("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Edit Function if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledEdit()) { $json = $this->getJSON(false); $this->enableJSONResponse(); echo $json; } }); /* * Insert a bean * POST /api/{tableName} */ $this->slim->post("(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Global Function $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } // Custom Create Function if ($this->createFunction != null) { $createFunction = $this->createFunction; $result = $createFunction($p1, $p2, $p3, $p4, $p5); } if ($result === false) { return; } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledCreate()) { $jsonObject = $this->insertBean($_POST); $this->enableJSONResponse(); echo json_encode($jsonObject); } else { // TODO: Should be json object echo "No permission"; } }); /* * Update a bean * PUT /crud/{tableName}/{id} */ $this->slim->put("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); // Load Bean $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Create Function if ($this->editFunction != null) { $editFunction = $this->editFunction; $result = $editFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Force hide ID $this->field("id")->hide(); // Insert into database if ($this->isEnabledEdit()) { $jsonObject = $this->updateBean($this->slim->request()->params()); $this->enableJSONResponse(); echo json_encode($jsonObject); } }); /* * Delete a bean * DELETE /crud/{tableName}/{id} */ $this->slim->delete("/:id(/:p1(/:p2(/:p3(/:p4(/:p5)))))", function ($id, $p1 = null, $p2 = null, $p3 = null, $p4 = null, $p5 = null) use($routeName, $customCRUDFunction, $tableName) { // MUST INIT FIRST $this->init($tableName, $routeName, $p1, $p2, $p3, $p4, $p5); $this->enableJSONResponse(); $this->loadBean($id); if ($this->configFunction != null) { $function = $this->configFunction; $result = $function(); if ($result === false) { return; } } // Custom Global Function if ($customCRUDFunction != null) { $result = $customCRUDFunction($p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } // Custom Delete Function if ($this->deleteFunction != null) { $deleteFunction = $this->deleteFunction; $result = $deleteFunction($id, $p1, $p2, $p3, $p4, $p5); if ($result === false) { return; } } if ($this->isEnabledDelete()) { $this->deleteBean(); $result = new \stdClass(); $result->status = "succ"; echo json_encode($result); } }); }); }
require 'vendor/autoload.php'; include_once 'app/autoloader.php'; /*********************************************** * init Slim **********************************************/ use Slim\Slim; Slim::registerAutoloader(); $app = new Slim(); $config['slimConfig'] = array_merge($config['slim'], $config['app']); $app->config($config['slimConfig']); /*********************************************** * init Twig **********************************************/ Twig_Autoloader::register(); $loader = new Twig_Loader_Filesystem(); foreach ($config['twig']['tpl_dir'] as $name => $tpl_path) { $loader->addPath($tpl_path, $name); } $twig = new Twig_Environment($loader, $config['twig']); $twig->addGlobal('baseUrl', $app->request()->getRootUri() . '/'); $twig->addGlobal('config', $config['app']); $app->config(array('twig' => $twig)); include_once 'app/constants.php'; include_once 'app/middlewares.php'; /*********************************************** * load routes dynamic **********************************************/ foreach (glob('app/routes/*.php') as $file) { include_once $file; } $app->run();
include __DIR__ . '/src/config/config.php'; require_once $config['magento_full_path']; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Process\ProcessBuilder; use Symfony\Component\Process\Process; use Helpers\CSV\CsvHandler; use Helpers\CSV\CsvSplitter; use Helpers\ProcessLocker; use Keboola\Csv\CsvFile; use Slim\Slim; $app = new Slim(array('mode' => 'development', 'templates.path' => $config['templates_path'])); $app->get('/', function () use($app, $config) { $app->render('page.php', array('csv_files_path' => $config['csv_files_path'], 'log_files_path' => $config['log_files_path'])); }); $app->get('/download_report', function () use($app, $config) { $fileName = $app->request()->params('filename'); echo "<pre>"; echo file_get_contents($config['log_files_path'] . $fileName); }); $app->get('/process/', function () use($app, $config) { $fileName = $app->request()->params('filename'); $locker = new ProcessLocker($config['lock_file']); if (!$locker->isLocked()) { $splitter = new CsvSplitter(new CsvFile($fileName), $config['output_csv_path']); $splitter->split($config['split_size']); $command = $config['nohup_path'] . ' ' . $config['php_path'] . ' ' . __DIR__ . '/src/shell/csv_importer.php ' . $config['output_csv_path'] . ' > /dev/null 2>&1 &'; $process = new Process($command, $config['proc_working_path']); $process->run(); } $app->redirect('/csv_batch_process/index.php'); });
} $authenticateUser = function ($app) { return function () use($app) { if (!isValidLogin($app->getCookie('username'), $app->getCookie('password'))) { $app->halt(401); // Unauthorized access } }; }; $app->post('/login', function () use($app) { try { // get user and pass from post if from form as dataType=html //$username = $app->request->post('username'); //$password = $app->request->post('password'); // get user and pass from post - get and decode JSON request body $body = $app->request()->getBody(); $input = json_decode($body); $username = (string) $input->username; $password = (string) $input->password; // this is how you can check what has been passed. Look into responds from ajaxPost.php //var_dump($password); if (isValidLogin($username, $password)) { // if username and pass are valid set Cookie $app->setCookie('username', $username, '1 day'); $app->setCookie('password', $password, '1 day'); $app->response()->header('Content-Type', 'application/json'); $app->response()->status(200); // OK echo json_encode(array('operation' => 'login', 'status' => 'ok')); } else { throw new AuthenticateFailedException();