public function product_mediaRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $media = $db->get("product_media", "*", ["id" => $attr["id"]]);
     if (!$media) {
         return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product/" . $attr["product_id"] . "/media");
     }
     if ($media["type"] == "image") {
         @unlink("../product_media/" . $media["image_path"]);
     }
     $db->delete("product_media", ["id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product/" . $attr["product_id"] . "/media");
 }
Ejemplo n.º 2
0
 public function __invoke(Request $req, Response $res, callable $next)
 {
     $path = $req->getUri()->getPath();
     $path = "/" . trim($path, "/");
     $allowNotAuth = ["/", "/login"];
     if (!in_array($path, $allowNotAuth)) {
         /** @var Aura\Session\Session */
         $session = $this->container["session"];
         $loginSegment = $session->getSegment("login");
         if (empty($loginSegment->get("user"))) {
             return $res->withHeader("Location", $req->getUri()->getBasePath() . "/login");
         }
     }
     return $next($req, $res);
 }
Ejemplo n.º 3
0
 public function edit(Request $request, Response $response, array $args)
 {
     $uid = $args['uid'];
     if (empty($uid)) {
         $this->flash->addMessage('flash', 'No record specified');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('accounts'));
     }
     $id = $this->authenticator->getIdentity();
     $user = R::load('users', $id['id']);
     if ($uid != 'new') {
         $account = R::load('accounts', $uid);
         if ($account->id == 0) {
             $this->flash->addMessage('flash', 'No record found');
             return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('accounts'));
         }
         // restrict access to own profile or Admin role
         if ($account->users->id != $id['id']) {
             if (strtolower($id['role']) != 'admin') {
                 $this->flash->addMessage('flash', 'Access Denied');
                 return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('accounts'));
             }
         }
     } else {
         $account = R::dispense('accounts');
     }
     if ($request->isPost()) {
         $data = $request->getParams();
         $account->import($data, 'apikey,accountid,servertype');
         $account->users = $user;
         $account->lasttid = 0;
         $oandaInfo = FALSE;
         // verify and get account balance
         try {
             $oandaInfo = new Broker_Oanda($account['servertype'], $account['apikey'], $account['accountid'], 0);
         } catch (\Exception $e) {
             $viewData['flash'] = 'Account Details Invalid';
         }
         if ($oandaInfo != FALSE) {
             $aid = R::store($account);
             $oandaInfo->updateAccount();
             $this->flash->addMessage('flash', "account updated");
             return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('editaccount', ['uid' => $aid]));
         }
     }
     $viewData['account'] = $account;
     $this->view->render($response, 'account.twig', $viewData);
     return $response;
 }
Ejemplo n.º 4
0
 public function listMedia(Request $request, Response $response, $arguments)
 {
     $media = $this->container->MediaService->getAllMedia();
     $media = collect($media)->values();
     $baseUrl = $request->getUri()->getBaseUrl();
     $media = $media->map(function ($item) use($baseUrl) {
         $item['is_image'] = false;
         if ($this->isImage($item)) {
             $imagick = $this->manager->make($item['full_name_with_path']);
             $item['height'] = $imagick->height();
             $item['width'] = $imagick->width();
             $item['is_image'] = true;
         }
         $item['url'] = $baseUrl . '/uploads/' . $item['full_name'];
         if ($this->isPdf($item)) {
             $item['thumbnail'] = $baseUrl . '/api/media/thumbnail/' . $item['full_name'];
         } elseif ($this->isImage($item)) {
             $item['thumbnail'] = $item['url'];
         } else {
             $item['thumbnail'] = null;
         }
         $item['downloadUrl'] = $baseUrl . '/api/media/download/' . $item['full_name'];
         return $item;
     });
     return $response->withJson($media);
 }
Ejemplo n.º 5
0
 /**
  * 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;
 }
Ejemplo n.º 6
0
 public function test(Request $request, Response $response, array $args)
 {
     $uid = $args['uid'];
     $myaccount = R::load('accounts', $uid);
     $accountId = $myaccount->accountid;
     $account = R::findOne('accounts', ' accountid = ?', [$accountId]);
     if (!empty($account)) {
         $apiKey = $account['apikey'];
         $type = $account['servertype'];
         $oandaInfo = new Broker_Oanda($type, $apiKey, $accountId);
     } else {
         $this->flash->addMessage('flash', "Oanda AccountId not found");
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('homepage'));
     }
     $side = 'buy';
     $pair = 'EUR_USD';
     $price = '1.1400';
     $expiry = time() + 60;
     $stopLoss = '1.1300';
     $takeProfit = NULL;
     $risk = 1;
     //        $side='buy';
     //        $pair='GBP_CHF';
     //        $price='2.1443';
     //        $expiry = $oandaInfo->getExpiry(time()+60);
     //        $stopLoss='2.1452';
     //        $takeProfit=NULL;
     //        $risk=1;
     //$oandaInfo->placeLimitOrder($side,$pair,$price,$expiry,$stopLoss,$takeProfit,$risk);
     $oandaInfo->processTransactions();
 }
Ejemplo n.º 7
0
 public function learningcenterRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("learningcenter", ["id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/learningcenter");
 }
Ejemplo n.º 8
0
 public function deleteUser(Request $request, Response $response, array $args)
 {
     $name = $args['name'];
     if (empty($name)) {
         $this->flash->addMessage('flash', 'No user specified');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('users'));
     }
     $user = R::findOne('users', ' email = ? ', [$name]);
     if (!empty($user)) {
         R::trash($user);
         $this->flash->addMessage('flash', "{$name} deleted");
     } else {
         $this->flash->addMessage('flash', "{$name} User not found");
     }
     return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('users'));
 }
 public function productRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("product", ["id" => $attr["id"]]);
     $db->delete("person_cripple", ["cripple_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product");
 }
Ejemplo n.º 10
0
 public function disavantaged_typeRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("disavantaged_type", ["id" => $attr["id"]]);
     $db->delete("person_disavantaged", ["disavantaged_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/disavantaged_type");
 }
Ejemplo n.º 11
0
 public function dispatch(Request $request, Response $response, array $args)
 {
     $this->logger->info("Oncall page action dispatched");
     $rota = strtolower($args['rota']);
     $display = isset($args['display']) ? $args['display'] : 6;
     $prev = $request->getParam('prev', 0);
     $dis = 5;
     $loggedIn = $this->authenticator->hasIdentity();
     $comments = "";
     $rotaBean = R::findOne('rotas', ' name = :name ', [':name' => $rota]);
     if (empty($rotaBean)) {
         $this->flash->addMessage('flash', "sorry {$rota} not found");
         return $response->withRedirect($this->router->pathFor('homepage'));
     }
     $title = $rotaBean->title;
     $users = $rotaBean->sharedUsersList;
     $months = [];
     $colour = [];
     $data = [];
     if (!empty($prev)) {
         $thisMonth = date("n") - 2;
     } else {
         $thisMonth = date("n") - 1;
     }
     $thisYear = date("Y");
     if ($thisMonth < 1) {
         $thisMonth = $thisMonth + 12;
         $thisYear = $thisYear - 1;
     }
     for ($i = 1; $i < $display + 1; $i++) {
         $thisMonth++;
         if ($thisMonth == 13) {
             $thisMonth = 1;
             $thisYear++;
         }
         $months[$i] = $thisYear . "-" . $thisMonth . "-1";
         if ($loggedIn) {
             foreach (range(1, 31) as $dayCount) {
                 $data[$i][$dayCount] = "<a href=\"" . $request->getUri()->getBaseUrl() . "/change/{$rota}?day={$dayCount}&month={$thisMonth}&year={$thisYear}&prev={$prev}\">{$dayCount}</a>";
             }
         } else {
             $data[$i] = range(0, 31);
         }
         foreach (range(1, 31) as $dayCount) {
             $rotaDay = R::findOne($rota, ' month = :month AND year = :year AND day = :day ', [':day' => $dayCount, ':month' => $thisMonth, ':year' => $thisYear]);
             if (!empty($rotaDay)) {
                 $onCallUser = $rotaDay->fetchAs('users')->name;
                 $colour[$i][$dayCount] = $onCallUser->colour;
                 //"#6622" . ($dayCount + 10);
             } else {
                 $colour[$i][$dayCount] = "#fefefe";
             }
         }
     }
     $onCallNow = $this->getOnCallNow($rota);
     $this->view->render($response, 'oncall.twig', ['rota' => $rota, 'title' => $title, 'comments' => $comments, 'months' => $months, 'data' => $data, 'colour' => $colour, 'users' => $users, 'formatDate' => date("l jS F Y,  g:ia"), 'onCallNow' => $onCallNow]);
     return $response;
 }
Ejemplo n.º 12
0
 public function anyLogout(Request $req, Response $res)
 {
     $container = $this->slim->getContainer();
     /** @var Aura\Session\Session */
     $session = $container->session;
     $loginSegment = $session->getSegment("login");
     $loginSegment->clear();
     $session->commit();
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/login");
 }
Ejemplo n.º 13
0
 public function auth(Request $request, Response $response, callable $next)
 {
     $auth = $this->authenticator;
     $role = $this->getRole($auth->getIdentity());
     $hasIdentity = $auth->hasIdentity();
     $identity = $auth->getIdentity();
     //        $data = array(
     //            'hasIdentity' => $hasIdentity,
     //            'role' => $role,
     //            'identity' => $identity
     //        );
     if (!$hasIdentity) {
         //throw new HttpUnauthorizedException();
         $_SESSION['urlRedirect'] = (string) $request->getUri();
         //$app->flash('error', 'Login required');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('login'));
     }
     /* Everything ok, call next middleware. */
     $response = $next($request, $response);
     return $response;
 }
Ejemplo n.º 14
0
 /**
  * Execute the middleware.
  *
  * @param Request  $request
  * @param Response $response
  * @param callable $next
  *
  * @return Response
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     // Overwrite request with new uri path
     $uri = $request->getUri();
     $request = $request->withUri($uri->withPath($this->path));
     // Overwrite params (if provided)
     if (!empty($this->params)) {
         $request = $request->withQueryParams($this->params);
     }
     // Call next middleware
     return $next($request, $response);
 }
Ejemplo n.º 15
0
 public function editUser(Request $request, Response $response, array $args)
 {
     $username = $args['username'];
     if (empty($username)) {
         $this->flash->addMessage('flash', 'No user specified');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('profile'));
     }
     $username = base64_decode($username);
     $id = $this->authenticator->getIdentity();
     // restrict access to own profile or Admin role
     if ($username != strtolower($id['email'])) {
         if (strtolower($id['role']) != 'admin') {
             $this->flash->addMessage('flash', 'Access Denied');
             return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('profile'));
         }
     }
     $user = R::findOne('users', ' email = ? ', [$username]);
     if ($user == NULL) {
         $user = R::dispense('users');
     }
     if ($request->isPost()) {
         $user->fullname = $request->getParam('userfullname');
         $user->email = $request->getParam('username');
         $password = $request->getParam('userpassword');
         if (!empty($password)) {
             $pass = password_hash($password, PASSWORD_DEFAULT);
             $user->hash = $pass;
         }
         $id = R::store($user);
         $this->flash->addMessage('flash', "{$user->name} updated");
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('edituser', ['username' => base64_encode($username)]));
     }
     $expUser['user'] = $user->export();
     $expUser['user']['hashemail'] = base64_encode($user['email']);
     $this->view->render($response, 'user.twig', $expUser);
     return $response;
 }
Ejemplo n.º 16
0
 public function editUser(Request $request, Response $response, array $args)
 {
     $username = strtolower($args['username']);
     if (empty($username)) {
         $this->flash->addMessage('flash', 'No user specified');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('profile'));
     }
     $id = $this->authenticator->getIdentity();
     // restrict access to own profile or Admin user
     if ($username != strtolower($id['name'])) {
         if (strtolower($id['name']) != 'admin') {
             $this->flash->addMessage('flash', 'Access Denied');
             return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('profile'));
         }
     }
     if ($username != 'new') {
         $user = R::findOrCreate('users', ['name' => $username]);
     } else {
         $user = R::dispense('users');
     }
     if ($request->isPost()) {
         $data = $request->getParams();
         //$username = $request->getParam('username');
         $user->import($data, 'fullname,colour,mobile,home');
         $user->name = $request->getParam('username');
         $password = $request->getParam('password');
         if (!empty($password)) {
             $pass = password_hash($password, PASSWORD_DEFAULT);
             $user->hash = $pass;
         }
         $id = R::store($user);
         $this->flash->addMessage('flash', "{$user->name} updated");
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('edituser', ['username' => $username]));
     }
     $this->view->render($response, 'user.twig', $user->export());
     return $response;
 }
Ejemplo n.º 17
0
 public function __invoke(Request $request, Response $response)
 {
     $data = ['uri' => $request->getUri()->getPath(), 'contact' => $this->container->router->pathFor('contact')];
     // We need a new response body
     $headers = new Headers(['Content-Type' => 'text/html; charset=UTF-8']);
     $res = new Response(404, $headers);
     // Start buffering
     ob_start();
     $view = new View($res);
     $view->setTemplate('errors.404');
     $view->render($data);
     // Get the buffer output
     $content = ob_get_clean();
     return $res->write($content);
 }
Ejemplo n.º 18
0
 public function __invoke(Request $req, Response $res)
 {
     if ($req->isPost()) {
         $adapter = $this->authService->getAdapter();
         if ($adapter instanceof ValidatableAdapterInterface) {
             $adapter->setIdentity($req->getParam('identity'));
             $adapter->setCredential($req->getParam('credential'));
         }
         $result = $this->authService->authenticate($adapter);
         if (!$result->isValid()) {
             $this->flash->addMessage('danger', reset($result->getMessages()));
             return $res->withRedirect($req->getUri());
         }
         return $res->withRedirect($this->successUrl);
     }
     return $this->view->render($res, 'user/login.twig', []);
 }
Ejemplo n.º 19
0
 /**
  * Execute the middleware.
  *
  * @param Request  $request
  * @param Response $response
  * @param callable $next
  *
  * @return Response
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     $uri = $request->getUri();
     $path = $uri->getPath();
     // Add or remove slash as configured
     if ($path != '/') {
         $path = rtrim($path, '/');
         if ($this->addSlash && !pathinfo($path, PATHINFO_EXTENSION)) {
             $path .= '/';
         }
     }
     // Redirect
     if ($uri->getPath() !== $path) {
         return $response->withRedirect($uri->withPath($path), 301);
     }
     return $next($request, $response);
 }
Ejemplo n.º 20
0
 /**
  *
  * @param Request $request            
  * @param unknown $response            
  * @param unknown $next            
  * @return unknown
  */
 public function __invoke(Request $request, $response, $next)
 {
     $container = $this->app->getContainer();
     $session = $container->get('session');
     // if not an admin section
     if ($this->startsWith($request->getUri()->getPath(), '/admin/login')) {
         $response = $next($request, $response);
         return $response;
     }
     if (!$this->isLoggedIn($session)) {
         $session->set('original', $request->getUri()->getPath());
         $view = $container->get('view');
         $router = $container->get('router');
         return $response->withRedirect($router->pathFor('adminlogin'));
         //return $view->render($response, 'adminlogin.twig', array());
     } else {
         $response = $next($request, $response);
     }
     return $response;
 }
Ejemplo n.º 21
0
 /**
  * display a static page
  *
  * @param Request $request
  * @param Response $response
  */
 public function get(Request $request, Response $response)
 {
     $pdate = str_replace('/', '-', $request->getAttribute('pdate'));
     $pslug = $request->getAttribute('pslug');
     $pfile = sprintf('%s/blog/%s-%s.md', ROOT_PATH, $pdate, strtolower($pslug));
     if (!is_file($pfile) || !is_readable($pfile)) {
         return $this->render($response, 'errors/404.html');
     }
     $f = file_get_contents($pfile);
     $t = \Michelf\MarkdownExtra::defaultTransform($f);
     return $response->getBody()->write($t);
     $pdata = json_decode(file_get_contents($pfile), true);
     if (empty($pdata)) {
         return $this->render($response, 'errors/500.html');
     }
     $pdata['published_at'] = $pdate;
     $pdata['slug'] = $pslug;
     $pdata['url'] = (string) $request->getUri();
     return $this->render($response, 'post.html', compact('pdata'));
 }
 public function forgot(Request $request, Response $response, array $args)
 {
     /** @var Users $users */
     $users = $this->data(Users::class);
     $input = $request->getParsedBody();
     $validator = $this->validator->rule('required', 'email');
     $validator->rule('email', 'email');
     $validator->addRule('assertNotEmailExists', function ($field, $value, array $params) use($users) {
         return !$users->assertEmailExists($value);
     }, 'Email tersebut tidak terdaftar!');
     $validator->rule('assertNotEmailExists', 'email');
     $success_msg = 'Email konfirmasi lupa password sudah berhasil dikirim. Segera check email anda. Terimakasih ^_^';
     $success_msg_alt = 'Email konfirmasi lupa password sudah berhasil dikirim. Segera check email anda.<br><br><strong>Kemungkinan email akan sampai agak terlambat, karena email server kami sedang mengalami sedikit kendala teknis. Jika belum juga mendapatkan email, maka jangan ragu untuk laporkan kepada kami melalu email: report@phpindonesia.or.id</strong><br><br>Terimakasih ^_^';
     if ($validator->validate()) {
         $resetKey = md5(uniqid(rand(), true));
         $emailAddress = $input['email'];
         $resetExpiredDate = date('Y-m-d H:i:s', time() + 7200);
         // 2 jam
         /** @var UsersResetPwd $usersResetPass */
         $usersResetPass = $this->data(UsersResetPwd::class);
         $member = $users->get(['user_id', 'username'], ['email' => $emailAddress])->fetch();
         $usersResetPass->create(['user_id' => $member['user_id'], 'reset_key' => $resetKey, 'expired_date' => $resetExpiredDate, 'email_sent' => 'N']);
         try {
             $emailSettings = $this->settings->get('email');
             $message = \Swift_Message::newInstance('PHP Indonesia - Konfirmasi lupa password')->setFrom([$emailSettings['sender_email'] => $emailSettings['sender_name']])->setTo([$emailAddress => $member['username']])->setBody(file_get_contents(APP_DIR . 'views' . _DS_ . 'email' . _DS_ . 'forgot-password-confirmation.txt'));
             $this->mailer->registerPlugin(new \Swift_Plugins_DecoratorPlugin([$emailAddress => ['{email_address}' => $emailAddress, '{request_reset_date}' => date('d-m-Y H:i:s'), '{reset_path}' => $this->router->pathFor('membership-reset-password', ['uid' => $member['user_id'], 'reset_key' => $resetKey]), '{reset_expired_date}' => date('d-m-Y H:i:s', strtotime($resetExpiredDate)), '{base_url}' => $request->getUri()->getBaseUrl()]]));
             $this->mailer->send($message);
             // Update email sent status
             $usersResetPass->update(['email_sent' => 'Y'], ['user_id' => $member['user_id'], 'reset_key' => $resetKey]);
             $this->addFormAlert('success', $success_msg);
         } catch (\PDOException $e) {
             $this->addFormAlert('error', 'System error' . $e->getMessage());
         } catch (\Swift_TransportException $e) {
             $this->addFormAlert('success', $success_msg_alt);
         }
     } else {
         $this->addFormAlert('warning', 'Some of mandatory fields is empty!', $validator->errors());
         return $response->withRedirect($this->router->pathFor('membership-forgot-password'));
     }
     return $response->withRedirect($this->router->pathFor('membership-login'));
 }
Ejemplo n.º 23
0
 public function options(Request $request, Response $response, array $args)
 {
     $uid = $args['uid'];
     if (empty($uid)) {
         $this->flash->addMessage('flash', 'No record specified');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('homepage'));
     }
     $id = $this->authenticator->getIdentity();
     $user = R::load('users', $id['id']);
     $strategy = R::load('strategies', $uid);
     if ($strategy->id == 0) {
         $this->flash->addMessage('flash', 'No record found');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('stratagies'));
     }
     // restrict access to own profile or Admin role
     if (strtolower($id['role']) != 'admin') {
         $this->flash->addMessage('flash', 'Access Denied');
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('stratagies'));
     }
     $params = $this->getParams($strategy);
     if ($request->isPost()) {
         $data = $request->getParams();
         $options = [];
         foreach ($data as $key => $value) {
             if (!$params || $params && in_array($key, $params)) {
                 $options[$key] = $value;
             }
         }
         $strategy->params = $options;
         $aid = R::store($strategy);
         $this->flash->addMessage('flash', "Strategy updated");
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('editstrategy', ['uid' => $aid]));
     }
     $viewData['strategy'] = $strategy;
     $viewData['params'] = $params;
     $this->view->render($response, 'strategyoptions.twig', $viewData);
     return $response;
 }
Ejemplo n.º 24
0
 public function logout(Request $request, Response $response, array $args)
 {
     $this->logger->info("Logout request action");
     $this->authenticator->clearIdentity();
     return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('homepage'));
 }
 protected function storeCurrentUrlInSession(Request $request)
 {
     $currentUrl = $request->getUri();
     $_SESSION['authentication.attempted_url'] = $currentUrl;
 }
 public function register(Request $request, Response $response, array $args)
 {
     /** @var Users $users */
     $users = $this->data(Users::class);
     $input = $request->getParsedBody();
     $validator = $this->validator->rule('required', ['email', 'username', 'fullname', 'password', 'repassword', 'job_id', 'gender_id', 'province_id', 'area']);
     $validator->addRule('assertEmailNotExists', function ($field, $value, array $params) use($users) {
         return !$users->assertEmailExists($value);
     }, 'tersebut sudah terdaftar! Silahkan gunakan email lain');
     $validator->addRule('assertUsernameNotExists', function ($field, $value, array $params) use($users) {
         $protected = ['admin', 'account', 'login', 'register', 'logout', 'activate', 'reactivate', 'regionals', 'forgot-password', 'reset-password'];
         return !in_array($value, $protected) && !$users->assertUsernameExists($value);
     }, 'tersebut sudah terdaftar! Silahkan gunakan username lain');
     $validator->rules(['regex' => [['fullname', ':^[A-z\\s]+$:'], ['username', ':^[A-z\\d\\-\\_]+$:']], 'email' => 'email', 'assertEmailNotExists' => 'email', 'assertUsernameNotExists' => 'username', 'dateFormat' => [['birth_date', 'Y-m-d']], 'equals' => [['repassword', 'password']], 'notIn' => [['username', 'password']], 'lengthMax' => [['username', 32], ['fullname', 64], ['area', 64]], 'lengthMin' => [['username', 6], ['password', 6]]]);
     if ($validator->validate()) {
         $emailAddress = $input['email'];
         $activationKey = md5(uniqid(rand(), true));
         $activationExpiredDate = date('Y-m-d H:i:s', time() + 172800);
         // 48 jam
         $registerSuccessMsg = 'Haayy <strong>' . $input['fullname'] . '</strong>,<br> Submission keanggotan sudah berhasil disimpan. Akan tetapi account anda tidak langsung aktif. Demi keamanan dan validitas data, maka sistem telah mengirimkan email ke email anda, untuk melakukan aktivasi account. Segera check email anda! Terimakasih ^_^';
         try {
             $input['activation_key'] = $activationKey;
             $input['expired_date'] = $activationExpiredDate;
             $input['fullname'] = ucwords($input['fullname']);
             $input['password'] = $this->salt($input['password']);
             if ($userId = $users->create($input)) {
                 $emailSettings = $this->settings->get('email');
                 $message = \Swift_Message::newInstance('PHP Indonesia - Aktivasi Membership')->setFrom([$emailSettings['sender_email'] => $emailSettings['sender_name']])->setTo([$emailAddress => $member['fullname']])->setBody(file_get_contents(APP_DIR . 'views' . _DS_ . 'email' . _DS_ . 'activation.txt'));
                 $this->mailer->registerPlugin(new \Swift_Plugins_DecoratorPlugin([$emailAddress => ['{email_address}' => $emailAddress, '{fullname}' => $input['fullname'], '{registration_date}' => date('d-m-Y H:i:s'), '{activation_path}' => $this->router->pathFor('membership-activation', ['uid' => $userId, 'activation_key' => $activationKey]), '{activation_expired_date}' => $activationExpiredDate, '{base_url}' => $request->getUri()->getBaseUrl()]]));
                 $this->mailer->send($message);
                 // Update email sent status
                 $this->data(UsersActivations::class)->update(['email_sent' => 'Y'], ['user_id' => $userId, 'activation_key' => $activationKey]);
             }
         } catch (\Swift_TransportException $e) {
             $registerSuccessMsg .= '<br><br><strong>Kemungkinan email akan sampai agak terlambat, karena email server kami sedang mengalami sedikit kendala teknis. Jika anda belum juga mendapatkan email, maka jangan ragu untuk laporkan kepada kami melalu email: report@phpindonesia.or.id</strong>';
         } catch (\PDOException $e) {
             $this->addFormAlert('error', 'System failed<br>' . $e->getMessage());
             return $response->withRedirect($this->router->pathFor('membership-register'));
         }
         $this->addFormAlert('success', $registerSuccessMsg);
     } else {
         $this->addFormAlert('warning', 'Some of mandatory fields is empty!', $validator->errors());
         return $response->withRedirect($this->router->pathFor('membership-register'));
     }
     return $response->withRedirect($this->router->pathFor('membership-index'));
 }
Ejemplo n.º 27
0
 public function testGetUri()
 {
     $uri = Uri::createFromString('https://example.com:443/foo/bar?abc=123');
     $headers = new Headers();
     $cookies = [];
     $serverParams = [];
     $body = new RequestBody();
     $request = new Request('GET', $uri, $headers, $cookies, $serverParams, $body);
     $this->assertSame($uri, $request->getUri());
 }