/** * Test Router Url */ public function testRouterFullUrl() { if (!isset($_SERVER['SERVER_NAME'])) { $_SERVER['SERVER_NAME'] = 'localhost'; } $this->assertEquals('http://' . $_SERVER['SERVER_NAME'] . '/', Router::getFullUrl()); }
/** * Test run Error Controller */ public function testErrorController() { // setup Request $request = new ServerRequest([], [], uniqid('module') . '/' . uniqid('controller'), Request::METHOD_GET); Request::setInstance($request); // run Application $this->getApp()->process(); $this->assertEquals(Router::getErrorModule(), $this->getApp()->getModule()); $this->assertEquals(Router::getErrorController(), $this->getApp()->getController()); }
/** * @param array $data * @throws Exception * @throws ValidatorException * @return integer */ public function createOne($data) { // password $password = $data['password'] ?? null; $password2 = $data['password2'] ?? null; if (empty($password)) { throw ValidatorException::exception('password', __('Password can\'t be empty')); } if ($password !== $password2) { throw ValidatorException::exception('password2', __('Password is not equal')); } if ($data['id'] == '') { unset($data['id']); } /** @var $row Row */ $row = $this->getTable()->create(); $row->setFromArray($data); $row->status = Table::STATUS_PENDING; $row->save(); $userId = $row->id; // create auth Auth\Table::getInstance()->generateEquals($row, $password); // create activation token // valid for 5 days $actionRow = UsersActions\Table::getInstance()->generate($userId, UsersActions\Table::ACTION_ACTIVATION, 5); // send activation email // generate activation URL $activationUrl = Router::getFullUrl('users', 'activation', ['code' => $actionRow->code, 'id' => $userId]); $subject = "Activation"; $body = Application::getInstance()->dispatch('users', 'mail/template', ['template' => 'registration', 'vars' => ['user' => $row, 'activationUrl' => $activationUrl, 'password' => $password]])->render(); try { $mail = Mailer::create(); $mail->Subject = $subject; $mail->msgHTML(nl2br($body)); $mail->addAddress($data['email']); Mailer::send($mail); } catch (\Exception $e) { Logger::log('error', $e->getMessage(), ['module' => 'users', 'controller' => 'change-email', 'userId' => $userId]); throw new Exception('Unable to send email. Please contact administrator.'); } // show notification and redirect Messages::addSuccess("Your account has been created and an activation link has" . "been sent to the e-mail address you entered.<br/>" . "Note that you must activate the account by clicking on the activation link" . "when you get the e-mail before you can login."); // wtf? // redirectTo('index', 'index'); return $userId; }
"> <i class="fa fa-eye fa-fw"></i> <strong><?php echo $active; ?> </strong> <small><?php echo __('Active Users'); ?> </small> </a> </li> <li class="divider"></li> <li> <a href="<?php echo Router::getUrl('users', 'profile', ['id' => $last['id']]); ?> "> <i class="fa fa-user fa-fw"></i> <strong><?php echo $last['login']; ?> </strong> <small><?php echo __('Last Registers'); ?> </small> </a> </li> </ul> </div>
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ /** * @namespace */ namespace Bluz\View\Helper; use Bluz\Proxy\Router; use Bluz\View\View; return function ($file = null) { // setup baseUrl if (!$this->baseUrl) { $this->baseUrl = Router::getBaseUrl(); // clean script name if (isset($_SERVER['SCRIPT_NAME']) && ($pos = strripos($this->baseUrl, basename($_SERVER['SCRIPT_NAME']))) !== false) { $this->baseUrl = substr($this->baseUrl, 0, $pos); } } // Remove trailing slashes if (null !== $file) { $file = ltrim($file, '/\\'); } return rtrim($this->baseUrl, '/') . '/' . $file; };
/** * Do process * @return void */ protected function doProcess() { Logger::info("app:process:do"); $module = Request::getModule(); $controller = Request::getController(); $params = Request::getAllParams(); // try to dispatch controller try { // get reflection of requested controller $controllerFile = $this->getControllerFile($module, $controller); $reflection = $this->reflection($controllerFile); // check header "accept" for catch JSON(P) or XML requests, and switch presentation // it's some magic for AJAX and REST requests if ($produces = $reflection->getAccept() and $accept = $this->getRequest()->getAccept()) { // switch statement for $accept switch ($accept) { case Request::ACCEPT_HTML: // with layout // without additional presentation break; case Request::ACCEPT_JSON: $this->useJson(); break; case Request::ACCEPT_JSONP: $this->useJsonp(); break; case Request::ACCEPT_XML: $this->useXml(); break; default: // not acceptable MIME type throw new NotAcceptableException(); break; } } // check call method(s) if ($reflection->getMethod() && !in_array(Request::getMethod(), $reflection->getMethod())) { throw new NotAllowedException(join(',', $reflection->getMethod())); } // check HTML cache if ($reflection->getCacheHtml() && Request::getMethod() == Request::METHOD_GET) { $htmlKey = 'html:' . $module . ':' . $controller . ':' . http_build_query($params); if ($cachedHtml = Cache::get($htmlKey)) { Response::setBody($cachedHtml); return; } } // dispatch controller $dispatchResult = $this->dispatch($module, $controller, $params); } catch (RedirectException $e) { Response::setException($e); if (Request::isXmlHttpRequest()) { // 204 - No Content Response::setStatusCode(204); Response::setHeader('Bluz-Redirect', $e->getMessage()); } else { Response::setStatusCode($e->getCode()); Response::setHeader('Location', $e->getMessage()); } return null; } catch (ReloadException $e) { Response::setException($e); if (Request::isXmlHttpRequest()) { // 204 - No Content Response::setStatusCode(204); Response::setHeader('Bluz-Reload', 'true'); } else { Response::setStatusCode($e->getCode()); Response::setHeader('Refresh', '0; url=' . Request::getRequestUri()); } return null; } catch (\Exception $e) { Response::setException($e); // cast to valid HTTP error code // 500 - Internal Server Error $statusCode = 100 <= $e->getCode() && $e->getCode() <= 505 ? $e->getCode() : 500; Response::setStatusCode($statusCode); $dispatchResult = $this->dispatch(Router::getErrorModule(), Router::getErrorController(), array('code' => $e->getCode(), 'message' => $e->getMessage())); } if ($this->hasLayout()) { Layout::setContent($dispatchResult); $dispatchResult = Layout::getInstance(); } if (isset($htmlKey, $reflection)) { // @TODO: Added ETag header Cache::set($htmlKey, $dispatchResult(), $reflection->getCacheHtml()); Cache::addTag($htmlKey, $module); Cache::addTag($htmlKey, 'html'); Cache::addTag($htmlKey, 'html:' . $module); Cache::addTag($htmlKey, 'html:' . $module . ':' . $controller); } Response::setBody($dispatchResult); }
/** * Assert forbidden * * @return void */ protected function assertForbidden() { $exception = Response::getException(); $this->assertInstanceOf('\\Bluz\\Application\\Exception\\ForbiddenException', $exception); $this->assertEquals(403, Response::getStatusCode()); $this->assertModule(Router::getErrorModule()); $this->assertController(Router::getErrorController()); }
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ /** * @namespace */ namespace Bluz\Application\Helper; use Bluz\Application\Application; use Bluz\Proxy\Router; return function ($module = 'index', $controller = 'index', $params = array()) { $url = Router::getUrl($module, $controller, $params); $this->redirect($url); };
<?php /** * @author Anton Shevchuk * @created 22.10.12 18:40 */ namespace Application; use Bluz\Proxy\Router; return function () { /** * @var Bootstrap $this */ ?> <a href="<?php echo Router::getUrl('facebook', 'auth'); ?> " class="btn fa fa-facebook-square fa-2x"></a> <?php };
/** * Method POST * * @return array|false * @throws BadRequestException * @throws NotImplementedException */ public function methodPost() { if (!empty($this->primary)) { // POST + ID is incorrect behaviour throw new NotImplementedException(); } try { $result = $this->createOne($this->data); if (!$result) { // system can't create record with this data throw new BadRequestException(); } if (is_array($result)) { $result = join('-', array_values($result)); } } catch (ValidatorException $e) { Response::setStatusCode(400); return ['errors' => $e->getErrors()]; } Response::setStatusCode(201); Response::setHeader('Location', Router::getUrl(Request::getModule(), Request::getController()) . '/' . $result); return false; // disable view }
/** * Get controller * * @return string */ public static function getController() { return self::getParam('_controller', Router::getDefaultController()); }
* @accept JSON * @method POST * * @param \Bluz\Crud\Table $crud * @param mixed $primary * @param array $data * @return void|array * @throws BadRequestException * @throws NotImplementedException */ return function ($crud, $primary, $data) { if (!empty($primary)) { // POST + ID is incorrect behaviour throw new NotImplementedException(); } try { $result = $crud->createOne($data); if (!$result) { // system can't create record with this data throw new BadRequestException(); } if (is_array($result)) { $result = join('-', array_values($result)); } } catch (ValidatorException $e) { Response::setStatusCode(400); return ['errors' => $e->getErrors()]; } Response::setStatusCode(201); Response::setHeader('Location', Router::getUrl(Request::getModule(), Request::getController()) . '/' . $result); };
/** * Prepare request for processing */ public function __construct() { // HTTP method $method = Request::getMethod(); $this->method = strtoupper($method); // get path // %module% / %controller% / %id% / %relation% / %id% $path = Router::getCleanUri(); $this->params = explode('/', rtrim($path, '/')); // module $this->module = array_shift($this->params); // controller $this->controller = array_shift($this->params); $data = Request::getParams(); unset($data['_method'], $data['_module'], $data['_controller']); $this->data = $data; }
/** * Denied access * @param ForbiddenException $exception * @return \Bluz\Controller\Controller|null */ public function forbidden(ForbiddenException $exception) { if (AuthProxy::getIdentity()) { $message = Translator::translate("You don't have permissions to access this page"); } else { $message = Translator::translate("You don't have permissions, please sign in"); } // for AJAX and API calls (over JSON) $jsonOrApi = Request::isXmlHttpRequest() || Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON; // for guest, for requests if (!AuthProxy::getIdentity() && !$jsonOrApi) { // save URL to session and redirect make sense if presentation is null Session::set('rollback', Request::getUri()->__toString()); // add error notice Messages::addError($message); // redirect to Sign In page $url = Router::getUrl('users', 'signin'); return $this->redirect($url); } else { return $this->error(new ForbiddenException($message, 403, $exception)); } }
/** * Pre process * @return void */ protected function preProcess() { Logger::info("app:process:pre"); Router::process(); }
/** * Pre process * * @return void * @throws ApplicationException */ protected function preProcess() { Router::process(); // disable Layout for XmlHttpRequests if (Request::isXmlHttpRequest()) { $this->layoutFlag = false; } // switch to JSON response based on Accept header if (Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON) { $this->layoutFlag = false; Response::switchType('JSON'); } }
/** * Redirect to controller * * @param string $module * @param string $controller * @param array $params * @return void */ public static function redirectTo($module = 'index', $controller = 'index', $params = []) { $url = Router::getUrl($module, $controller, $params); self::redirect($url); }
/** * Test Helper RedirectTo * * @expectedException \Bluz\Application\Exception\RedirectException */ public function testHelperRedirectTo() { Response::redirectTo(Router::getDefaultModule(), Router::getDefaultController()); }
* @link https://github.com/bluzphp/framework */ /** * @namespace */ namespace Bluz\Application\Helper; use Bluz\Application\Application; use Bluz\Controller\Controller; use Bluz\Proxy\Response; use Bluz\Proxy\Router; /** * Reload helper can be declared inside Bootstrap * @param \Exception $exception * @return Controller */ return function ($exception) { /** * @var Application $this */ Response::removeHeaders(); Response::clearBody(); // cast to valid HTTP error code // 500 - Internal Server Error $statusCode = 100 <= $exception->getCode() && $exception->getCode() <= 505 ? $exception->getCode() : 500; Response::setStatusCode($statusCode); $module = Router::getErrorModule(); $controller = Router::getErrorController(); $params = ['code' => $exception->getCode(), 'message' => $exception->getMessage()]; return $this->dispatch($module, $controller, $params); };
} // check exists $user = Users\Table::findRowWhere(['email' => $email]); if (!$user) { throw new Exception('Email not found'); } // check status, only for active users if ($user->status != Users\Table::STATUS_ACTIVE) { throw new Exception('User is inactive'); } // create activation token // valid for 5 days $actionRow = UsersActions\Table::getInstance()->generate($user->id, UsersActions\Table::ACTION_RECOVERY, 5); // send activation email // generate restore URL $resetUrl = Router::getFullUrl('users', 'recovery-reset', ['code' => $actionRow->code, 'id' => $user->id]); $subject = "Password Recovery"; $body = $this->dispatch('users', 'mail-template', ['template' => 'recovery', 'vars' => ['user' => $user, 'resetUrl' => $resetUrl]])->render(); try { $mail = Mailer::create(); // subject $mail->Subject = $subject; $mail->MsgHTML(nl2br($body)); $mail->AddAddress($user->email); Mailer::send($mail); } catch (\Exception $e) { // log it Logger::log('error', $e->getMessage(), ['module' => 'users', 'controller' => 'recovery', 'email' => $email]); throw new Exception('Unable to send email. Please contact administrator.'); } // show notification and redirect
/** * Pre process * @return void */ protected function preProcess() { Router::process(); Response::switchType('CLI'); }
/** * Get Url * * @param array $params * @return string */ public function getUrl($params) { // prepare params $params = $this->getParams($params); // retrieve URL return Router::getUrl($this->getModule(), $this->getController(), $params); }
<?php namespace Application; use Bluz\Proxy\Router; return function () { /** * @var Bootstrap $this */ ?> <a href="<?php echo Router::getUrl('google', 'auth'); ?> " class="btn fa fa-google-plus-square fa-2x"></a> <?php };
<?php /** * Generate Swagger configuration * * @author Anton Shevchuk * @created 22.08.12 17:14 */ namespace Application; use Bluz\Proxy\Router; use Swagger\Swagger; return function ($resource = null) { /** * @var Bootstrap $this */ $this->useJson(); $paths = array(PATH_APPLICATION . '/models', PATH_APPLICATION . '/modules'); $exclude = array(); $swagger = new Swagger($paths, $exclude); if ($resource) { return $swagger->getResource('/' . $resource, ['defaultBasePath' => rtrim(Router::getFullUrl(), '/')]); } else { return $swagger->getResourceList(['basePath' => '/system/api/resource']); } };
* @param bool $checkAccess * @return null|string * @throws ViewException */ return function ($module, $controller, $params = [], $checkAccess = false) { /** * @var View $this */ try { if ($checkAccess) { try { $controllerInstance = new Controller($module, $controller); $controllerInstance->checkPrivilege(); } catch (ForbiddenException $e) { return null; } } } catch (\Exception $e) { throw new ViewException('Url View Helper: ' . $e->getMessage()); } if (null === $module) { $module = Request::getModule(); } if (null === $controller) { $controller = Request::getController(); } if (null === $params) { $params = Request::getParams(); } return Router::getUrl($module, $controller, $params); };
/** * Test Router Url */ public function testRouterFullUrl() { $this->setRequestParams('/', [], [], Request::METHOD_GET); $this->assertEquals('http://127.0.0.1/', Router::getFullUrl()); }
/** * Test Helper RedirectTo * * @expectedException \Bluz\Application\Exception\RedirectException */ public function testHelperRedirectTo() { $this->getApp()->redirectTo(Router::getDefaultModule(), Router::getDefaultController()); }
try { if (empty($password)) { throw new Exception('Password is empty'); } // login/password Auth\Table::getInstance()->checkEquals($user->login, $password); // check email for unique $emailUnique = Users\Table::findRowWhere(['email' => $email]); if ($emailUnique && $emailUnique->id != $userId) { throw new Exception('User with email "' . htmlentities($email) . '" already exists'); } // generate change mail token and get full url $actionRow = UsersActions\Table::getInstance()->generate($userId, Table::ACTION_CHANGE_EMAIL, 5, ['email' => $email]); $changeUrl = Router::getFullUrl('users', 'change-email', ['token' => $actionRow->code]); $subject = __("Change email"); $body = $this->dispatch('users', 'mail/template', ['template' => 'change-email', 'vars' => ['user' => $user, 'email' => $email, 'changeUrl' => $changeUrl, 'profileUrl' => Router::getFullUrl('users', 'profile')]])->render(); try { $mail = Mailer::create(); $mail->Subject = $subject; $mail->msgHTML(nl2br($body)); $mail->addAddress($email); Mailer::send($mail); Messages::addNotice('Check your email and follow instructions in letter.'); } catch (\Exception $e) { Logger::log('error', $e->getMessage(), ['module' => 'users', 'controller' => 'change-email', 'userId' => $userId]); throw new Exception('Unable to send email. Please contact administrator.'); } // try back to index Response::redirectTo('users', 'profile'); } catch (Exception $e) { Messages::addError($e->getMessage());
<?php /** * @author Anton Shevchuk * @created 22.10.12 18:40 */ namespace Application; use Bluz\Proxy\Router; return function () { /** * @var Bootstrap $this */ ?> <a href="<?php echo Router::getUrl('twitter', 'auth'); ?> " class="btn fa fa-twitter-square fa-2x"></a> <?php };