public function indexAction() { $request = new Request(); $this->view->setVar("title", "Інспектори"); $search = trim($request->get("search")); $pageCount = $request->get("page-count") ? $request->get("page-count") : $this->session->get("page-count"); if ($pageCount) { $this->session->set("page-count", $pageCount); } $orderColumn = trim($request->get("order-column")) . " " . trim($request->get("order-type")); $offset = $request->get("page") * $pageCount - $pageCount; $inspectorsQuery = \Users::query()->rightJoin("UserGroups")->where("UserGroups.group_id = 3"); $pageCount = $pageCount ? $pageCount : self::$ITEMS_ON_PAGE; $inspectorsQuery->limit($pageCount, $offset >= 0 ? $offset : null); if ($orderColumn and !empty($orderColumn)) { $inspectorsQuery->orderBy(trim($orderColumn) ? $orderColumn : "last_name ASC"); } if ($search and !empty($search)) { $searchBind = "'%" . $search . "%'"; $inspectorsQuery->andWhere("name LIKE {$searchBind} OR last_name LIKE {$searchBind} OR second_name LIKE {$searchBind} OR email LIKE {$searchBind} OR pmobile LIKE {$searchBind}"); } $paginator = new \Phalcon\Paginator\Adapter\Model(array("data" => $inspectorsQuery->execute(), "limit" => $pageCount ? $pageCount : self::$ITEMS_ON_PAGE, "page" => $request->get("page"))); $page = $paginator->getPaginate(); $this->view->page = $page; $this->view->countItems = count($page->items); $this->view->search = $search; $this->view->orderColumn = $request->get("order-column"); $this->view->orderType = $request->get("order-type"); $this->view->pageCount = $pageCount; }
/** * executed before each test */ public function _before() { $this->markTestSkipped('Mocking up php functions doesnt work for zephir extensions.'); $_FILES = ['photo' => ['name' => ['f0', 'f1', ['f2', 'f3'], [[[['f4']]]]], 'type' => ['text/plain', 'text/csv', ['image/png', 'image/jpeg'], [[[['application/octet-stream']]]]], 'tmp_name' => ['t0', 't1', ['t2', 't3'], [[[['t4']]]]], 'error' => [0, 0, [0, 0], [[[[8]]]]], 'size' => [10, 20, [30, 40], [[[[50]]]]]]]; $request = new Request(); $request->setDI($this->tester->getApplication()->getDI()); $uploadedFiles = $request->getUploadedFiles(); $files = []; /** @var Request\File $file */ foreach ($uploadedFiles as $file) { $files[] = ['name' => $file->getName(), 'tmp_name' => $file->getTempName(), 'type' => $file->getType(), 'size' => $file->getSize(), 'error' => $file->getError()]; } $this->files = $files; Test::func('Phalcon\\Validation\\Validator', 'getimagesize', function ($tmpName) { $tmpSizes = ['t0' => null, 't1' => null, 't2' => [500, 500], 't3' => [1000, 1000], 't4' => null]; return $tmpSizes[$tmpName]; }); Test::func('Phalcon\\Validation\\Validator', 'finfo_open', function ($mimeType) { return null; }); Test::func('Phalcon\\Validation\\Validator', 'finfo_file', function ($tmp, $tmpName) { $tmpTypes = ['t0' => 'text/plain', 't1' => 'text/csv', 't2' => 'image/png', 't3' => 'image/jpeg', 't4' => 'application/octet-stream']; return $tmpTypes[$tmpName]; }); Test::func('Phalcon\\Validation\\Validator', 'is_uploaded_file', function ($tmpName) { return true; }); Test::func('Phalcon\\Validation\\Validator', 'finfo_close', function ($tmp, $tmpName) { }); $_SERVER["REQUEST_METHOD"] = "POST"; }
public function setUp() { $di = new DI(); $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/path?foo=aaa&bar=bbb'; $_GET = array('_url' => '/path', 'foo' => 'aaa', 'bar' => 'bbb'); $request = new Request(); $request->setDI($di); $this->request = $request; $response = new Response(); $response->setDI($di); $this->response = $response; $eventsManager = new Manager(); $cors = new Cors(array(array('domain' => 'bar.com'))); $di->set('request', $request, true); $di->set('response', $response, true); $di->set('eventsManager', $eventsManager); $di->set('cors', $cors); $this->di = $di; $application = new Application(); $application->setDI($di); $application->setEventsManager($eventsManager); $this->application = $application; }
/** * @param View $view */ protected function _renderJsonp(View $view) { $content = $this->getResponse()->setContentType('application/json')->setJsonContent($view->getParamsToView())->getContent(); $content = $this->request->get('callback') . '(' . $content . ')'; $this->response->setContent($content)->send(); $view->setRenderLevel(View::LEVEL_NO_RENDER); }
public function registerAction() { return $this->handleRequest(function () { $req = new Request(); if ($req->isPost()) { $post = json_decode($req->getRawBody()); $a = $this->getUserDocument(); $user = new $a(); $user->salt = Text::random(Text::RANDOM_ALNUM); $user->password = $this->hash($post->password, $user->salt); unset($post->password); $post = (array) $post; foreach ($post as $key => $value) { $user->{$key} = $value; } $user->save(); $this->session->set('user', $user); } else { if ($req->isOptions()) { return ''; } } return $this->jsonOutput($user); }); }
/** * */ public function setUp() { $di = new DI(); $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['REQUEST_METHOD'] = 'GET'; $_SERVER['REQUEST_URI'] = '/path?foo=aaa&bar=bbb'; $_GET = array('_url' => '/path', 'foo' => 'aaa', 'bar' => 'bbb'); $request = new Request(); $request->setDI($di); $this->request = $request; $response = new Response(); $response->setDI($di); $dispatcher = new Dispatcher(); $dispatcher->setDI($di); $this->dispatcher = $dispatcher; $cache = new BackendCache(new FrontendCache()); $di->set('viewCache', $cache); $config = new Config(array('cache' => array('enable' => true))); $di->set('config', $config); $eventsManager = new Manager(); $di->set('request', $request, true); $di->set('response', $response, true); $di->set('dispatcher', $dispatcher, true); $di->set('eventsManager', $eventsManager); $this->di = $di; $application = new Application(); $application->setDI($di); $application->setEventsManager($eventsManager); $this->application = $application; }
/** * @brief parseRequest 解析请求方式 * * @Returns */ protected function parseRequest() { $request = new Request(); $res = 1; foreach ($this->rules['_request'] as $_req) { switch ($_req) { case 'ajax': if ($request->isAjax()) { $res = $res & 1; } break; case 'soap': if ($request->isSoapRequested()) { $res = $res & 1; } break; case 'secure': if ($request->isSecureRequest()) { $res = $res & 1; } break; default: $res = $res & 0; break; } } if (!$res) { $this->reqErr = true; return false; } else { return true; } }
/** * Get request body from client */ public function getRequestBody() { $request = new Request(); if ($request->getContentType() != 'application/json') { throw new \Exception("Wrong content type"); } return $request->getJsonRawBody(); }
/** * Renders the uncaught exception (default implementation). * * @param Phalcon\Http\Request $request * @param Phalcon\Http\Response $response * @param \Exception $exception * @return void */ public function render(Request $request, Response $response, Exception $exception) { if ($request->isAjax()) { $this->renderAJAX($response, $exception); } else { $this->renderBrowser($response, $exception); } $response->setStatusCode(500, 'Internal Error'); }
public function __construct(Request $request) { if (strpos($request->getURI(), 'index.php') || strpos($request->getURI(), 'index.html')) { header('HTTP/1.0 301 Moved Permanently'); $replaced_url = str_replace(['index.php/', 'index.php', 'index.html'], ['', '', ''], str_replace('?', '', $request->getURI())); header('Location: http://' . $request->getHttpHost() . $replaced_url); exit(0); } }
public function passThrouthMiddleWares(Request $request, Response $response, Dispatcher $dispatcher) { $route = $this->getMatchedRoute(); if (null == $route) { $r = $this->getDI()->get('router'); $r->handle($request->getURI()); $route = $r->getMatchedRoute(); //为什么搜索“装备”会出现找不到路由的问题?估计与字符处理有关系 if (null == $route) { die('url地址无效,找不到对应的路由设置!'); } } $pattern = $route->getPattern(); //对每个路由都进行验证的中间件! @todo 如果是get方式的话,目标对象如何获取呢?当前用户是否拥有该资源? foreach ($this->middlewaresForEveryRoute as $validator) { $data = null; if (preg_match('|.*:.*|', $validator)) { //此处设置了可以带中间件参数 list($validator, $data) = explode(':', $validator); $data = $dispatcher->getParam($data); } /** @var myValidation $validator */ $validator = new $validator(); if (!in_array($route->getName(), $validator->excludedRoutes) and !$validator->isValid($data)) { $url = $validator->getRedirectedUrl(); // dd($url); $response->redirect($url, true); return false; } } //@todo 如果是get方式的如何过滤呢?应该如何设置才是正常的呢?例如get方式的search的过滤,单独处理?也许吧? if ($this->hasMatchedMiddleWares($pattern) and $request->isPost()) { $middleWares = $this->getMiddleWares($pattern); foreach ($middleWares as $validator) { $data = $request->getPost(); // dd($validator); if (preg_match('|[^:]+:[^:]+|', $validator)) { list($validator, $data) = explode(':', $validator); $data = $dispatcher->getParam($data); } if (preg_match('|.*Rules$|', $validator)) { $rules = new $validator(); $validator = (new myValidation())->take($rules); } else { $validator = new $validator(); } if (!$validator->isValid($data)) { $url = $validator->getRedirectedUrl(); // dd($url); $response->redirect($url, true); return false; } } } return true; }
public function __construct(Dispatcher $dispatcher, Request $request, Router $router, View $view) { if ($view->getLayout() == 'admin') { return; } $match_url_entry = $this->matchingUrl($request->getURI()); if ($match_url_entry) { $this->pick($match_url_entry); } }
private function composeCheckData() { $data = array(); if ($this->method == \core\RuleBase::$methodPost) { $data = $this->request->getPost(); } else { $data = $this->request->getQuery(); } $this->formData = $data; }
/** * 初始化客户端IP地址 * * @return string */ public static function initClientIp() { if (self::$request === null) { self::$request = new Request(); } $ip = self::$request->getClientAddress(); if ($ip == "::1") { $ip = "127.0.0.1"; } self::$clientIp = $ip; }
/** * Выполняет обработку запроса * * @param \Phalcon\Http\Request $request * @param \Kladr\Core\Plugins\Base\PluginResult $prevResult * @return \Kladr\Core\Plugins\Base\PluginResult */ public function process(Request $request, PluginResult $prevResult) { if ($prevResult->error) { return $prevResult; } $userKey = $request->getQuery('token'); $user = $this->userService->getUserByKey($userKey); $this->userService->logUser($user); $prevResult->user = $user; return $prevResult; }
/** * インスタンスを生成 * Logger constructor. * @param null $fileName ファイル名を指定。デフォルトはmain設定ファイルのlog_file_format */ public function __construct($fileName = null) { if ((bool) $fileName) { $logFile = LOGS_PATH . $fileName; } else { $logFile = LOGS_PATH . APPS_MAIN_CONF['log_file_name_format']; } $this->logger = new File($logFile); $req = new Request(); $uri = $req->getURI(); $this->logger->setFormatter(new LogFormatter("[%date%][{$uri}][%type%] %message%")); }
public function addToExitedList(Lists $list, Request $request) { $data = $request->getPost(); $listable = new Listables(); $listable->list_id = $list->id; $listable->user_id = $this->getDI()->getShared('session')->get('auth')['id']; //后面需要替换成登录用户id $listable->listable_type = get_class($this); $listable->listable_id = $this->id; if (isset($data['comment'])) { $listable->comment = $data['comment']; } $listable->save(); }
/** * PHPWebDevelopers\Api\Common\Http\Response constructor * * @param string $content * @param int $code * @param string $status */ public function __construct($content = null, $code = null, $status = null) { parent::__construct($content, $code, $status); $request = new PhalconRequest(); //@TODO Security fail!! Please do not go with this BETA $origin = $request->getHeader("ORIGIN"); if (!empty($origin)) { parent::setHeader("Access-Control-Allow-Origin", $origin); } parent::setContentType(self::CONTENT_TYPE_JSON, self::CHARSET); parent::setHeader("Access-Control-Allow-Methods", self::ALLOW_METHODS); parent::setHeader("Access-Control-Allow-Headers", self::ALLOW_HEADERS); parent::setHeader("Access-Control-Allow-Credentials", self::ALLOW_CREDENTIALS); }
public function setupAction() { $request = new Request(); if ($request->isPost()) { $password = $request->getPost('password'); $userType = $request->getPost('userType'); $user = Users::findFirst("type = '" . $userType . "'"); if (!$user) { $user = new Users(); $user->setType($userType); } $user->setPass($this->security->hash($password)); $user->save(); } }
/** * Get the body of a POST or PUT. * * Used for fetching the post parameters and to calculate the body signature. * * @return string null when no body present (or wrong content type for body) */ public function getRequestBody() { if ($this->_rawBody === null) { $body = null; if ($this->getContentType() == 'multipart/form-data') { $body = \function_exists("http_get_request_body") ? http_get_request_body() : @$_POST[0]; } else { if ($this->request->getMethod() == 'POST' || $this->request->getMethod() == 'PUT') { $body = ''; $fh = @fopen('php://input', 'r'); if ($fh) { while (!feof($fh)) { $s = fread($fh, 1024); if (is_string($s)) { $body .= $s; } } fclose($fh); } } } $this->_rawBody = $body; } return $this->_rawBody; }
public function reset() { if (!$this->multiLocale) { return; } $this->request or $this->request = static::$di->getShared('request'); if ($locale = $this->request->get('_locale')) { $this->_setLocale($locale); return; } if (($cookie = Cookies::get('locale')) && ($locale = $cookie->useEncryption(false)->getValue())) { $this->_setLocale($locale); $cookie->setHttpOnly(false)->delete(); return; } if ($locale = Session::get('current_locale')) { $this->loadLocale($this->currentLocale = $locale); return; } // @codeCoverageIgnoreStart if ($this->detectClientLocale) { $this->_setLocale($this->request->getBestLanguage()); return; } // @codeCoverageIgnoreEnd $this->loadLocale($this->currentLocale = $this->defaultLocale); }
/** * Выполняет обработку запроса * * @param \Phalcon\Http\Request $request * @param \Kladr\Core\Plugins\Base\PluginResult $prevResult * @return \Kladr\Core\Plugins\Base\PluginResult */ public function process(Request $request, PluginResult $prevResult) { if ($prevResult->error) { return $prevResult; } $userKey = $request->getQuery('token'); $tokens = array(); include __DIR__ . '/../../config/enabled_tokens.php'; if (trim($userKey) == '' || !in_array($userKey, $tokens)) { $prevResult->error = true; $prevResult->errorCode = 403; $prevResult->errorMessage = 'Неверный token'; return $prevResult; } return $prevResult; }
/** * Логирует запрос * @param \Phalcon\Http\Request $request */ public function log(Request $request) { $token = trim($request->get('token')); $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; $host = parse_url($referer); $host = $host['host']; if ($token != '') { $this->googleTracker->setClientID($token); } $page = new \Racecore\GATracking\Tracking\Page(); $page->setDocumentPath($referer != '' ? $referer : '/'); $page->setDocumentTitle($referer != '' ? $referer : 'Direct'); $this->googleTracker->addTracking($page); $event = new \Racecore\GATracking\Tracking\Event(); $event->setEventCategory('Token_' . $request->get('token')); $event->setEventLabel($host); $event->setEventAction('Hit'); $this->googleTracker->addTracking($event); try { $this->googleTracker->send(); } catch (Exception $e) { //echo 'Error: ' . $e->getMessage() . '<br />' . "\r\n"; //echo 'Type: ' . get_class($e); } }
public function updateAction() { $request = new Request(); if ($request->isPost()) { $donations = Donations::find(); $validIds = $request->getPost(); foreach ($donations as $donation) { if (in_array($donation->getId(), $validIds)) { $donation->setVerified(1); } else { $donation->setVerified(0); } $donation->save(); } } $this->dispatcher->forward(array('controller' => 'admin', 'action' => 'index')); }
public function __construct() { if (!self::isAvailable()) { throw new ProviderException('CURL extension is not loaded'); } $this->handle = curl_init(); $this->initOptions(); parent::__construct(); }
/** * Выполняет обработку запроса * * @param \Phalcon\Http\Request $request * @param \Kladr\Core\Plugins\Base\PluginResult $prevResult * @return \Kladr\Core\Plugins\Base\PluginResult */ public function process(Request $request, PluginResult $prevResult) { if ($prevResult->error) { return $prevResult; } if (!$request->getQuery('withParent')) { return $prevResult; } $objects = $this->cache->get('FindParentsPlugin', $request); $result = $prevResult; if ($objects === null) { $objects = $result->result; switch ($request->getQuery('contentType')) { case Regions::ContentType: foreach ($objects as $key => $object) { $objects[$key]['parents'] = self::findParents(Regions::getCodes($object['id'])); } break; case Districts::ContentType: foreach ($objects as $key => $object) { $objects[$key]['parents'] = self::findParents(Districts::getCodes($object['id'])); } break; case Cities::ContentType: foreach ($objects as $key => $object) { $objects[$key]['parents'] = self::findParents(Cities::getCodes($object['id'])); } break; case Streets::ContentType: foreach ($objects as $key => $object) { $objects[$key]['parents'] = self::findParents(Streets::getCodes($object['id'])); } break; case Buildings::ContentType: foreach ($objects as $key => $object) { $objects[$key]['parents'] = self::findParents(Buildings::getCodes($object['id'])); } break; } $this->cache->set('FindParentsPlugin', $request, $objects); } $result->result = $objects; return $result; }
/** * Convert to array * * @return array */ public function toArray($shuffle = true) { $this->setIp($this->getIp() ? $this->getIp() : $this->request->getClientAddress()); $this->setDomain($this->getDomain() ? $this->getDomain() : $_SERVER['SERVER_NAME']); $data = ['uid' => $this->getUid(), 'exp' => $this->getExp(), 'ip' => $this->getIp(), 'domain' => $this->getDomain(), 'salt' => $this->getSalt(), 'remember_token' => $this->getRememberToken()]; if ($shuffle) { $data = $this->shuffle_assoc($data); } return $data; }
/** * Preenche os registros a serem exibidos na pagina solicitada * * @return \wsGerProj\Http\GetResponse */ private function setResults() { if ($this->request->getQuery(DefaultParams::SKIP_PAGINATION)) { $this->retorno->results = $this->data; } else { $startRow = ($this->currentPage - 1) * Settings::RECORDS; $this->retorno->results = array_slice($this->data, $startRow, Settings::RECORDS); } return $this; }
public function getPut($name = null, $filters = null, $defaultValue = null, $notAllowEmpty = false, $noRecursive = false) { if ($this->isJson()) { $put = $this->getJsonRawBody(); if ($name) { return isset($put[$name]) ? $put[$name] : null; } return $put; } return parent::getPut($name, $filters, $defaultValue, $notAllowEmpty, $noRecursive); }
public function uploadAndStoreAttachment(\Phalcon\Http\Request $request) { $user = \Phalcon\Di::getDefault()->get('auth'); /** @var myModel $this */ foreach ($request->getUploadedFiles() as $f) { $data = []; $data['name'] = $f->getName(); $data['url'] = myTools::storeAttachment($f); $data['user_id'] = $user->id; $data['attachable_id'] = $this->id; $data['attachable_type'] = get_class($this); (new Attachments())->save($data); $this->increaseCount('attachmentCount'); } if (is_a($this, 'Tags')) { $meta = $this->getTagmetaOrNew(); $meta->save(); } return $this; }