public function testXSS() { if (!class_exists('DOMDocument')) { $this->markTestSkipped('Test skipped'); return; } $str = '<strong style="color:blue">Click</strong><div>name</div>'; $filter = new Phalcon\Filter(); $ret = $filter->sanitize('<strong style="color:blue" onclick="alert(\'clicked\')">Click</strong><div style="color:expression(1+1)">name</div>', 'xssclean'); $this->assertEquals($ret, $str); $ret = $filter->sanitize('1.1111', 'int!'); $this->assertTrue(is_int($ret)); $ret = $filter->sanitize('1.1111', 'float!'); $this->assertTrue(is_float($ret)); $ret = $filter->sanitize('-1.1111', 'abs'); $this->assertTrue($ret === 1.1111); }
/** * Get latest tagged images */ $app->get('/images/latest', function () use($app) { $url = $app->getDI()->get('imageLocation'); $sql = 'select distinct(images.id), CONCAT("' . $url . '",images.id,"_thumb.jpg") as url from images left join images_tags ON images.id = images_tags.image_id order by images_tags.created DESC limit 30'; $resultSet = $app->getDI()->get('db')->query($sql); $resultSet->setFetchMode(Phalcon\Db::FETCH_ASSOC); echo json_encode($resultSet->fetchAll()); }); /** * Set image tags */ $app->post('/image/metadata/{id:[0-9]+}', function ($id) use($app) { $request = new Phalcon\Http\Request(); $filter = new Phalcon\Filter(); $user = new Users(); $data = $request->getPost('tags', null, false); $image = Images::findFirst("id = '" . $id . "'"); $tags = []; /** * Save each tag * This is done by: * 1) Getting/creating the tag * 2) Creating an imageTag * 3) Saving the imageTag */ foreach ($data as $tagRow) { $name = $filter->sanitize($tagRow['name'], 'string'); //Get tag if it exists already $tag = Tags::findFirst("name = '" . $name . "' AND category_id = '" . $tagRow['category_id'] . "'");
<?php require_once __DIR__ . '/../app/bootstrap.php'; $di->set('filter', function () { $filter = new Phalcon\Filter(); $filter->add('string', function ($value) { return '' . $value; /* is_string($value) ? $value : ''; */ }); $filter->add('uint', function ($value) { return is_scalar($value) && preg_match('/^[0-9]+$/iD', $value) && $value >= 0 ? $value : 0; }); $filter->add('array', function ($value) { return is_array($value) ? $value : []; }); $filter->add('intbool', function ($value) { return empty($value) ? 0 : 1; }); return $filter; }, true); $di->set('request', new Phalcon\Http\Request()); $di->set('router', function () use($di) { $router = new \Phalcon\Mvc\Router(); return $router; }, true); $di->set('flash', function () { return new Phalcon\Flash\Session(['error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning']); }); $di->set('session', function () use($di) { $class = Config::instance()->session->class; session_name(Config::instance()->session->name);
private function definirVariablesCommunes() { $this->view->setVar("version", $this->config->application->version); $this->view->setVar("apps", "js/app"); $this->view->setVar("widgets", "js/widgets"); $configClient = $this->config->navigateur; $configClient->uri = $this->config->uri; $this->view->setVar("configClient", $configClient); global $application; $libelleProfil = ''; $user = ''; $count = 0; $application->getDI()->getSession()->set('page', '../' . $application->getDi()['router']->getRewriteUri()); if ($application->getDI()->getSession()->has("info_utilisateur")) { if ($application->getDI()->getSession()->get("info_utilisateur")->identifiant) { $user = $application->getDI()->getSession()->get("info_utilisateur")->identifiant; $idProfil = $application->getDI()->getSession()->get("info_utilisateur")->profilActif; if (isset($application->getDI()->getSession()->get("info_utilisateur")->profils)) { $count = count($application->getDI()->getSession()->get("info_utilisateur")->profils); foreach ($application->getDI()->getSession()->get("info_utilisateur")->profils as $value) { if ($value['id'] == $idProfil) { $libelleProfil = $value['libelle']; break; } } } if ($libelleProfil === '') { $count = 0; } } } $this->view->setVar("profil", $libelleProfil); $this->view->setVar("utilisateur", $user); $this->view->setVar("nbProfil", $count); if ($this->request->get('url') || $this->request->get('URL')) { $filter = new \Phalcon\Filter(); $filter->add('url', function ($value) { filter_var($value, FILTER_SANITIZE_URL); }); $url = $this->request->get('url') ? $this->request->get('url') : $this->request->get('URL'); $layers = $this->request->get('layers') ? $this->request->get('layers', 'string') : $this->request->get('LAYERS', 'string'); if ($layers == null && strrpos($url, 'layers') !== false) { $layers = substr($url, strrpos($url, 'layers') + 7); $url = substr($url, 0, strrpos($url, 'layers')); } if ($layers == null && strrpos($url, 'LAYERS') !== false) { $layers = substr($url, strrpos($url, 'LAYERS') + 7); $url = substr($url, 0, strrpos($url, 'LAYERS')); } $filter->sanitize($url, 'url'); $active = $layers == null ? 'false' : 'true'; $fonctionCallback = "function(e){\n var coucheWMS = new Igo.Couches.WMS(\n {\n url:'{$url}', \n nom:'{$layers}',\n fond:false,\n active:{$active},\n mode: 'getCapabilities'\n }\n );\n Igo.nav.carte.gestionCouches.ajouterCouche(coucheWMS);\n };"; $this->view->setVar("callbackInitIGO", $fonctionCallback); } else { $this->view->setVar("callbackInitIGO", 'null'); } }
/** * Reimports an old revision, creating a new revision with the old contents of the old revision in the process. */ public function reimportAction() { $id = (int) $this->dispatcher->getParam('id'); $revision = (int) $this->dispatcher->getParam('revision'); $oldRevision = Versions::findFirst(array('page_id = :id: AND version = :revision:', 'bind' => array('id' => $id, 'revision' => $revision))); $page = Pages::findFirst($id); if ($page === false) { return $this->dispatcher->forward(array('action' => 'error404')); } if ($oldRevision === false) { return $this->dispatcher->forward(array('action' => 'error404')); } $filter = new \Phalcon\Filter(); $page->content = $filter->sanitize($oldRevision->content, array('trim')); $page->update(); $curVersion = Versions::maximum(array("column" => "version", "conditions" => "page_id = :id:", "bind" => array('id' => $id))); $version = new Versions(); $version->page_id = $page->id; $version->content = $page->content; $version->version = $curVersion + 1; $version->create(); $this->viewCache->delete('page-' . $page->id); $this->modelsCache->delete('page-' . $page->title); $this->flash->success("The changes have been saved!"); return $this->response->redirect("page/" . $page->title); }
/** * Set the filter service * * @return void */ protected function filter() { $this->_di->set('filter', function () { $filter = new \Phalcon\Filter(); $filter->add('repeat', new Extension\Repeat()); $filter->add('escape', new Extension\Escape()); return $filter; }); }
function transaction($data) { $filter = new \Phalcon\Filter(); $results = array(); $services = getServices(); if (isset($data["layer"])) { $layer = $filter->sanitize($data["layer"], array("string")); $srv = $services[$layer]; } $connection = $srv->getConnection(); $connection->begin(); try { $errors = array(); $warnings = array(); if (isset($data["features"])) { $featureCollection = json_decode($data["features"]); foreach ($featureCollection->features as $feature) { if ($feature->action === "create") { $result = $srv->createFeature($feature); } else { if ($feature->action === "update") { $result = $srv->updateFeature($feature); } else { if ($feature->action === "delete") { $result = $srv->deleteFeature($feature); } else { throw new Exception("Action invalide ou indéfinit: " . $feature->action); } } } if ($result["result"] === "failure" && isset($result["error"])) { $errors[$feature->no_seq] = $result["error"]; } else { if ($result["result"] === "failure" && isset($result["errors"])) { $errors[$feature->no_seq] = $result["errors"]; } else { if ($result["result"] === "warning") { $warnings[$feature->no_seq] = $result["warning"]; } } } $srv->reset(); } } if (count($errors) > 0 || count($warnings) > 0) { $connection->rollback(); return array("result" => "failure", "errors" => $errors, "warnings" => $warnings); } $connection->commit(); } catch (\Exception $e) { $connection->rollback(); throw $e; } return array("result" => "success"); }
/** * unlock package * @param string $pkg_name package name to unlock * @return array status * @throws \Exception */ public function unlockAction($pkg_name) { $backend = new Backend(); $response = array(); if ($this->request->isPost()) { $response['status'] = 'ok'; // sanitize package name $filter = new \Phalcon\Filter(); $filter->add('pkgname', function ($value) { return preg_replace('/[^0-9a-zA-Z-_]/', '', $value); }); $pkg_name = $filter->sanitize($pkg_name, "pkgname"); // execute action $response['msg_uuid'] = trim($backend->configdpRun("firmware unlock", array($pkg_name), true)); } else { $response['status'] = 'failure'; } return $response; }
}); $di->setShared('response', function () { $response = new \Phalcon\Http\Response(); return $response; }); //注入DB服务 $di->setShared('gcoperator', function () use($di) { $dbclass = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $di['config']->v3opDB->driver; return new $dbclass(array('host' => $di['config']->v3opDB->host, 'username' => $di['config']->v3opDB->username, 'password' => $di['config']->v3opDB->password, 'dbname' => $di['config']->v3opDB->database, 'charset' => $di['config']->v3opDB->charset)); }); //注入sphinx 服务 $di->setShared('sphinxCon', function () use($di) { $conn = new \Foolz\SphinxQL\Connection(); $conn->setParams(array('host' => $di['config']->sphinx->host, 'port' => intval($di['config']->sphinx->port))); return $conn; }); $di->setShared('filter', function () { $filter = new \Phalcon\Filter(); $filter->add('price', function ($value) { return round(abs($value), 2); }); return $filter; }); $di->set('memObj', function () use($di) { $mcObj = new \Xz\Lib\Memcached($di['config']->memcommon); return $mcObj; }); $di->set('request', function () { $request = new \Phalcon\Http\Request(); return $request; });
<?php $filter = new \Phalcon\Filter(); //Using an anonymous function $filter->add('md5', function ($value) { return preg_replace('/[^0-9a-f]/', '', $value); }); //Sanitize with the "md5" filter $filtered = $filter->sanitize($possibleMd5, "md5");
<?php class IPv4Filter { public function filter($value) { return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); } } $filter = new \Phalcon\Filter(); //Using an object $filter->add('ipv4', new IPv4Filter()); //Sanitize with the "ipv4" filter $filteredIp = $filter->sanitize("127.0.0.1", "ipv4");
/** * @return mixed */ public function getExpectedFieldB() { $filter = new \Phalcon\Filter(); $value = $filter->sanitize($this->fieldB, 'email'); return $filter->sanitize($value, 'upper'); }
<?php $filter = new \Phalcon\Filter(); // returns "*****@*****.**" $filter->sanitize("some(one)@exa\\mple.com", "email"); // returns "hello" $filter->sanitize("hello<<", "string"); // returns "100019" $filter->sanitize("!100a019", "int"); // returns "100019.01" $filter->sanitize("!100a019.01a", "float");
/** * Filters a value * * @param string $paramValue * @return mixed */ protected function filter($paramValue, $filters) { $filter = new \Phalcon\Filter(); return $filter->sanitize($paramValue, $filters); }
function getLabelNameInformation($data) { $filter = new \Phalcon\Filter(); $services = getServices(); if (isset($data["layer"])) { $layer = $filter->sanitize($data["layer"], array("string")); if (!isset($services[$layer])) { throw new Exception("Le service {$layer} n'est pas disponible."); } $srv = $services[$layer]; } return $srv->getLabelName(); }
<?php // Manually applying the filter $filter = new Phalcon\Filter(); $email = $filter->sanitize($_POST["user_email"], "email"); // Manually applying the filter to the value $filter = new Phalcon\Filter(); $email = $filter->sanitize($request->getPost("user_email"), "email"); // Automatically applying the filter $email = $request->getPost("user_email", "email"); // Setting a default value if the param is null $email = $request->getPost("user_email", "email", "*****@*****.**"); // Setting a default value if the param is null without filtering $email = $request->getPost("user_email", null, "*****@*****.**");
function wms_proxy($contexteId) { global $app; $httprequest = new Phalcon\Http\Request(); $httprequest->setDI($app->getDI()); //Possible sanitize filters: string, email, int, float, alphanum, striptags, trim, lower, upper $filter = new \Phalcon\Filter(); if ($httprequest->isGet() || $httprequest->isPost()) { $datain = $httprequest->get(); $data = array(); foreach ($datain as $key => $value) { $data[strtoupper($key)] = $value; } $service = $filter->sanitize($data["SERVICE"], array("string", "upper")); $request = $filter->sanitize($data["REQUEST"], array("string", "upper")); } else { // TODO : Gérer l'erreur, on ne peut appeler un service wms en put ou en delete. error_log("not a get or a post?"); return; } error_log("service: {$service}, request: {$request}"); if ($service === "WMS") { $config = $app->getDI()->get("config"); $mapserver = $config['mapserver']['host'] . $config['mapserver']['mapserver_path'] . $config['mapserver']['executable']; $contexte = IgoContexte::findFirst("id='{$contexteId}'"); $map = $config['mapserver']['mapfileCacheDir'] . $config['mapserver']['contextesCacheDir'] . $contexte->code . ".map"; $method = $httprequest->getMethod(); $data = $httprequest->get(); $data["MAP"] = $map; $response = null; switch ($request) { case "GETCAPABILITIES": $response = proxy_request($mapserver, $data, $method); // Devrait-on enlever les couches non permises en lecture de la réponse.? C'est probablement trop complexe... break; case "GETMAP": case "GETFEATUREINFO": case "DESCRIBELAYER": case "GETLEGENDGRAPHIC": $authentificationModule = obtenirAuthentificationModule(); if ($authentificationModule === null) { $response = proxy_request($mapserver, $data, $method); } else { if (isset($data["LAYERS"])) { $couches = explode(",", $data["LAYERS"]); } else { $couches = explode(",", $data["LAYER"]); } foreach ($couches as $couche) { $igoVueContexteCoucheNavigateur = IgoVueContexteCoucheNavigateur::findFirst("mf_layer_name='{$couche}'"); $coucheContexte = array($igoVueContexteCoucheNavigateur); if ($igoVueContexteCoucheNavigateur === false) { $coucheContexte = IgoVueContexteCoucheNavigateur::find("mf_layer_group='{$couche}' and contexte_id='{$contexteId}'"); } if (count($coucheContexte) === 0) { // L'utilisateur essaie d'appeler la couche root du mapfile qui consiste à toutes les couches. // Nous interdissons ce type d'appels pour le moment. die("Forbidden"); } $estPermis = false; foreach ($coucheContexte as $igoVueContexteCoucheNavigateur) { $permission = obtenirPermission($igoVueContexteCoucheNavigateur->couche_id); if ($permission !== null && $permission->est_lecture) { $estPermis = true; break; } } if (!$estPermis) { die("Forbidden"); } } $response = proxy_request($mapserver, $data, $method); } break; default: break; } $headerArray = explode("\r\n", $response["header"]); foreach ($headerArray as $headerLine) { header($headerLine); } echo $response["content"]; } else { die("Seul les services WMS sont pris en charge par ce proxy."); } }
<?php $filter = new \Phalcon\Filter(); // returns "Hello" $filter->filter("<h1>Hello</h1>", "striptags"); // returns "Hello" $filter->filter(" Hello ", "trim");
<?php $di->setShared('filter', function () { $filter = new \Phalcon\Filter(); // Remove quotation marks (single and double): $filter->add('removeq', function ($value) { if (preg_match("/[^']'\$/", $value) and !preg_match("/^'[^']/", $value)) { return $value; } return preg_replace("/^[\"']+|[\"']+\$/u", '', $value); }); // Saxon genitive replacement: $filter->add('saxgen', function ($value) { return preg_replace("/'+/u", '’', $value); }); // Empty value null replacement: $filter->add('null', function ($value) { return strlen($value) === 0 ? null : $value; }); // Title case modifier: $filter->add('title', function ($value) { return mb_convert_case($value, MB_CASE_TITLE, 'UTF-8'); }); // Lower case modifier: $filter->add('lower', function ($value) { return mb_convert_case($value, MB_CASE_LOWER, 'UTF-8'); }); // Upper case modifier: $filter->add('upper', function ($value) { return mb_convert_case($value, MB_CASE_UPPER, 'UTF-8'); });