protected function _prepareTpl()
 {
     // Get the project and repository params
     $project = $this->param('project');
     $repository = $this->param('repository');
     $auth_url_return = $this->param('auth_url_return');
     if (!$auth_url_return) {
         $auth_url_return = jUrl::get('view~map:index', array("repository" => $repository, "project" => $project));
     }
     // Get lizmapProject class
     $assign = array('isConnected' => jAuth::isConnected(), 'user' => jAuth::getUserSession(), 'auth_url_return' => $auth_url_return, "externalSearch" => "", "edition" => false, "measure" => false, "locate" => false, "geolocation" => false, "timemanager" => false, "print" => false, "attributeLayers" => false);
     try {
         $lproj = lizmap::getProject($repository . '~' . $project);
         $configOptions = $lproj->getOptions();
         if (property_exists($configOptions, 'externalSearch')) {
             $assign['externalSearch'] = $configOptions->externalSearch;
         }
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
     }
     $this->_tpl->assign($assign);
     // Get lizmap services
     $services = lizmap::getServices();
     if ($services->allowUserAccountRequests) {
         $this->_tpl->assign('allowUserAccountRequests', True);
     }
 }
 protected function _prepareTpl()
 {
     // Get the project and repository params
     $project = $this->param('project');
     $repository = $this->param('repository');
     // Get lizmapProject class
     $assign = array("edition" => false, "measure" => false, "locate" => false, "geolocation" => false, "timemanager" => false, "print" => false, "attributeLayers" => false);
     try {
         $lproj = lizmap::getProject($repository . '~' . $project);
         $configOptions = $lproj->getOptions();
         if (property_exists($configOptions, 'measure') && $configOptions->measure == 'True') {
             $assign['measure'] = true;
         }
         $assign['locate'] = $lproj->hasLocateByLayer();
         if (property_exists($configOptions, 'print') && $configOptions->print == 'True') {
             $assign['print'] = true;
         }
         $assign['edition'] = $lproj->hasEditionLayers();
         if (property_exists($configOptions, 'geolocation') && $configOptions->geolocation == 'True') {
             $assign['geolocation'] = true;
         }
         $assign['timemanager'] = $lproj->hasTimemanagerLayers();
         $assign['attributeLayers'] = $lproj->hasAttributeLayers();
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
     }
     $this->_tpl->assign($assign);
 }
 public function getLabel2($key, $form)
 {
     $criteria = $form->getData($this->criteriaFrom[0]);
     if ($criteria && array_key_exists($criteria, $this->data)) {
         try {
             $p = lizmap::getProject($criteria . '~' . $key);
             if ($p) {
                 return (string) $p->getData('title');
             }
         } catch (UnknownLizmapProjectException $e) {
             jLog::logEx($e, 'error');
             return null;
         }
     }
     return null;
 }
 /**
  * Empty a map service cache
  * @param string $repository Repository for which to remove all tile cache
  * @return Redirection to the index
  */
 function removeLayerCache()
 {
     // Create response to redirect to the index
     $rep = $this->getResponse("redirect");
     $rep->action = "admin~config:index";
     $repository = $this->param('repository');
     $lrep = lizmap::getRepository($repository);
     if (!$lrep) {
         jMessage::add('The repository ' . strtoupper($repository) . ' does not exist !', 'error');
         return $rep;
     }
     $project = $this->param('project');
     try {
         $lproj = lizmap::getProject($lrep->getKey() . '~' . $project);
         if (!$lproj) {
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'error');
             return $rep;
         }
         $layer = $this->param('layer');
         // Remove project cache
         $lproj->clearCache();
         // Remove the cache for the layer
         lizmapProxy::clearLayerCache($repository, $project, $layer);
         jMessage::add(jLocale::get("admin~admin.cache.layer.removed", array($layer)));
         return $rep;
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
         jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'error');
         return $rep;
     }
     return $rep;
 }
 /**
  * Get parameters and set classes for the project and repository given.
  *
  * @return array List of needed variables : $params, $lizmapProject, $lizmapRepository, $lizmapCache.
  */
 protected function getServiceParameters()
 {
     // Get the project
     $project = $this->iParam('project');
     if (!$project) {
         jMessage::add('The parameter project is mandatory !', 'ProjectNotDefined');
         return false;
     }
     // Get repository data
     $repository = $this->iParam('repository');
     // Get the corresponding repository
     $lrep = lizmap::getRepository($repository);
     if (!$lrep) {
         jMessage::add('The repository ' . strtoupper($repository) . ' does not exist !', 'RepositoryNotDefined');
         return false;
     }
     // Get the project object
     $lproj = null;
     try {
         $lproj = lizmap::getProject($repository . '~' . $project);
         if (!$lproj) {
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
             return false;
         }
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
         jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
         return false;
     }
     // Redirect if no rights to access this repository
     if (!$lproj->checkAcl()) {
         jMessage::add(jLocale::get('view~default.repository.access.denied'), 'AuthorizationRequired');
         return false;
     }
     // Get and normalize the passed parameters
     $pParams = jApp::coord()->request->params;
     $pParams['map'] = realpath($lrep->getPath()) . '/' . $project . ".qgs";
     $lizmapCache = jClasses::getService('lizmap~lizmapCache');
     $params = $lizmapCache->normalizeParams($pParams);
     // Define class private properties
     $this->project = $lproj;
     $this->repository = $lrep;
     $this->services = lizmap::getServices();
     $this->params = $params;
     $this->lizmapCache = $lizmapCache;
     // Optionnaly filter data by login
     if (isset($params['request'])) {
         $request = strtolower($params['request']);
         if (in_array($request, array('getmap', 'getfeatureinfo', 'getfeature', 'getprint')) and !jAcl2::check('lizmap.tools.loginFilteredLayers.override', $lrep->getKey())) {
             $this->filterDataByLogin();
         }
     }
     return true;
 }
 /**
  * Get data from map service or from the cache.
  * @param lizmapProject $project The project.
  * @param array $params Array of parameters.
  * @return array $data Normalized and filtered array.
  */
 public static function getMap($project, $params, $forced = False)
 {
     // Get cache if exists
     $keyParams = array();
     foreach ($params as $pk => $value) {
         if (in_array($pk, array("bbox", "format", "height", "layers", "transparent"))) {
             $keyParams[$pk] = $value;
         }
     }
     ksort($keyParams);
     $layers = str_replace(',', '_', $params['layers']);
     $crs = preg_replace('#[^a-zA-Z0-9_]#', '_', $params['crs']);
     // Get repository data
     $ser = lizmap::getServices();
     $lrep = $project->getRepository();
     $lproj = $project;
     $project = $lproj->getKey();
     $repository = $lrep->getKey();
     // Change to true to put some information in debug files
     $debug = $ser->debugMode;
     // Read config file for the current project
     $layername = $params["layers"];
     $configLayers = $lproj->getLayers();
     $configLayer = null;
     if (property_exists($configLayers, $layername)) {
         $configLayer = $configLayers->{$layername};
     }
     // Set or get tile from the parent project in case of embedded layers
     if ($configLayer and property_exists($configLayer, 'sourceRepository') and property_exists($configLayer, 'sourceProject')) {
         $newRepository = (string) $configLayer->sourceRepository;
         $newProject = (string) $configLayer->sourceProject;
         $repository = $newRepository;
         $project = $newProject;
         $lrep = lizmap::getRepository($repository);
         if (!$lrep) {
             jMessage::add('The repository ' . strtoupper($repository) . ' does not exist !', 'RepositoryNotDefined');
             return array('error', 'text/plain', '404');
         }
         try {
             $lproj = lizmap::getProject($repository . '~' . $project);
             if (!$lproj) {
                 jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
                 return array('error', 'text/plain', '404');
             }
         } catch (UnknownLizmapProjectException $e) {
             jLog::logEx($e, 'error');
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
             return array('error', 'text/plain', '404');
         }
     }
     $key = md5(serialize($keyParams));
     // Get tile cache virtual profile (tile storage)
     // And get tile if already in cache
     // --> must be done after checking that parent project is involved
     $profile = lizmapProxy::createVirtualProfile($repository, $project, $layers, $crs);
     if ($debug) {
         lizmap::logMetric('LIZMAP_PROXY_READ_LAYER_CONFIG');
     }
     // Has the user asked for cache for this layer ?
     $useCache = False;
     if ($configLayer) {
         $useCache = strtolower($configLayer->cached) == 'true';
     }
     // Avoid using cache for requests concerning not square tiles or too big
     // Focus on real web square tiles
     $wmsClient = 'web';
     if ($useCache and $params['width'] != $params['height'] and ($params['width'] > 300 or $params['height'] > 300)) {
         $wmsClient = 'gis';
         $useCache = False;
     }
     if ($useCache and !$forced) {
         $tile = jCache::get($key, $profile);
         if ($tile) {
             $_SESSION['LIZMAP_GETMAP_CACHE_STATUS'] = 'read';
             $mime = 'image/jpeg';
             if (preg_match('#png#', $params['format'])) {
                 $mime = 'image/png';
             }
             if ($debug) {
                 lizmap::logMetric('LIZMAP_PROXY_HIT_CACHE');
             }
             return array($tile, $mime, 200);
         }
     }
     // ***************************
     // No cache hit : need to ask the tile from QGIS Server
     // ***************************
     // Construction of the WMS url : base url + parameters
     $url = $ser->wmsServerURL . '?';
     // Add project path into map parameter
     $params["map"] = realpath($lproj->getQgisPath());
     // Metatile : if needed, change the bbox
     // Avoid metatiling when the cache is not active for the layer
     $metatileSize = '1,1';
     if ($configLayer and property_exists($configLayer, 'metatileSize')) {
         if (preg_match('#^[3579],[3579]$#', $configLayer->metatileSize)) {
             $metatileSize = $configLayer->metatileSize;
         }
     }
     # Metatile buffer
     $metatileBuffer = 5;
     // Also checks if gd is installed
     if ($metatileSize and $useCache and $wmsClient == 'web' and extension_loaded('gd') && function_exists('gd_info')) {
         # Metatile Size
         $metatileSizeExp = explode(',', $metatileSize);
         $metatileSizeX = (int) $metatileSizeExp[0];
         $metatileSizeY = (int) $metatileSizeExp[1];
         # Get requested bbox
         $bboxExp = explode(',', $params['bbox']);
         $width = $bboxExp[2] - $bboxExp[0];
         $height = $bboxExp[3] - $bboxExp[1];
         # Calculate factors
         $xFactor = (int) ($metatileSizeX / 2);
         $yFactor = (int) ($metatileSizeY / 2);
         # Calculate the new bbox
         $xmin = $bboxExp[0] - $xFactor * $width - $metatileBuffer * $width / $params["width"];
         $ymin = $bboxExp[1] - $yFactor * $height - $metatileBuffer * $height / $params["height"];
         $xmax = $bboxExp[2] + $xFactor * $width + $metatileBuffer * $width / $params["width"];
         $ymax = $bboxExp[3] + $yFactor * $height + $metatileBuffer * $height / $params["height"];
         # Replace request bbox by metatile bbox
         $params["bbox"] = "{$xmin},{$ymin},{$xmax},{$ymax}";
         # Keep original param value
         $originalParams = array("width" => $params["width"], "height" => $params["height"]);
         # Replace width and height before requesting the image from qgis
         $params["width"] = $metatileSizeX * $params["width"] + 2 * $metatileBuffer;
         $params["height"] = $metatileSizeY * $params["height"] + 2 * $metatileBuffer;
     }
     // Build params before send the request to Qgis
     $builtParams = http_build_query($params);
     // Replace needed characters (not needed for php >= 5.4, just use the 4th parameter of the method http_build_query)
     $a = array('+', '_', '.', '-');
     $b = array('%20', '%5F', '%2E', '%2D');
     $builtParams = str_replace($a, $b, $builtParams);
     // Get data from the map server
     $proxyMethod = $ser->proxyMethod;
     $getRemoteData = lizmapProxy::getRemoteData($url . $builtParams, $proxyMethod, $debug);
     $data = $getRemoteData[0];
     $mime = $getRemoteData[1];
     $code = $getRemoteData[2];
     if ($debug) {
         lizmap::logMetric('LIZMAP_PROXY_REQUEST_QGIS_MAP');
     }
     if ($useCache && !preg_match('/^image/', $mime)) {
         $useCache = False;
     }
     // Metatile : if needed, crop the metatile into a single tile
     // Also checks if gd is installed
     if ($metatileSize and $useCache and $wmsClient == 'web' and extension_loaded('gd') && function_exists('gd_info')) {
         # Save original content into an image var
         $original = imagecreatefromstring($data);
         # crop parameters
         $newWidth = (int) $originalParams["width"];
         // px
         $newHeight = (int) $originalParams["height"];
         // px
         $positionX = (int) ($xFactor * $originalParams["width"]) + $metatileBuffer;
         // left translation of 30px
         $positionY = (int) ($yFactor * $originalParams["height"]) + $metatileBuffer;
         // top translation of 20px
         # create new gd image
         $image = imageCreateTrueColor($newWidth, $newHeight);
         # save transparency if needed
         if (preg_match('#png#', $params['format'])) {
             imagesavealpha($original, true);
             imagealphablending($image, false);
             $color = imagecolortransparent($image, imagecolorallocatealpha($image, 0, 0, 0, 127));
             imagefill($image, 0, 0, $color);
             imagesavealpha($image, true);
         }
         # crop image
         imagecopyresampled($image, $original, 0, 0, $positionX, $positionY, $newWidth, $newHeight, $newWidth, $newHeight);
         # Output the image as a string (use PHP buffering)
         ob_start();
         if (preg_match('#png#', $params['format'])) {
             imagepng($image, null, 9);
         } else {
             imagejpeg($image, null, 90);
         }
         $data = ob_get_contents();
         // read from buffer
         ob_end_clean();
         // delete buffer
         // Destroy image handlers
         imagedestroy($original);
         imagedestroy($image);
         if ($debug) {
             lizmap::logMetric('LIZMAP_PROXY_CROP_METATILE');
         }
     }
     $_SESSION['LIZMAP_GETMAP_CACHE_STATUS'] = 'off';
     // Store into cache if needed
     if ($useCache) {
         //~ jLog::log( ' Store into cache');
         $cacheExpiration = (int) $ser->cacheExpiration;
         if (property_exists($configLayer, 'cacheExpiration')) {
             $cacheExpiration = (int) $configLayer->cacheExpiration;
         }
         jCache::set($key, $data, $cacheExpiration, $profile);
         $_SESSION['LIZMAP_GETMAP_CACHE_STATUS'] = 'write';
         if ($debug) {
             lizmap::logMetric('LIZMAP_PROXY_WRITE_CACHE');
         }
     }
     return array($data, $mime, $code);
 }
 /**
  * Get a project
  * @return lizmapProject (null if it does not exist)
  * @FIXME all calls to getProject construct $key. Why not to
  * deliver directly $rep and $project? It could avoid
  * a preg_match
  */
 public static function getProject($key)
 {
     $match = preg_match('/(?P<rep>\\w+)~(?P<proj>\\w+)/', $key, $matches);
     if ($match != 1) {
         return null;
     }
     $rep = self::getRepository($matches['rep']);
     if ($rep == null) {
         return null;
     }
     if (isset(self::$projectInstances[$key])) {
         return self::$projectInstances[$key];
     }
     try {
         $proj = new lizmapProject($matches['proj'], $rep);
     } catch (UnknownLizmapProjectException $e) {
         throw $e;
     } catch (Exception $e) {
         jLog::logEx($e, 'error');
         return null;
     }
     self::$projectInstances[$key] = $proj;
     return $proj;
 }
 /**
  * Displays a list of project for a given repository.
  *
  * @param string $repository. Name of the repository.
  * @return Html page with a list of projects.
  */
 function index()
 {
     if ($this->param('theme')) {
         jApp::config()->theme = $this->param('theme');
     }
     $rep = $this->getResponse('html');
     // Get lizmap services
     $services = lizmap::getServices();
     // only maps
     if ($services->onlyMaps) {
         $repository = lizmap::getRepository($services->defaultRepository);
         if ($repository && jAcl2::check('lizmap.repositories.view', $repository->getKey())) {
             try {
                 $project = lizmap::getProject($repository->getKey() . '~' . $services->defaultProject);
                 if ($project) {
                     // test redirection to an other controller
                     $items = jEvent::notify('mainviewGetMaps')->getResponse();
                     foreach ($items as $item) {
                         if ($item->parentId == $repository->getKey() && $item->id == $services->defaultProject) {
                             $rep = $this->getResponse('redirectUrl');
                             $rep->url = $item->url;
                             return $rep;
                         }
                     }
                     // redirection to default controller
                     $rep = $this->getResponse('redirect');
                     $rep->action = 'view~map:index';
                     return $rep;
                 }
             } catch (UnknownLizmapProjectException $e) {
                 jMessage::add('The \'only maps\' option is not well configured!', 'error');
                 jLog::logEx($e, 'error');
             }
         }
     }
     // Get repository data
     $repository = $this->param('repository');
     $repositoryList = array();
     if ($repository) {
         if (!jAcl2::check('lizmap.repositories.view', $repository)) {
             $rep = $this->getResponse('redirect');
             $rep->action = 'view~default:index';
             jMessage::add(jLocale::get('view~default.repository.access.denied'), 'error');
             return $rep;
         }
     }
     $title = jLocale::get("view~default.repository.list.title") . ' - ' . $services->appName;
     if ($repository) {
         $lrep = lizmap::getRepository($repository);
         $title = $lrep->getData('label') . ' - ' . $title;
     }
     $rep->title = $title;
     $rep->body->assign('repositoryLabel', $title);
     $auth_url_return = jUrl::get('view~default:index');
     if ($repository) {
         $auth_url_return = jUrl::get('view~default:index', array('repository' => $repository));
     }
     $rep->body->assign('auth_url_return', $auth_url_return);
     $rep->body->assign('isConnected', jAuth::isConnected());
     $rep->body->assign('user', jAuth::getUserSession());
     if ($services->allowUserAccountRequests) {
         $rep->body->assign('allowUserAccountRequests', True);
     }
     // Add Google Analytics ID
     if ($services->googleAnalyticsID != '' && preg_match("/^UA-\\d+-\\d+\$/", $services->googleAnalyticsID) == 1) {
         $rep->body->assign('googleAnalyticsID', $services->googleAnalyticsID);
     }
     $rep->body->assignZone('MAIN', 'main_view', array('repository' => $repository, 'auth_url_return' => $auth_url_return));
     $rep->addJSCode("\n      \$(window).load(function() {\n        \$('.liz-project-img').parent().mouseenter(function(){\n          var self = \$(this);\n          self.find('.liz-project-desc').slideDown();\n          self.css('cursor','pointer');\n        }).mouseleave(function(){\n          var self = \$(this);\n          self.find('.liz-project-desc').hide();\n        }).click(function(){\n          var self = \$(this);\n          window.location = self.parent().find('a.liz-project-view').attr('href');\n          return false;\n        });\n      });\n      ");
     // Js hack to normalize the height of the project thumbnails to avoid line breaks with long project titles
     $bp = jApp::config()->urlengine['basePath'];
     $rep->addJSLink($bp . 'js/view.js');
     return $rep;
 }
 /**
  * Get illustration image for a specified project.
  * @param string $repository Repository of the project.
  * @param string $project Project key.
  * @return binary object The image for this project.
  */
 function illustration()
 {
     $rep = $this->getResponse('binary');
     $rep->doDownload = false;
     // Get repository data
     $repository = $this->param('repository');
     $lrep = lizmap::getRepository($repository);
     if (!$lrep) {
         return $this->error404('');
     }
     if (!jAcl2::check('lizmap.repositories.view', $lrep->getKey())) {
         return $this->error403(jLocale::get('view~default.repository.access.denied'));
     }
     // Get the project
     $project = $this->param('project');
     // Get lizmapProject class
     try {
         $lproj = lizmap::getProject($lrep->getKey() . '~' . $project);
         if (!$lproj) {
             return $this->error404('The lizmapProject ' . strtoupper($project) . ' does not exist !');
         }
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
         return $this->error404('The lizmapProject ' . strtoupper($project) . ' does not exist !');
     }
     // Redirect if no right to access the project
     if (!$lproj->checkAcl()) {
         return $this->error403(jLocale::get('view~default.repository.access.denied'));
     }
     // Get the project
     $project = $this->param('project');
     // default illustration
     $themePath = jApp::wwwPath() . 'themes/' . jApp::config()->theme . '/';
     $rep->fileName = $themePath . 'css/img/250x250_mappemonde.png';
     // get project illustration if exists
     if ($project) {
         $imageTypes = array('jpg', 'jpeg', 'png', 'gif');
         foreach ($imageTypes as $type) {
             if (file_exists($lrep->getPath() . $project . '.qgs.' . $type)) {
                 $rep->fileName = $lrep->getPath() . $project . '.qgs.' . $type;
                 $rep->mimeType = "image/{$type}";
                 $rep->setExpires('+60 seconds');
                 return $rep;
             }
         }
     }
     return $rep;
 }
示例#10
0
 /**
  * Query a QuickFinder database
  * @param text $query A query on OpenStreetMap object
  * @param text $bbox A bounding box in EPSG:4326 Optionnal
  * @return GeoJSON.
  */
 function get()
 {
     $rep = $this->getResponse('binary');
     $rep->outputFileName = 'search_results.json';
     $rep->mimeType = 'application/json';
     $content = '[]';
     $rep->content = $content;
     // Get project and repository, and check rights
     $project = $this->param('project');
     $repository = $this->param('repository');
     $lrep = lizmap::getRepository($repository);
     $lproj = null;
     try {
         $lproj = lizmap::getProject($repository . '~' . $project);
         if (!$lproj) {
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
             return $rep;
         }
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
         jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
         return $rep;
     }
     if (!$lproj->checkAcl()) {
         jMessage::add(jLocale::get('view~default.repository.access.denied'), 'AuthorizationRequired');
         return $rep;
     }
     // Parameters
     $pquery = $this->param('query');
     if (!$pquery) {
         return $rep;
     }
     $pquery = filter_var($pquery, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
     // Get FTS searches
     $ftsSearches = $lproj->hasFtsSearches();
     if (!$ftsSearches) {
         return $rep;
     }
     $searches = $ftsSearches['searches'];
     $jdb_profile = $ftsSearches['jdb_profile'];
     // Limitations
     $limit_tot = 30;
     $limit_search = 15;
     $cnx = jDb::getConnection($jdb_profile);
     // Create FTS query
     $words = explode(' ', $pquery);
     $matches = implode('* ', $words) . '*';
     $sql = "SELECT search_id,content,wkb_geom FROM quickfinder_data WHERE";
     $sql .= " content MATCH " . $cnx->quote($matches);
     // Add filter by groups and user if the user is authenticated
     if (!jAcl2::check('lizmap.tools.loginFilteredLayers.override', $lrep->getKey())) {
         $sql .= " AND ( content LIKE '%@@all' OR content NOT LIKE '%@@%'";
         $isConnected = jAuth::isConnected();
         if ($isConnected) {
             // Ok if any group matches
             $userGroups = jAcl2DbUserGroup::getGroups();
             foreach ($userGroups as $g) {
                 $sql .= " OR content LIKE '%@@" . $g . "'";
             }
             // Ok if user matches
             $user = jAuth::getUserSession();
             $login = $user->login;
             $sql .= " OR content LIKE '%@@" . $login . "'";
         }
         $sql .= ' )';
     }
     // Query and format data for each search key
     $nb = array('search' => array(), 'tot' => 0);
     $data = array();
     foreach ($searches as $skey => $sval) {
         // Add filter to get only data for given search key
         $sql_search = $sql . ' AND search_id = ' . $cnx->quote($skey);
         $limit = $limit_search;
         $sql_search .= " LIMIT " . $limit;
         //jLog::log($sql_search);
         // Run query
         $res = $cnx->query($sql_search);
         // Format data
         foreach ($res as $item) {
             $key = $item->search_id;
             if (!array_key_exists($key, $nb['search'])) {
                 $nb['search'][$key] = 0;
             }
             if ($nb['search'][$key] >= $limit_search) {
                 continue;
             }
             if ($nb['tot'] >= $limit_tot) {
                 break;
             }
             if (!array_key_exists($key, $data)) {
                 $data[$key] = array();
             }
             $data[$key]['search_name'] = $searches[$key]['search_name'];
             $data[$key]['layer_name'] = $searches[$key]['layer_name'];
             $data[$key]['srid'] = $searches[$key]['srid'];
             if (!array_key_exists('features', $data[$key])) {
                 $data[$key]['features'] = array();
             }
             $data[$key]['features'][] = array('label' => preg_replace('#@@.+#', '', $item->content), 'geometry' => $item->wkb_geom);
             $nb['search'][$key] += 1;
             $nb['tot'] += 1;
         }
     }
     $rep->content = json_encode($data);
     return $rep;
 }
示例#11
0
 /**
  * Query the IGN Geoportal API
  * @param text $query A query on IGN BD adresse object
  * @param text $bbox A bounding box in EPSG:4326
  * @return XML.
  */
 function address()
 {
     $rep = $this->getResponse('json');
     $rep->data = array();
     $query = $this->param('query');
     if (!$query) {
         return $rep;
     }
     // Get the project
     $project = filter_var($this->param('project'), FILTER_SANITIZE_STRING);
     if (!$project) {
         return $rep;
     }
     // Get repository data
     $repository = $this->param('repository');
     if (!$repository) {
         return $rep;
     }
     // Get the project object
     $lproj = null;
     try {
         $lproj = lizmap::getProject($repository . '~' . $project);
         if (!$lproj) {
             return $rep;
         }
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
         return $rep;
     }
     $configOptions = $lproj->getOptions();
     if (!property_exists($configOptions, 'ignKey') || $configOptions->ignKey == '') {
         return $rep;
     }
     $url = 'http://gpp3-wxs.ign.fr/' . $configOptions->ignKey . '/geoportail/ols?';
     $xls = '<XLS xmlns:xls="http://www.opengis.net/xls" xmlns:gml="http://www.opengis.net/gml" xmlns="http://www.opengis.net/xls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="http://www.opengis.net/xls http://schemas.opengis.net/ols/1.2/olsAll.xsd">';
     $xls .= '<RequestHeader/><Request requestID="1" version="1.2" methodName="LocationUtilityService"><GeocodeRequest returnFreeForm="false"><Address countryCode="StreetAddress">';
     $xls .= '<freeFormAddress>' . $query . '</freeFormAddress>';
     $xls .= '</Address></GeocodeRequest></Request></XLS>';
     $params = array("xls" => $xls, "output" => 'xml');
     $url .= http_build_query($params);
     $curl_handle = curl_init();
     curl_setopt($curl_handle, CURLOPT_URL, $url);
     curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Expect:'));
     curl_setopt($curl_handle, CURLOPT_REFERER, jUrl::getFull('lizmap~ign:address'));
     $content = curl_exec($curl_handle);
     curl_close($curl_handle);
     $rep->content = $content;
     $content = str_replace('xmlns=', 'ns=', $content);
     $content = str_replace('gml:', '', $content);
     $xml = simplexml_load_string($content);
     $results = array();
     $GeocodedAddresses = $xml->xpath('//GeocodedAddress');
     foreach ($GeocodedAddresses as $GeocodedAddress) {
         $result = array();
         $address = array();
         /*
          * bug with gml:*
          */
         $Point = $GeocodedAddress->xpath('Point/pos');
         if (count($Point) != 0) {
             $Point = $Point[0];
             $point = explode(' ', (string) $Point);
             $result['point'] = array($point[1], $point[0]);
         }
         $Address = $GeocodedAddress->xpath('Address');
         if (count($Address) == 0) {
             continue;
         }
         $Address = $Address[0];
         $Building = $Address->xpath('StreetAddress/Building');
         if (count($Building) != 0) {
             $Building = $Building[0];
             $address['number'] = (string) $Building['number'];
         }
         $Street = $Address->xpath('StreetAddress/Street');
         if (count($Street) != 0) {
             $Street = $Street[0];
             $address['street'] = (string) $Street;
         }
         $Places = $Address->xpath('Place');
         foreach ($Places as $Place) {
             $PlaceType = (string) $Place['type'];
             if ($PlaceType == 'Municipality') {
                 $address['municipality'] = (string) $Place;
             } else {
                 if ($PlaceType == 'Departement') {
                     $address['departement'] = (string) $Place;
                 } else {
                     if ($PlaceType == 'Bbox') {
                         $result['bbox'] = explode(';', (string) $Place);
                     }
                 }
             }
         }
         $formatted_address = '';
         if (array_key_exists('number', $address)) {
             $formatted_address = $address['number'] . ' ';
         }
         if (array_key_exists('street', $address) && $address['street'] != '') {
             $formatted_address .= $address['street'] . ', ';
         }
         if (array_key_exists('municipality', $address)) {
             $formatted_address .= $address['municipality'] . ', ';
         }
         if (array_key_exists('departement', $address)) {
             $formatted_address .= $address['departement'];
         }
         $result['formatted_address'] = $formatted_address;
         $results[] = $result;
     }
     $rep->data = $results;
     return $rep;
 }
 /**
  * Query a QuickFinder database
  * @param text $query A query on OpenStreetMap object
  * @param text $bbox A bounding box in EPSG:4326 Optionnal
  * @return GeoJSON.
  */
 function get()
 {
     $rep = $this->getResponse('binary');
     $rep->outputFileName = 'search_results.json';
     $rep->mimeType = 'application/json';
     $content = '[]';
     $rep->content = $content;
     // Get project and repository, and check rights
     $project = $this->param('project');
     $repository = $this->param('repository');
     $lrep = lizmap::getRepository($repository);
     $lproj = null;
     try {
         $lproj = lizmap::getProject($repository . '~' . $project);
         if (!$lproj) {
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
             return $rep;
         }
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
         jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
         return $rep;
     }
     if (!$lproj->checkAcl()) {
         jMessage::add(jLocale::get('view~default.repository.access.denied'), 'AuthorizationRequired');
         return $rep;
     }
     // Parameters
     $pquery = $this->param('query');
     if (!$pquery) {
         return $rep;
     }
     $pquery = filter_var($pquery, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
     // Get FTS searches
     $ftsSearches = $lproj->hasFtsSearches();
     if (!$ftsSearches) {
         return $rep;
     }
     $searches = $ftsSearches['searches'];
     $jdb_profile = $ftsSearches['jdb_profile'];
     // Limitations
     $limit_tot = 30;
     $limit_search = 10;
     // Create FTS query
     $words = explode(' ', $pquery);
     $matches = implode('* ', $words) . '*';
     $sql = "\n    SELECT search_id,content,wkb_geom\n    FROM quickfinder_data\n    WHERE content MATCH\n    ";
     $cnx = jDb::getConnection($jdb_profile);
     $sql .= " " . $cnx->quote($matches);
     $limit = max(count($searches) * $limit_search, $limit_tot);
     $sql .= " LIMIT " . $limit;
     //jLog::log($sql);
     // Run query
     $res = $cnx->query($sql);
     $data = array();
     $nb = array('search' => array(), 'tot' => 0);
     foreach ($res as $item) {
         $key = $item->search_id;
         if (!array_key_exists($key, $nb['search'])) {
             $nb['search'][$key] = 0;
         }
         if ($nb['search'][$key] >= $limit_search) {
             continue;
         }
         if ($nb['tot'] >= $limit_tot) {
             break;
         }
         if (!array_key_exists($key, $data)) {
             $data[$key] = array();
         }
         $data[$key]['search_name'] = $searches[$key]['search_name'];
         $data[$key]['layer_name'] = $searches[$key]['layer_name'];
         $data[$key]['srid'] = $searches[$key]['srid'];
         if (!array_key_exists('features', $data[$key])) {
             $data[$key]['features'] = array();
         }
         $data[$key]['features'][] = array('label' => $item->content, 'geometry' => $item->wkb_geom);
         $nb['search'][$key] += 1;
         $nb['tot'] += 1;
     }
     $rep->content = json_encode($data);
     return $rep;
 }
 public function getProjects()
 {
     $projects = array();
     $dir = $this->getPath();
     if (is_dir($dir)) {
         if ($dh = opendir($dir)) {
             $cfgFiles = array();
             $qgsFiles = array();
             while (($file = readdir($dh)) !== false) {
                 if (substr($file, -3) == 'cfg') {
                     $cfgFiles[] = $file;
                 }
                 if (substr($file, -3) == 'qgs') {
                     $qgsFiles[] = $file;
                 }
             }
             closedir($dh);
             foreach ($qgsFiles as $qgsFile) {
                 $proj = null;
                 if (in_array($qgsFile . '.cfg', $cfgFiles)) {
                     try {
                         $proj = lizmap::getProject($this->key . '~' . substr($qgsFile, 0, -4));
                         if ($proj != null) {
                             $projects[] = $proj;
                         }
                     } catch (UnknownLizmapProjectException $e) {
                         jLog::logEx($e, 'error');
                     }
                 }
             }
         }
     }
     return $projects;
 }