---
-Before opening a new feature request, please search through the open issue to check that your request hasn't been reported already.
+<!-- Before opening a new feature request, please search through the open issue to check that your request hasn't been reported already. -->
**Is your feature request related to a problem? Please describe.**
-A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
**Describe the solution you'd like**
-A clear and concise description of what you want to happen.
+<!-- A clear and concise description of what you want to happen. -->
**Describe alternatives you've considered**
-A clear and concise description of any alternative solutions or features you've considered.
+<!-- A clear and concise description of any alternative solutions or features you've considered. -->
**Additional context**
-Add any other context or screenshots about the feature request here.
+<!-- Add any other context or screenshots about the feature request here. -->
## What did you search for?
-Please try to provide a link to your search. You can go to https://nominatim.openstreetmap.org and repeat your search there. If you originally found the issue somewhere else, please tell us what software/website you were using.
+<!-- Please try to provide a link to your search. You can go to https://nominatim.openstreetmap.org and repeat your search there. If you originally found the issue somewhere else, please tell us what software/website you were using. -->
## What result did you get?
**Is the result in the right place and just named wrongly?**
-Please tell us the display name you expected.
+<!-- Please tell us the display name you expected. -->
**Is the result missing completely?**
-Make sure that the data you are looking for is in OpenStreetMap. Provide a link to the OpenStreetMap object or if you cannot get it, a link to the map on https://openstreetmap.org where you expect the result to be.
+<!-- Make sure that the data you are looking for is in OpenStreetMap. Provide a link to the OpenStreetMap object or if you cannot get it, a link to the map on https://openstreetmap.org where you expect the result to be.
To get the link to the OSM object, you can try the following:
* Click on the question mark on the right side of the map. You get a question cursor. Use it to click on the map where your object is located.
* Find the object of interest in the list that appears on the left side.
* Click on the object and report back the URL that the browser shows.
+-->
## Further details
-Anything else we should know about the search. Particularities with addresses in the area etc.
+<!-- Anything else we should know about the search. Particularities with addresses in the area etc. -->
---
-___Note: if you are installing Nominatim through a docker image, you should report issues with the installation process with the docker repository first.___
+<!-- Note: if you are installing Nominatim through a docker image, you should report issues with the installation process with the docker repository first. -->
**Describe the bug**
-A clear and concise description of what the bug is.
+<!-- A clear and concise description of what the bug is. -->
**To Reproduce**
-Please describe what you did to get to the issue.
+<!-- Please describe what you did to get to the issue. -->
**Software Environment (please complete the following information):**
- Nominatim version:
- type and size of disks:
- bare metal/AWS/other cloud service:
+**Postgresql Configuration:**
+
+<!-- List any configuration items you changed in your postgresql configuration. -->
+
**Additional context**
-Add any other context about the problem here.
+
+<!-- Add any other context about the problem here. -->
steps:
- name: Install prerequisits
- run: sudo apt-get install -y -qq libboost-system-dev libboost-filesystem-dev libexpat1-dev zlib1g-dev libbz2-dev libpq-dev libproj-dev python3-psycopg2 python3-pyosmium
+ run: |
+ sudo apt-get install -y -qq libboost-system-dev libboost-filesystem-dev libexpat1-dev zlib1g-dev libbz2-dev libpq-dev libproj-dev python3-psycopg2 python3-pyosmium php-symfony-dotenv
shell: bash
- name: Configure
name: 'Setup Postgresql and Postgis'
+inputs:
+ postgresql-version:
+ description: 'Version of PostgreSQL to install'
+ required: true
+ postgis-version:
+ description: 'Version of Postgis to install'
+ required: true
+
runs:
using: "composite"
steps:
- - name: Install postgis
+ - name: Remove existing PostgreSQL
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get purge -yq postgresql*
+ shell: bash
+
+ - name: Install PostgreSQL
run: |
- sudo apt-get update -qq
- sudo apt-get install -y -qq postgresql-13-postgis-3 postgresql-13-postgis-3-scripts postgresql-server-dev-13
+ sudo apt-get install -y -qq --no-install-suggests --no-install-recommends postgresql-client-${PGVER} postgresql-${PGVER}-postgis-${POSTGISVER} postgresql-${PGVER}-postgis-${POSTGISVER}-scripts postgresql-contrib-${PGVER} postgresql-${PGVER} postgresql-server-dev-${PGVER}
shell: bash
+ env:
+ PGVER: ${{ inputs.postgresql-version }}
+ POSTGISVER: ${{ inputs.postgis-version }}
- name: Adapt postgresql configuration
run: |
- echo 'fsync = off' | sudo tee /etc/postgresql/13/main/conf.d/local.conf
- echo 'synchronous_commit = off' | sudo tee -a /etc/postgresql/13/main/conf.d/local.conf
- echo 'full_page_writes = off' | sudo tee -a /etc/postgresql/13/main/conf.d/local.conf
- echo 'shared_buffers = 1GB' | sudo tee -a /etc/postgresql/13/main/conf.d/local.conf
+ echo 'fsync = off' | sudo tee /etc/postgresql/${PGVER}/main/conf.d/local.conf
+ echo 'synchronous_commit = off' | sudo tee -a /etc/postgresql/${PGVER}/main/conf.d/local.conf
+ echo 'full_page_writes = off' | sudo tee -a /etc/postgresql/${PGVER}/main/conf.d/local.conf
+ echo 'shared_buffers = 1GB' | sudo tee -a /etc/postgresql/${PGVER}/main/conf.d/local.conf
+ echo 'port = 5432' | sudo tee -a /etc/postgresql/${PGVER}/main/conf.d/local.conf
shell: bash
+ env:
+ PGVER: ${{ inputs.postgresql-version }}
- name: Setup database
run: |
- sudo systemctl start postgresql
+ sudo systemctl restart postgresql
sudo -u postgres createuser -S www-data
sudo -u postgres createuser -s runner
shell: bash
tests:
runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ postgresql: [9.5, 13]
+ include:
+ - postgresql: 9.5
+ postgis: 2.5
+ - postgresql: 13
+ postgis: 3
+
steps:
- uses: actions/checkout@v2
with:
submodules: true
+ - name: Setup PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: '7.4'
+ tools: phpunit, phpcs
+
- name: Get Date
id: get-date
run: |
- uses: actions/cache@v2
with:
path: |
- data/country_osm_grid.sql.gz
- monaco-latest.osm.pbf
+ {{ github.workspace }}/data/country_osm_grid.sql.gz
+ {{ github.workspace }}/monaco-latest.osm.pbf
key: nominatim-data-${{ steps.get-date.outputs.date }}
- uses: ./.github/actions/setup-postgresql
+ with:
+ postgresql-version: ${{ matrix.postgresql }}
+ postgis-version: ${{ matrix.postgis }}
- uses: ./.github/actions/build-nominatim
- name: Install test prerequsites
- uses: actions/cache@v2
with:
path: |
- data/country_osm_grid.sql.gz
- monaco-latest.osm.pbf
+ {{ github.workspace }}/data/country_osm_grid.sql.gz
+ {{ github.workspace }}/monaco-latest.osm.pbf
key: nominatim-data-${{ steps.get-date.outputs.date }}
- uses: ./.github/actions/setup-postgresql
+ with:
+ postgresql-version: 13
+ postgis-version: 3
- uses: ./.github/actions/build-nominatim
- name: Create configuration
run: |
- echo '<?php' > settings/local.php
- echo " @define('CONST_Pyosmium_Binary', '/usr/lib/python3-pyosmium/pyosmium-get-changes');" >> settings/local.php
+ echo "NOMINATIM_PYOSMIUM_BINARY=/usr/lib/python3-pyosmium/pyosmium-get-changes" >> .env
working-directory: build
- name: Download import data
project(nominatim)
set(NOMINATIM_VERSION_MAJOR 3)
-set(NOMINATIM_VERSION_MINOR 5)
+set(NOMINATIM_VERSION_MINOR 6)
set(NOMINATIM_VERSION_PATCH 0)
set(NOMINATIM_VERSION "${NOMINATIM_VERSION_MAJOR}.${NOMINATIM_VERSION_MINOR}.${NOMINATIM_VERSION_PATCH}")
if (BUILD_IMPORTER)
set(CUSTOMSCRIPTS
- utils/check_import_finished.php
- utils/country_languages.php
- utils/importWikipedia.php
- utils/export.php
- utils/query.php
- utils/setup.php
- utils/specialphrases.php
- utils/update.php
- utils/warm.php
+ check_import_finished.php
+ country_languages.php
+ importWikipedia.php
+ export.php
+ query.php
+ setup.php
+ specialphrases.php
+ update.php
+ warm.php
)
foreach (script_source ${CUSTOMSCRIPTS})
configure_file(${PROJECT_SOURCE_DIR}/cmake/script.tmpl
- ${PROJECT_BINARY_DIR}/${script_source})
+ ${PROJECT_BINARY_DIR}/utils/${script_source})
endforeach()
endif()
#-----------------------------------------------------------------------------
-# webserver scripts (API only)
+# Targets for running a development webserver from the build directory.
#-----------------------------------------------------------------------------
if (BUILD_API)
- set(WEBSITESCRIPTS
- website/deletable.php
- website/details.php
- website/lookup.php
- website/polygons.php
- website/reverse.php
- website/search.php
- website/status.php
- )
-
set(WEBSITEFILES
403.html
509.html
taginfo.json
)
- foreach (script_source ${WEBSITESCRIPTS})
- configure_file(${PROJECT_SOURCE_DIR}/cmake/website.tmpl
- ${PROJECT_BINARY_DIR}/${script_source})
- endforeach()
-
- set(WEBPATHS css images js)
-
foreach (webfile ${WEBSITEFILES})
configure_file(${PROJECT_SOURCE_DIR}/website/${webfile}
${PROJECT_BINARY_DIR}/website/${webfile})
endforeach()
- foreach (wp ${WEBPATHS})
- execute_process(
- COMMAND ln -sf ${PROJECT_SOURCE_DIR}/website/${wp} ${PROJECT_BINARY_DIR}/website/
- )
- endforeach()
-
add_custom_target(serve
php -S 127.0.0.1:8088
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/website
)
endif()
-#-----------------------------------------------------------------------------
-# default settings
-#-----------------------------------------------------------------------------
-
-configure_file(${PROJECT_SOURCE_DIR}/settings/defaults.php
- ${PROJECT_BINARY_DIR}/settings/settings.php)
-
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
not add your bugs to closed issues. They may looks similar to you but
often are completely different from the maintainer's point of view.
-### When Reporting Bad Search Results...
-
-Please make sure to add the following information:
-
- * the URL of the query that produces the bad result
- * the result you are getting
- * the expected result, preferably a link to the OSM object you want to find,
- otherwise an address that is as precise as possible
-
-To get the link to the OSM object, you can try the following:
-
- * go to https://openstreetmap.org
- * zoom to the area of the map where you expect the result and
- zoom in as much as possible
- * click on the question mark on the right side of the map,
- then with the queston cursor on the map where your object is located
- * find the object of interest in the list that appears on the left side
- * click on the object and report the URL back that the browser shows
-
-### When Reporting Bugs...
-
-Please add the following information to your issue:
-
- * hardware configuration: RAM size, CPUs, kind and size of disks
- * Operating system (also mention if you are running on a cloud service)
- * Postgres and Postgis version
- * list of settings you changed in your Postgres configuration
- * Nominatim version (release version or,
- if you run from the git repo, the output of `git rev-parse HEAD`)
- * (if applicable) exact command line of the command that was causing the issue
-
-Bug reports that do not include extensive information about your system,
-about the problem and about what you have been trying to debug the problem
-will be closed.
-
## Workflow for Pull Requests
We love to get pull requests from you. We operate the "Fork & Pull" model
+3.6.0
+
+ * add full support for searching by and displaying of addr:* tags
+ * improve address output for large-area objects
+ * better use of country names from OSM data for search and display
+ * better debug output for reverse call
+ * add support for addr:place links without an place equivalent in OSM
+ * improve finding postcodes with normalisation artefacts
+ * batch object to index for rank 30, avoiding a wrap-around of transaction
+ IDs in PostgreSQL
+ * introduce dynamic address rank computation for administrative boundaries
+ depending on linked objects and their place in the admin level hierarchy
+ * add country-specific address ranking for Indonesia, Russia, Belgium and
+ the Netherlands (thanks @hendrikmoree)
+ * make sure wikidata/wikipedia tags are imported for all styles
+ * make POIs searchable by name and housenumber (thanks @joy-yyd)
+ * reverse geocoding now ignores places without an address rank (rivers etc.)
+ * installation of a webserver is no longer mandatory, for development
+ use the php internal webserver via 'make serve
+ * reduce the influence of place nodes in addresses
+ * drop support for the unspecific is_in tag
+ * various minor tweaks to supplied styles
+ * move HTML web frontend into its own project
+ * move scripts for processing external data sources into separate directories
+ * introduce separate configuration for website (thanks @krahulreddy)
+ * update documentation, in particular, clean up development docs
+ * update osm2pgsql to 1.4.0
+
+3.5.2
+
+ * ensure that wikipedia tags are imported for all styles
+ * reinstate verbosity for indexing during updates
+ * make house number reappear in display name on named POIs
+ * introduce batch processing in indexer to avoid transaction ID overrun
+ * increase splitting for large geometries to improve indexing speed
+ * remove deprecated get_magic_quotes_gpc() function
+ * make sure that all postcodes have an entry in word and are thus searchable
+ * remove use of ST_Covers in conjunction woth ST_Intersects,
+ causes bad query planning and slow updates in Postgis3
+ * update osm2pgsql
+
+3.5.1
+
+ * disable jit and parallel processing in PostgreSQL for osm2pgsql
+ * update libosmium to 2.15.6 (fixes an issue with processing hanging
+ on large multipolygons)
+
3.5.0
* structured select on HTML search page
* cleanup of partition function
* improve parenting for large POIs
* add support for Postgresql 12 and Postgis 3
- * add earlier cleanup when --drop is given, to reduce meory usage
+ * add earlier cleanup when --drop is given, to reduce memory usage
* remove use of place_id in URLs
* replace C nominatim indexer with a simpler Python implementation
* split up the huge sql/functions.sql file
#!@PHP_BIN@ -Cq
<?php
-require_once(dirname(dirname(__FILE__)).'/settings/settings.php');
-require_once(CONST_BasePath.'/@script_source@');
+@define('CONST_BinDir', '@CMAKE_SOURCE_DIR@/utils');
+@define('CONST_LibDir', '@CMAKE_SOURCE_DIR@/lib');
+@define('CONST_DataDir', '@CMAKE_SOURCE_DIR@');
+
+require_once(CONST_BinDir.'/@script_source@');
+++ /dev/null
-<?php
-@define('CONST_Debug', (isset($_GET['debug']) && $_GET['debug']));
-require_once(dirname(dirname(__FILE__)).'/settings/settings-frontend.php');
-
-require_once(CONST_BasePath.'/@script_source@');
On the client side you now need to configure the import to point to the
correct location of the library **on the database server**. Add the following
-line to your your `settings/local.php` file:
+line to your your `.env` file:
```php
-@define('CONST_Database_Module_Path', '<directory on the database server where nominatim.so resides>');
+NOMINATIM_DATABASE_MODULE_PATH="<directory on the database server where nominatim.so resides>"
```
-Now change the `CONST_Database_DSN` to point to your remote server and continue
+Now change the `NOMINATIM_DATABASE_DSN` to point to your remote server and continue
to follow the [standard instructions for importing](/admin/Import).
### Can I import negative OSM ids into Nominatim?
See [this question of Stackoverflow](https://help.openstreetmap.org/questions/64662/nominatim-flatnode-with-negative-id).
-
-### Missing XML or text declaration
-
-The website might show: `XML Parsing Error: XML or text declaration not at start of entity Location.`
-
-Make sure there are no spaces at the beginning of your `settings/local.php` file.
-
-
is assumed that you have already successfully installed the Nominatim
software itself, if not return to the [installation page](Installation.md).
-## Configuration setup in settings/local.php
+## Configuration setup in `.env`
-The Nominatim server can be customized via the file `settings/local.php`
-in the build directory. Note that this is a PHP file, so it must always
-start like this:
-
- <?php
-
-without any leading spaces.
+The Nominatim server can be customized via a `.env` in the build directory.
+This is a file in [dotenv](https://symfony.com/doc/4.3/components/dotenv.html) format
+which looks the same as variable settings in a standard shell environment.
+You can also set the same configuration via environment variables. All
+settings have a `NOMINATIM_` prefix to avoid conflicts with other environment
+variables.
There are lots of configuration settings you can tweak. Have a look
-at `settings/default.php` for a full list. Most should have a sensible default.
+at `settings/env.default` for a full list. Most should have a sensible default.
#### Flatnode files
you should also enable flatnode storage of node locations. With this
setting enabled, node coordinates are stored in a simple file instead
of the database. This will save you import time and disk storage.
-Add to your `settings/local.php`:
+Add to your `.env`:
- @define('CONST_Osm2pgsql_Flatnode_File', '/path/to/flatnode.file');
+ NOMINATIM_FLATNODE_FILE="/path/to/flatnode.file"
Replace the second part with a suitable path on your system and make sure
-the directory exists. There should be at least 64GB of free space.
+the directory exists. There should be at least 75GB of free space.
## Downloading additional data
cd $NOMINATIM_SOURCE_DIR/data
wget https://www.nominatim.org/data/wikimedia-importance.sql.gz
-The file is about 400MB and adds around 4GB to Nominatim database.
+The file is about 400MB and adds around 4GB to the Nominatim database.
!!! tip
If you forgot to download the wikipedia rankings, you can also add
wget https://www.nominatim.org/data/gb_postcode_data.sql.gz
wget https://www.nominatim.org/data/us_postcode_data.sql.gz
-## Choosing the Data to Import
+## Choosing the data to import
In its default setup Nominatim is configured to import the full OSM data
set for the entire planet. Such a setup requires a powerful machine with
-at least 64GB of RAM and around 800GB of SSD hard disks. Depending on your
+at least 64GB of RAM and around 900GB of SSD hard disks. Depending on your
use case there are various ways to reduce the amount of data imported. This
section discusses these methods. They can also be combined.
### Using an extract
-If you only need geocoding for a smaller region, then precomputed extracts
+If you only need geocoding for a smaller region, then precomputed OSM extracts
are a good way to reduce the database size and import time.
[Geofabrik](https://download.geofabrik.de) offers extracts for most countries.
They even have daily updates which can be used with the update process described
-below. There are also
+[in the next section](../Update). There are also
[other providers for extracts](https://wiki.openstreetmap.org/wiki/Planet.osm#Downloading).
Please be aware that some extracts are not cut exactly along the country
Like the full style but also adds most of the OSM tags into the extratags
column.
-The style can be changed with the configuration `CONST_Import_Style`.
+The style can be changed with the configuration `NOMINATIM_IMPORT_STYLE`.
To give you an idea of the impact of using the different styles, the table
below gives rough estimates of the final database size after import of a
-2018 planet and after using the `--drop` option. It also shows the time
-needed for the import on a machine with 64GB RAM, 4 CPUS and SSDs. Note that
-the given sizes are just an estimate meant for comparison of style requirements.
-Your planet import is likely to be larger as the OSM data grows with time.
+2020 planet and after using the `--drop` option. It also shows the time
+needed for the import on a machine with 64GB RAM, 4 CPUS and NVME disks.
+Note that the given sizes are just an estimate meant for comparison of
+style requirements. Your planet import is likely to be larger as the
+OSM data grows with time.
style | Import time | DB size | after drop
----------|--------------|------------|------------
-admin | 5h | 190 GB | 20 GB
-street | 42h | 400 GB | 180 GB
-address | 59h | 500 GB | 260 GB
-full | 80h | 575 GB | 300 GB
-extratags | 80h | 585 GB | 310 GB
+admin | 4h | 215 GB | 20 GB
+street | 22h | 440 GB | 185 GB
+address | 36h | 545 GB | 260 GB
+full | 54h | 640 GB | 330 GB
+extratags | 54h | 650 GB | 340 GB
-You can also customize the styles further. For a description of the
-style format see [the development section](../develop/Import.md).
+You can also customize the styles further.
+A [description of the style format](../develop/Import.md#configuring-the-import)
+can be found in the development section.
## Initial import of the data
First try the import with a small extract, for example from
[Geofabrik](https://download.geofabrik.de).
-Download the data to import and load the data with the following command
-from the build directory:
+Download the data to import. Then issue the following command
+from the **build directory** to start the import:
```sh
./utils/setup.php --osm-file <data file> --all 2>&1 | tee setup.log
```
-***Note for full planet imports:*** Even on a perfectly configured machine
-the import of a full planet takes at least 2 days. Once you see messages
+### Notes on full planet imports
+
+Even on a perfectly configured machine
+the import of a full planet takes around 2 days. Once you see messages
with `Rank .. ETA` appear, the indexing process has started. This part takes
the most time. There are 30 ranks to process. Rank 26 and 30 are the most complex.
They take each about a third of the total import time. If you have not reached
### Notes on memory usage
-In the first step of the import Nominatim uses osm2pgsql to load the OSM data
-into the PostgreSQL database. This step is very demanding in terms of RAM usage.
-osm2pgsql and PostgreSQL are running in parallel at this point. PostgreSQL
-blocks at least the part of RAM that has been configured with the
-`shared_buffers` parameter during [PostgreSQL tuning](Installation#postgresql-tuning)
+In the first step of the import Nominatim uses [osm2pgsql](https://osm2pgsql.org)
+to load the OSM data into the PostgreSQL database. This step is very demanding
+in terms of RAM usage. osm2pgsql and PostgreSQL are running in parallel at
+this point. PostgreSQL blocks at least the part of RAM that has been configured
+with the `shared_buffers` parameter during
+[PostgreSQL tuning](Installation#postgresql-tuning)
and needs some memory on top of that. osm2pgsql needs at least 2GB of RAM for
its internal data structures, potentially more when it has to process very large
relations. In addition it needs to maintain a cache for node locations. The size
by default, so you do not need to configure anything in this case.
For imports without a flatnode file, set `--osm2pgsql-cache` approximately to
-the size of the OSM pbf file (in MB) you are importing. Make sure you leave
-enough RAM for PostgreSQL and osm2pgsql as mentioned above. If the system starts
-swapping or you are getting out-of-memory errors, reduce the cache size or
-even consider using a flatnode file.
+the size of the OSM pbf file you are importing. The size needs to be given in
+MB. Make sure you leave enough RAM for PostgreSQL and osm2pgsql as mentioned
+above. If the system starts swapping or you are getting out-of-memory errors,
+reduce the cache size or even consider using a flatnode file.
### Verify the import
### Setting up the website
-Run the following command to set up the configuration file for the website
+Run the following command to set up the configuration file for the API frontend
`settings/settings-frontend.php`. These settings are used in website/*.php files.
```sh
./utils/setup.php --import-tiger-data
- 3. Enable use of the Tiger data in your `settings/local.php` by adding:
+ 3. Enable use of the Tiger data in your `.env` by adding:
- @define('CONST_Use_US_Tiger_Data', true);
+ NOMINATIM_USE_US_TIGER_DATA=yes
4. Apply the new settings:
planet import 64GB of RAM or more are strongly recommended. Do not report
out of memory problems if you have less than 64GB RAM.
-For a full planet install you will need at least 800GB of hard disk space
-(take into account that the OSM database is growing fast). SSD disks
-will help considerably to speed up import and queries.
+For a full planet install you will need at least 900GB of hard disk space.
+Take into account that the OSM database is growing fast.
+Fast disks are essential. Using NVME disks is recommended.
Even on a well configured machine the import of a full planet takes
-at least 2 days. Without SSDs 7-8 days are more realistic.
+around 2 days. On traditional spinning disks, 7-8 days are more realistic.
## Tuning the PostgreSQL database
SQL statements should be executed from the PostgreSQL commandline. Execute
`psql nominatim` to enter command line mode.
-## 3.5.0 -> master
+## 3.5.0 -> 3.6.0
### Change of layout of search_name_* tables
git clone https://github.com/osm-search/nominatim-ui
-Adapt the configuration `dist/config.js` to your needs. You need at least
+Copy the example configuration into the right place:
+
+ cd nominatim-ui
+ cp dist/config.example.js dist/config.js
+
+Now adapt the configuration to your needs. You need at least
to change the `Nominatim_API_Endpoint` to point to your Nominatim installation.
Then you can just test it locally by spinning up a webserver in the `dist`
~(^|&)format= other;
}
-# Determine from the URI and the format parameter aboce if forwarding is needed.
+# Determine from the URI and the format parameter above if forwarding is needed.
map $uri/$format $forward_to_ui {
default 1; # The default is to forward.
~^/ui 0; # If the URI point to the UI already, we are done.
The following section describes how to keep it up-to-date with Pyosmium.
For a list of other methods see the output of `./utils/update.php --help`.
-!!! warning
+!!! important
If you have configured a flatnode file for the import, then you
- need to keep this flatnode file around for updates as well.
+ need to keep this flatnode file around for updates.
#### Installing the newest version of Pyosmium
Nominatim needs a tool called `pyosmium-get-changes` which comes with
Pyosmium. You need to tell Nominatim where to find it. Add the
-following line to your `settings/local.php`:
+following line to your `.env`:
- @define('CONST_Pyosmium_Binary', '/home/user/.local/bin/pyosmium-get-changes');
+ NOMINATIM_PYOSMIUM_BINARY=/home/user/.local/bin/pyosmium-get-changes
The path above is fine if you used the `--user` parameter with pip.
Replace `user` with your user name.
to update using the global minutely diffs.
If you want a different update source you will need to add some settings
-to `settings/local.php`. For example, to use the daily country extracts
+to `.env`. For example, to use the daily country extracts
diffs for Ireland from Geofabrik add the following:
- // base URL of the replication service
- @define('CONST_Replication_Url', 'https://download.geofabrik.de/europe/ireland-and-northern-ireland-updates');
- // How often upstream publishes diffs
- @define('CONST_Replication_Update_Interval', '86400');
- // How long to sleep if no update found yet
- @define('CONST_Replication_Recheck_Interval', '900');
+ # base URL of the replication service
+ NOMINATIM_REPLICATION_URL="https://download.geofabrik.de/europe/ireland-and-northern-ireland-updates"
+ # How often upstream publishes diffs
+ NOMINATIM_REPLICATION_UPDATE_INTERVAL=86400
+ # How long to sleep if no update found yet
+ NOMINATIM_REPLICATION_RECHECK_INTERVAL=900
To set up the update process now run the following command:
# Place details
-Lookup details about a single place by id. The default output is HTML for debugging search logic and results.
+Show all details about a single place saved in the database.
-**The details page (including JSON output) exists for debugging only and must not be downloaded automatically**, see [Nominatim Usage Policy](https://operations.osmfoundation.org/policies/nominatim/).
+!!! warning
+ The details page exists for debugging only. You may not use it in scripts
+ or to automatically query details about a result.
+ See [Nominatim Usage Policy](https://operations.osmfoundation.org/policies/nominatim/).
## Parameters
The details API supports the following two request formats:
-```
- https://nominatim.openstreetmap.org/details?osmtype=[N|W|R]&osmid=<value>&class=<value>
+``` xml
+https://nominatim.openstreetmap.org/details?osmtype=[N|W|R]&osmid=<value>&class=<value>
```
-`osmtype` and `osmid` are required parameter. The type is one of node (N), way (W)
+`osmtype` and `osmid` are required parameters. The type is one of node (N), way (W)
or relation (R). The id must be a number. The `class` parameter is optional and
allows to distinguish between entries, when the corresponding OSM object has more
than one main tag. For example, when a place is tagged with `tourism=hotel` and
but the `class` parameter is left out, then one of the places will be chosen
at random and displayed.
-```
- https://nominatim.openstreetmap.org/details?place_id=<value>
+``` xml
+https://nominatim.openstreetmap.org/details?place_id=<value>
```
-Placeids are assigned sequentially during Nominatim data import. The id for a place is different between Nominatim installation (servers) and changes when data gets reimported. Therefore it can't be used as permanent id and shouldn't be used in bug reports.
+Place IDs are assigned sequentially during Nominatim data import. The ID
+for a place is different between Nominatim installation (servers) and
+changes when data gets reimported. Therefore it cannot be used as
+a permanent id and shouldn't be used in bug reports.
Additional optional parameters are explained below.
### Output format
-* `format=[html|json]`
-
-See [Place Output Formats](Output.md) for details on each format. (Default: html)
-
* `json_callback=<string>`
Wrap JSON output in a callback function (JSONP) i.e. `<string>(<json>)`.
-Only has an effect for JSON output formats.
* `pretty=[0|1]`
-For JSON output will add indentation to make it more human-readable. (Default: 0)
+Add indentation to make it more human-readable. (Default: 0)
### Output details
* `addressdetails=[0|1]`
-Include a breakdown of the address into elements. (Default for JSON: 0, for HTML: 1)
+Include a breakdown of the address into elements. (Default: 0)
* `keywords=[0|1]`
* `linkedplaces=[0|1]`
-Include details of places higher in the address hierarchy. E.g. for a street this is usually the city, state, postal code, country. (Default: 1)
+Include a details of places that are linked with this one. Places get linked
+together when they are different forms of the same physical object. Nominatim
+links two kinds of objects together: place nodes get linked with the
+corresponding administrative boundaries. Waterway relations get linked together with their
+members.
+(Default: 1)
* `hierarchy=[0|1]`
-Include details of places lower in the address hierarchy. E.g. for a city this usually a list of streets, suburbs, rivers. (Default for JSON: 0, for HTML: 1)
+Include details of places lower in the address hierarchy. (Default: 0)
* `group_hierarchy=[0|1]`
* `polygon_geojson=[0|1]`
-Include geometry of result. (Default for JSON: 0, for HTML: 1)
+Include geometry of result. (Default: 0)
### Language of results
## Examples
-##### HTML
-
-[https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=38210407](https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=38210407)
-
##### JSON
[https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=38210407&format=json](https://nominatim.openstreetmap.org/details.php?osmtype=W&osmid=38210407&format=json)
Either use a standard RFC2616 accept-language string or a simple
comma-separated list of language codes.
+### Polygon output
+
+* `polygon_geojson=1`
+* `polygon_kml=1`
+* `polygon_svg=1`
+* `polygon_text=1`
+
+Output geometry of results as a GeoJSON, KML, SVG or WKT. Only one of these
+options can be used at a time. (Default: 0)
+
+* `polygon_threshold=0.0`
+
+Return a simplified version of the output geometry. The parameter is the
+tolerance in degrees with which the geometry may differ from the original
+geometry. Topology is preserved in the result. (Default: 0.0)
### Other
The [/reverse](Reverse.md), [/search](Search.md) and [/lookup](Lookup.md)
API calls produce very similar output which is explained in this section.
-There is one section for each format which is selectable via the `format`
-parameter.
+There is one section for each format. The format correspond to what was
+selected via the `format` parameter.
-## Formats
-
-### JSON
+## JSON
The JSON format returns an array of places (for search and lookup) or
a single place (for reverse) of the following format:
"wikipedia": "en:London",
"population": "8416535"
}
- },
+ }
```
The possible fields are:
* `place_id` - reference to the Nominatim internal database ID ([see notes](#place_id-is-not-a-persistent-id))
- * `osm_type`, `osm_id` - reference to the OSM object
+ * `osm_type`, `osm_id` - reference to the OSM object ([see notes](#osm-reference))
* `boundingbox` - area of corner coordinates ([see notes](#boundingbox))
* `lat`, `lon` - latitude and longitude of the centroid of the object
* `display_name` - full comma-separated address
* `geojson`, `svg`, `geotext`, `geokml` - full geometry
(only with the appropriate `polygon_*` parameter)
-### JSONv2
+## JSONv2
This is the same as the JSON format with two changes:
* `class` renamed to `category`
* additional field `place_rank` with the search rank of the object
-### GeoJSON
+## GeoJSON
This format follows the [RFC7946](https://geojson.org). Every feature includes
a bounding box (`bbox`).
-The feature list has the following fields:
+The properties object has the following fields:
* `place_id` - reference to the Nominatim internal database ID ([see notes](#place_id-is-not-a-persistent-id))
- * `osm_type`, `osm_id` - reference to the OSM object
+ * `osm_type`, `osm_id` - reference to the OSM object ([see notes](#osm-reference))
* `category`, `type` - key and value of the main OSM tag
* `display_name` - full comma-separated address
* `place_rank` - class search rank
Use `polygon_geojson` to output the full geometry of the object instead
of the centroid.
-### GeocodeJSON
+## GeocodeJSON
The GeocodeJSON format follows the
[GeocodeJSON spec 0.1.0](https://github.com/geocoders/geocodejson-spec).
The following feature attributes are implemented:
- * `osm_type`, `osm_id` - reference to the OSM object (unofficial extension)
+ * `osm_type`, `osm_id` - reference to the OSM object (unofficial extension, [see notes](#osm-reference))
* `type` - value of the main tag of the object (e.g. residential, restaurant, ...)
* `label` - full comma-separated address
* `name` - localised name of the place
Use `polygon_geojson` to output the full geometry of the object instead
of the centroid.
-### XML
+## XML
The XML response returns one or more place objects in slightly different
formats depending on the API call.
-#### Reverse
+### Reverse
```
<reversegeocode timestamp="Sat, 11 Aug 18 11:53:21 +0000"
attribution="Data © OpenStreetMap contributors, ODbL 1.0. https://www.openstreetmap.org/copyright"
querystring="lat=48.400381&lon=11.745876&zoom=5&format=xml">
- <result place_id="179509537" osm_type="relation" osm_id="2145268" ref="BY"
+ <result place_id="179509537" osm_type="relation" osm_id="2145268" ref="BY" place_rank="15" address_rank="15"
lat="48.9467562" lon="11.4038717"
boundingbox="47.2701114,50.5647142,8.9763497,13.8396373">
Bavaria, Germany
The place information can be found in the `result` element. The attributes of that element contain:
* `place_id` - reference to the Nominatim internal database ID ([see notes](#place_id-is-not-a-persistent-id))
- * `osm_type`, `osm_id` - reference to the OSM object
+ * `osm_type`, `osm_id` - reference to the OSM object ([see notes](#osm-reference))
* `ref` - content of `ref` tag if it exists
* `lat`, `lon` - latitude and longitude of the centroid of the object
* `boundingbox` - comma-separated list of corner coordinates ([see notes](#boundingbox))
Additional information requested with `addressdetails=1`, `extratags=1` and
`namedetails=1` can be found in extra elements.
-#### Search and Lookup
+### Search and Lookup
```
<searchresults timestamp="Sat, 11 Aug 18 11:55:35 +0000"
attribution="Data © OpenStreetMap contributors, ODbL 1.0. https://www.openstreetmap.org/copyright"
querystring="london" polygon="false" exclude_place_ids="100149"
more_url="https://nominatim.openstreetmap.org/search.php?q=london&addressdetails=1&extratags=1&exclude_place_ids=100149&format=xml&accept-language=en-US%2Cen%3Bq%3D0.7%2Cde%3Bq%3D0.3">
- <place place_id="100149" osm_type="node" osm_id="107775" place_rank="15"
+ <place place_id="100149" osm_type="node" osm_id="107775" place_rank="15" address_rank="15"
boundingbox="51.3473219,51.6673219,-0.2876474,0.0323526" lat="51.5073219" lon="-0.1276474"
display_name="London, Greater London, England, SW1A 2DU, United Kingdom"
class="place" type="city" importance="0.9654895765402"
be more than one. The attributes of that element contain:
* `place_id` - reference to the Nominatim internal database ID ([see notes](#place_id-is-not-a-persistent-id))
- * `osm_type`, `osm_id` - reference to the OSM object
+ * `osm_type`, `osm_id` - reference to the OSM object ([see notes](#osm-reference))
* `ref` - content of `ref` tag if it exists
* `lat`, `lon` - latitude and longitude of the centroid of the object
* `boundingbox` - comma-separated list of corner coordinates ([see notes](#boundingbox))
- * `place_rank` - class search rank
+ * `place_rank` - class [search rank](../develop/Ranking#search-rank)
+ * `address_rank` - place [address rank](../develop/Ranking#address-rank)
* `display_name` - full comma-separated address
* `class`, `type` - key and value of the main OSM tag
* `importance` - computed importance rank
as subelements with the type of the address part.
Additional information requested with `extratags=1` and `namedetails=1` can
-be found in extra elements as sub-element of each place.
+be found in extra elements as sub-element of `extratags` and `namedetails`
+respectively.
## Notes on field values
### place_id is not a persistent id
-The `place_id` is created when a Nominatim database gets installed. A
-single place will have a different value on another server or even when
-the same data gets re-imported. It's thus not useful to treat it as
-permanent for later use.
+The `place_id` is an internal identifier that is assigned data is imported
+into a Nominatim database. The same OSM object will have a different value
+on another server. It may even change its ID on the same server when it is
+removed and reimported while updating the database with fresh OSM data.
+It is thus not useful to treat it as permanent for later use.
The combination `osm_type`+`osm_id` is slighly better but remember in
OpenStreetMap mappers can delete, split, recreate places (and those
e.g. when a restaurant is retagged as supermarket. For a more in-depth
discussion see [Permanent ID](https://wiki.openstreetmap.org/wiki/Permanent_ID).
-Nominatim merges some places (e.g. center node of a city with the boundary
-relation) so `osm_type`+`osm_id`+`class_name` would be more unique.
+If you need an ID that is consistent over multiple installations of Nominatim,
+then you should use the combination of `osm_type`+`osm_id`+`class`.
+
+### OSM reference
+
+Nominatim may sometimes return special objects that do not correspond directly
+to an object in OpenStreetMap. These are:
+
+* **Postcodes**. Nominatim returns an postcode point created from all mapped
+ postcodes of the same name. The class and type of these object is `place=postcdode`.
+ No `osm_type` and `osm_id` are included in the result.
+* **Housenumber interpolations**. Nominatim returns a single interpolated
+ housenumber from the interpolation way. The class and type are `place=house`
+ and `osm_type` and `osm_id` correspond to the interpolation way in OSM.
+* **TIGER housenumber.** Nominatim returns a single interpolated housenumber
+ from the TIGER data. The class and type are `place=house`
+ and `osm_type` and `osm_id` correspond to the street mentioned in the result.
+
+Please note that the `osm_type` and `osm_id` returned may be changed in the
+future. You should not expect to only find `node`, `way` and `relation` for
+the type.
### boundingbox
Comma separated list of min latitude, max latitude, min longitude, max longitude.
The whole planet would be `-90,90,-180,180`.
-Can we used to pan and center the map on the result, for example with leafletjs
+Can be used to pan and center the map on the result, for example with leafletjs
mapping library
`map.fitBounds([[bbox[0],bbox[2]],[bbox[1],bbox[3]]], {padding: [20, 20], maxzoom: 16});`
Bounds crossing the antimeridian have a min latitude -180 and max latitude 180,
-essentially covering the planet (See [issue 184](https://github.com/openstreetmap/Nominatim/issues/184)).
+essentially covering the entire planet
+(see [issue 184](https://github.com/openstreetmap/Nominatim/issues/184)).
### addressdetails
# Reverse Geocoding
-Reverse geocoding generates an address from a latitude and longitude or from
-an OSM object.
+Reverse geocoding generates an address from a latitude and longitude.
+
+## How it works
+
+The reverse geocoding API does not exactly compute the address for the
+coordinate it receives. It works by finding the closest suitable OSM object
+and returning its address information. This may occasionally lead to
+unexpected results.
+
+First of all, Nominatim only includes OSM objects in
+its index that are suitable for searching. Small, unnamed paths for example
+are missing from the database and can therefore not be used for reverse
+geocoding either.
+
+The other issue to be aware of is that the closest OSM object may not always
+have a similar enough address to the coordinate you were requesting. For
+example, in dense city areas it may belong to a completely different street.
+
## Parameters
The main format of the reverse API is
```
-https://nominatim.openstreetmap.org/reverse?<query>
+https://nominatim.openstreetmap.org/reverse?lat=<value>&lon=<value>&<params>
```
-There are two ways how the requested location can be specified:
-
-* `lat=<value>` `lon=<value>`
-
- A geographic location to generate an address for. The coordiantes must be
- in WGS84 format.
-
-* `osm_type=[N|W|R]` `osm_id=<value>`
+where `lat` and `lon` are latitude and longitutde of a coordinate in WGS84
+projection. The API returns exactly one result or an error when the coordinate
+is in an area with no OSM data coverage.
- A specific OSM node(N), way(W) or relation(R) to return an address for.
+Additional paramters are accepted as listed below.
-In both cases exactly one object is returned. The two input parameters cannot
-be used at the same time. Both accept the additional optional parameters listed
-below.
+!!! warning "Deprecation warning"
+ The reverse API used to allow address lookup for a single OSM object by
+ its OSM id. This use is now deprecated. Use the [Address Lookup API](../Lookup)
+ instead.
### Output format
* `format=[xml|json|jsonv2|geojson|geocodejson]`
-See [Place Output Formats](Output.md) for details on each format. (Default: html)
+See [Place Output Formats](Output.md) for details on each format. (Default: xml)
* `json_callback=<string>`
* `zoom=[0-18]`
-Level of detail required for the address. Default: 18. This is a number that corresponds
-roughly to the zoom level used in map frameworks like Leaflet.js, Openlayers etc.
+Level of detail required for the address. Default: 18. This is a number that
+corresponds roughly to the zoom level used in XYZ tile sources in frameworks
+like Leaflet.js, Openlayers etc.
In terms of address details the zoom levels are as follows:
zoom | address detail
* `polygon_threshold=0.0`
-Simplify the output geometry before returning. The parameter is the
+Return a simplified version of the output geometry. The parameter is the
tolerance in degrees with which the geometry may differ from the original
geometry. Topology is preserved in the result. (Default: 0.0)
# Search queries
-The search API allows you to look up a location from a textual description.
-Nominatim supports structured as well as free-form search queries.
+The search API allows you to look up a location from a textual description
+or address. Nominatim supports structured and free-form search queries.
The search query may also contain
[special phrases](https://wiki.openstreetmap.org/wiki/Nominatim/Special_Phrases)
which are translated into specific OpenStreetMap (OSM) tags (e.g. Pub => `amenity=pub`).
-Note that this only limits the items to be found, it's not suited to return complete
-lists of OSM objects of a specific type. For those use [Overpass API](https://overpass-api.de/).
+This can be used to narrow down the kind of objects to be returned.
-## Parameters
-
-The search API has the following two formats:
+!!! warning
+ Special phrases are not suitable to query all objects of a certain type in an
+ area. Nominatim will always just return a collection of the best matches. To
+ download OSM data by object type, use the [Overpass API](https://overpass-api.de/).
-```
- https://nominatim.openstreetmap.org/search/<query>?<params>
-```
+## Parameters
-This format only accepts a free-form query string where the
-parts of the query are separated by slashes.
+The search API has the following format:
```
https://nominatim.openstreetmap.org/search?<params>
```
-In this form, the query may be given through two different sets of parameters:
+The search term may be specified with two different sets of parameters:
* `q=<query>`
Structured requests are faster but are less robust against alternative
OSM tagging schemas. **Do not combine with** `q=<query>` **parameter**.
-All three query forms accept the additional parameters listed below.
+Both query forms accept the additional parameters listed below.
### Output format
-* `format=[html|xml|json|jsonv2|geojson|geocodejson]`
+* `format=[xml|json|jsonv2|geojson|geocodejson]`
-See [Place Output Formats](Output.md) for details on each format. (Default: html)
+See [Place Output Formats](Output.md) for details on each format. (Default: jsonv2)
* `json_callback=<string>`
e.g. `gb` for the United Kingdom, `de` for Germany.
Each place in Nominatim is assigned to one country code based
-on `admin_level=2` tags, in rare cases to none (for example in
-international waters outside any country).
+on OSM country boundaries. In rare cases a place may not be in any country
+at all, for example, in international waters.
* `exclude_place_ids=<place_id,[place_id],[place_id]`
If you do not want certain OSM objects to appear in the search
result, give a comma separated list of the `place_id`s you want to skip.
-This can be used to broaden search results. For example, if a previous
-query only returned a few results, then including those here would cause
-the search to return other, less accurate, matches (if possible).
+This can be used to retrieve additional search results. For example, if a
+previous query only returned a few results, then including those here would
+cause the search to return other, less accurate, matches (if possible).
* `limit=<integer>`
* `bounded=[0|1]`
-When a viewbox is given, restrict the result to items contained with that
+When a viewbox is given, restrict the result to items contained within that
viewbox (see above). When `viewbox` and `bounded=1` are given, an amenity
-only search is allowed. In this case, give the special keyword for the
-amenity in square brackets, e.g. `[pub]`. (Default: 0)
+only search is allowed. Give the special keyword for the amenity in square
+brackets, e.g. `[pub]` and a selection of objects of this type is returned.
+There is no guarantee that the result is complete. (Default: 0)
### Polygon output
* `polygon_threshold=0.0`
-Simplify the output geometry before returning. The parameter is the
+Return a simplified version of the output geometry. The parameter is the
tolerance in degrees with which the geometry may differ from the original
geometry. Topology is preserved in the result. (Default: 0.0)
* `dedupe=[0|1]`
Sometimes you have several objects in OSM identifying the same place or
-object in reality. The simplest case is a street being split in many
+object in reality. The simplest case is a street being split into many
different OSM ways due to different characteristics. Nominatim will
attempt to detect such duplicates and only return one match unless
this parameter is set to 0. (Default: 1)
-
-
* `debug=[0|1]`
Output assorted developer debug information. Data on internals of Nominatim's
## Prerequisites for testing and documentation
-The Nominatim tests suite consists of behavioural tests (using behave) and
+The Nominatim test suite consists of behavioural tests (using behave) and
unit tests (using PHPUnit). It has the following additional requirements:
* [behave test framework](https://behave.readthedocs.io) >= 1.2.5
Some of the behavioural test expect a test database to be present. You need at
least 2GB RAM and 10GB disk space to create the database.
-First create a separate directory for the test DB and Fetch the test planet
+First create a separate directory for the test DB and fetch the test planet
data and the Tiger data for South Dakota:
```
make
```
-Copy the test settings:
+Create a minimal test settings file:
```
-cp $USERNAME/Nominatim/test/testdb/local.php settings/
+tee .env << EOF
+NOMINATIM_DATABASE_DSN="pgsql:dbname=test_api_nominatim"
+NOMINATIM_USE_US_TIGER_DATA=yes
+NOMINATIM_TIGER_DATA_PATH=tiger
+NOMINATIM_WIKIPEDIA_DATA_PATH=$USERNAME/Nominatim/test/testdb
+EOF
```
Inspect the file to check that all settings are correct for your local setup.
+In particular, the wikipedia path should point to the test directory in your
+Nominatim source directory.
Now you can import the test database:
# OSM Data Import
-OSM data is initially imported using osm2pgsql. Nominatim uses its own data
-output style 'gazetteer', which differs from the output style created for
-map rendering.
+OSM data is initially imported using [osm2pgsql](https://osm2pgsql.org).
+Nominatim uses its own data output style 'gazetteer', which differs from the
+output style created for map rendering.
## Database Layout
## Configuring the Import
How tags are interpreted and assigned to the different `place` columns can be
-configured via the import style configuration file (`CONST_Import_style`). This
+configured via the import style configuration file (`NOMINATIM_IMPORT_STYLE`). This
is a JSON file which contains a list of rules which are matched against every
tag of every object and then assign the tag its specific role.
## Search rank
The search rank describes the extent and importance of a place. It is used
-when ranking search result. Simply put, if there are two results for a
+when ranking search results. Simply put, if there are two results for a
search query which are otherwise equal, then the result with the _lower_
search rank will be appear higher in the result list.
* highway nodes
* landuse that is not an area
-Other than that, the ranks can be freely assigned via the JSON file
-defined with `CONST_Address_Level_Config` according to their type and
-the country they are in.
+Other than that, the ranks can be freely assigned via the JSON file according
+to their type and the country they are in. The name of the config file to be
+used can be changed with the setting `NOMINATIM_ADDRESS_LEVEL_CONFIG`.
The address level configuration must consist of an array of configuration
entries, each containing a tag definition and an optional country array:
## PHP Unit Tests (`test/php`)
-Unit tests can be found in the php/ directory and tests selected php functions.
+Unit tests can be found in the php/ directory. They test selected php functions.
Very low coverage.
To execute the test suite run
### API Tests (`test/bdd/api`)
These tests are meant to test the different API endpoints and their parameters.
-They require a to import several datasets into a test database.
+They require to import several datasets into a test database.
See the [Development Setup chapter](Development-Environment.md#preparing-the-test-database)
for instructions on how to set up this database.
These tests check the import and update of the Nominatim database. They do not
test the correctness of osm2pgsql. Each test will write some data into the `place`
-table (and optionally `the planet_osm_*` tables if required) and then run
+table (and optionally the `planet_osm_*` tables if required) and then run
Nominatim's processing functions on that.
These tests need to create their own test databases. By default they will be
### Import Tests (`test/bdd/osm2pgsql`)
These tests check that data is imported correctly into the place table. They
-use the same template database as the Indexing tests, so the same remarks apply.
+use the same template database as the DB Creation tests, so the same remarks apply.
The __data import__ stage reads the raw OSM data and extracts all information
that is useful for geocoding. This part is done by osm2pgsql, the same tool
that can also be used to import a rendering database. It uses the special
-gazetteer output plugin in `osm2pgsql/output-gazetter.[ch]pp`. The result of
+gazetteer output plugin in `osm2pgsql/src/output-gazetter.[ch]pp`. The result of
the import can be found in the database table `place`.
The __address computation__ or __indexing__ stage takes the data from `place`
and adds additional information needed for geocoding. It ranks the places by
importance, links objects that belong together and computes addresses and
the search index. Most of this work is done in PL/pgSQL via database triggers
-and can be found in the file `sql/functions.sql`.
+and can be found in the files in the `sql/functions/` directory.
The __search frontend__ implements the actual API. It takes search
and reverse geocoding queries from the user, looks up the data and
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/ClassTypes.php');
+require_once(CONST_LibDir.'/ClassTypes.php');
/**
* Detailed list of address parts for a single result
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/DatabaseError.php');
+require_once(CONST_LibDir.'/DatabaseError.php');
/**
* Uses PDO to access the database specified in the CONST_Database_DSN
{
protected $connection;
- public function __construct($sDSN = CONST_Database_DSN)
+ public function __construct($sDSN = null)
{
- $this->sDSN = $sDSN;
+ $this->sDSN = $sDSN ?? getSetting('DATABASE_DSN');
}
public function connect($bNew = false, $bPersistent = true)
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/PlaceLookup.php');
-require_once(CONST_BasePath.'/lib/Phrase.php');
-require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
-require_once(CONST_BasePath.'/lib/SearchDescription.php');
-require_once(CONST_BasePath.'/lib/SearchContext.php');
-require_once(CONST_BasePath.'/lib/TokenList.php');
+require_once(CONST_LibDir.'/PlaceLookup.php');
+require_once(CONST_LibDir.'/Phrase.php');
+require_once(CONST_LibDir.'/ReverseGeocode.php');
+require_once(CONST_LibDir.'/SearchDescription.php');
+require_once(CONST_LibDir.'/SearchContext.php');
+require_once(CONST_LibDir.'/TokenList.php');
class Geocode
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/AddressDetails.php');
-require_once(CONST_BasePath.'/lib/Result.php');
+require_once(CONST_LibDir.'/AddressDetails.php');
+require_once(CONST_LibDir.'/Result.php');
class PlaceLookup
{
$aOutlineResult = array();
if (!$iPlaceID) return $aOutlineResult;
- if (CONST_Search_AreaPolygons) {
- // Get the bounding box and outline polygon
- $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
- if ($fLonReverse != null && $fLatReverse != null) {
- $sSQL .= ' ST_Y(closest_point) as centrelat,';
- $sSQL .= ' ST_X(closest_point) as centrelon,';
- } else {
- $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
- }
- $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
- $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
- if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
- if ($this->bIncludePolygonAsKML) $sSQL .= ',ST_AsKML(geometry) as askml';
- if ($this->bIncludePolygonAsSVG) $sSQL .= ',ST_AsSVG(geometry) as assvg';
- if ($this->bIncludePolygonAsText) $sSQL .= ',ST_AsText(geometry) as astext';
- if ($fLonReverse != null && $fLatReverse != null) {
- $sFrom = ' from (SELECT * , CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN ';
- $sFrom .=' ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326))';
- $sFrom .=' ELSE centroid END AS closest_point';
- $sFrom .= ' from placex where place_id = '.$iPlaceID.') as plx';
- } else {
- $sFrom = ' from placex where place_id = '.$iPlaceID;
- }
- if ($this->fPolygonSimplificationThreshold > 0) {
- $sSQL .= ' from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry'.$sFrom.') as plx';
- } else {
- $sSQL .= $sFrom;
- }
-
- $aPointPolygon = $this->oDB->getRow($sSQL, null, 'Could not get outline');
+ // Get the bounding box and outline polygon
+ $sSQL = 'select place_id,0 as numfeatures,st_area(geometry) as area,';
+ if ($fLonReverse != null && $fLatReverse != null) {
+ $sSQL .= ' ST_Y(closest_point) as centrelat,';
+ $sSQL .= ' ST_X(closest_point) as centrelon,';
+ } else {
+ $sSQL .= ' ST_Y(centroid) as centrelat, ST_X(centroid) as centrelon,';
+ }
+ $sSQL .= ' ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,';
+ $sSQL .= ' ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon';
+ if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ',ST_AsGeoJSON(geometry) as asgeojson';
+ if ($this->bIncludePolygonAsKML) $sSQL .= ',ST_AsKML(geometry) as askml';
+ if ($this->bIncludePolygonAsSVG) $sSQL .= ',ST_AsSVG(geometry) as assvg';
+ if ($this->bIncludePolygonAsText) $sSQL .= ',ST_AsText(geometry) as astext';
+ if ($fLonReverse != null && $fLatReverse != null) {
+ $sFrom = ' from (SELECT * , CASE WHEN (class = \'highway\') AND (ST_GeometryType(geometry) = \'ST_LineString\') THEN ';
+ $sFrom .=' ST_ClosestPoint(geometry, ST_SetSRID(ST_Point('.$fLatReverse.','.$fLonReverse.'),4326))';
+ $sFrom .=' ELSE centroid END AS closest_point';
+ $sFrom .= ' from placex where place_id = '.$iPlaceID.') as plx';
+ } else {
+ $sFrom = ' from placex where place_id = '.$iPlaceID;
+ }
+ if ($this->fPolygonSimplificationThreshold > 0) {
+ $sSQL .= ' from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,'.$this->fPolygonSimplificationThreshold.') as geometry'.$sFrom.') as plx';
+ } else {
+ $sSQL .= $sFrom;
+ }
- if ($aPointPolygon && $aPointPolygon['place_id']) {
- if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
- $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
- $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
- }
+ $aPointPolygon = $this->oDB->getRow($sSQL, null, 'Could not get outline');
- if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
- if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
- if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
- if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
+ if ($aPointPolygon && $aPointPolygon['place_id']) {
+ if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null) {
+ $aOutlineResult['lat'] = $aPointPolygon['centrelat'];
+ $aOutlineResult['lon'] = $aPointPolygon['centrelon'];
+ }
- if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
- $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
- $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
- }
+ if ($this->bIncludePolygonAsGeoJSON) $aOutlineResult['asgeojson'] = $aPointPolygon['asgeojson'];
+ if ($this->bIncludePolygonAsKML) $aOutlineResult['askml'] = $aPointPolygon['askml'];
+ if ($this->bIncludePolygonAsSVG) $aOutlineResult['assvg'] = $aPointPolygon['assvg'];
+ if ($this->bIncludePolygonAsText) $aOutlineResult['astext'] = $aPointPolygon['astext'];
- if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
- $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
- $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
- }
+ if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001) {
+ $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
+ $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
+ }
- $aOutlineResult['aBoundingBox'] = array(
- (string)$aPointPolygon['minlat'],
- (string)$aPointPolygon['maxlat'],
- (string)$aPointPolygon['minlon'],
- (string)$aPointPolygon['maxlon']
- );
+ if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001) {
+ $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
+ $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
}
+
+ $aOutlineResult['aBoundingBox'] = array(
+ (string)$aPointPolygon['minlat'],
+ (string)$aPointPolygon['maxlat'],
+ (string)$aPointPolygon['minlon'],
+ (string)$aPointPolygon['maxlon']
+ );
}
// as a fallback we generate a bounding box without knowing the size of the geometry
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/Result.php');
+require_once(CONST_LibDir.'/Result.php');
class ReverseGeocode
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/lib.php');
+require_once(CONST_LibDir.'/lib.php');
/**
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
-require_once(CONST_BasePath.'/lib/SearchContext.php');
-require_once(CONST_BasePath.'/lib/Result.php');
+require_once(CONST_LibDir.'/SpecialSearchOperator.php');
+require_once(CONST_LibDir.'/SearchContext.php');
+require_once(CONST_LibDir.'/Result.php');
/**
* Description of a single interpretation of a search query.
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/TokenCountry.php');
-require_once(CONST_BasePath.'/lib/TokenHousenumber.php');
-require_once(CONST_BasePath.'/lib/TokenPostcode.php');
-require_once(CONST_BasePath.'/lib/TokenSpecialTerm.php');
-require_once(CONST_BasePath.'/lib/TokenWord.php');
-require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
+require_once(CONST_LibDir.'/TokenCountry.php');
+require_once(CONST_LibDir.'/TokenHousenumber.php');
+require_once(CONST_LibDir.'/TokenPostcode.php');
+require_once(CONST_LibDir.'/TokenSpecialTerm.php');
+require_once(CONST_LibDir.'/TokenWord.php');
+require_once(CONST_LibDir.'/SpecialSearchOperator.php');
/**
* Saves information about the tokens that appear in a search query.
namespace Nominatim\Token;
-require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
+require_once(CONST_LibDir.'/SpecialSearchOperator.php');
/**
* A word token describing a place type.
<?php
-require_once(CONST_BasePath.'/lib/Shell.php');
+require_once(CONST_LibDir.'/Shell.php');
function getCmdOpt($aArg, $aSpec, &$aResult, $bExitOnError = false, $bExitOnUnknown = false)
{
function runSQLScript($sScript, $bfatal = true, $bVerbose = false, $bIgnoreErrors = false)
{
// Convert database DSN to psql parameters
- $aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
+ $aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
$oCmd = new \Nominatim\Shell('psql');
fail("pgsql returned with error code ($iReturn)");
}
}
+
+function setupHTTPProxy()
+{
+ if (!getSettingBool('HTTP_PROXY')) {
+ return;
+ }
+
+ $sProxy = 'tcp://'.getSetting('HTTP_PROXY_HOST').':'.getSetting('HTTP_PROXY_PROT');
+ $aHeaders = array();
+
+ $sLogin = getSetting('HTTP_PROXY_LOGIN');
+ $sPassword = getSetting('HTTP_PROXY_PASSWORD');
+
+ if ($sLogin && $sPassword) {
+ $sAuth = base64_encode($sLogin.':'.$sPassword);
+ $aHeaders = array('Proxy-Authorization: Basic '.$sAuth);
+ }
+
+ $aProxyHeader = array(
+ 'proxy' => $sProxy,
+ 'request_fulluri' => true,
+ 'header' => $aHeaders
+ );
+
+ $aContext = array('http' => $aProxyHeader, 'https' => $aProxyHeader);
+ stream_context_set_default($aContext);
+}
require_once('init.php');
require_once('cmd.php');
require_once('DebugNone.php');
-
-// handle http proxy when using file_get_contents
-if (CONST_HTTP_Proxy) {
- $proxy = 'tcp://' . CONST_HTTP_Proxy_Host . ':' . CONST_HTTP_Proxy_Port;
- $aHeaders = array();
- if (CONST_HTTP_Proxy_Login != null && CONST_HTTP_Proxy_Login != '' && CONST_HTTP_Proxy_Password != null && CONST_HTTP_Proxy_Password != '') {
- $auth = base64_encode(CONST_HTTP_Proxy_Login . ':' . CONST_HTTP_Proxy_Password);
- $aHeaders = array("Proxy-Authorization: Basic $auth");
- }
- $aContext = array(
- 'http' => array(
- 'proxy' => $proxy,
- 'request_fulluri' => true,
- 'header' => $aHeaders
- ),
- 'https' => array(
- 'proxy' => $proxy,
- 'request_fulluri' => true,
- 'header' => $aHeaders
- )
- );
- stream_context_set_default($aContext);
-}
{
http_response_code($exception->getCode());
header('Content-type: application/json; charset=utf-8');
- include(CONST_BasePath.'/lib/template/error-json.php');
+ include(CONST_LibDir.'/template/error-json.php');
exit();
}
http_response_code($exception->getCode());
header('Content-type: text/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
- include(CONST_BasePath.'/lib/template/error-xml.php');
+ include(CONST_LibDir.'/template/error-xml.php');
exit();
}
<?php
-require_once(CONST_BasePath.'/lib/lib.php');
-require_once(CONST_BasePath.'/lib/DB.php');
+require_once(CONST_LibDir.'/lib.php');
+require_once(CONST_LibDir.'/DB.php');
<?php
+require('Symfony/Component/Dotenv/autoload.php');
+
+function loadSettings($sProjectDir)
+{
+ @define('CONST_InstallDir', $sProjectDir);
+
+ $dotenv = new \Symfony\Component\Dotenv\Dotenv();
+ $dotenv->load(CONST_DataDir.'/settings/env.defaults');
+
+ if (file_exists($sProjectDir.'/.env')) {
+ $dotenv->load($sProjectDir.'/.env');
+ }
+}
+
+function getSetting($sConfName, $sDefault = null)
+{
+ $sValue = $_SERVER['NOMINATIM_'.$sConfName];
+
+ if ($sDefault !== null && !$sValue) {
+ return $sDefault;
+ }
+
+ return $sValue;
+}
+
+function getSettingBool($sConfName)
+{
+ $sVal = strtolower(getSetting($sConfName));
+
+ return strcmp($sVal, 'yes') == 0
+ || strcmp($sVal, 'true') == 0
+ || strcmp($sVal, '1') == 0;
+}
+
+function getSettingConfig($sConfName, $sSystemConfig)
+{
+ $sValue = $_ENV['NOMINATIM_'.$sConfName];
+
+ if (!$sValue) {
+ return CONST_DataDir.'/settings/'.$sSystemConfig;
+ }
+
+ return $sValue;
+}
+
function fail($sError, $sUserError = false)
{
if (!$sUserError) $sUserError = $sError;
return "'".$s."'";
}
+function fwriteConstDef($rFile, $sConstName, $value)
+{
+ $sEscapedValue;
+
+ if (is_bool($value)) {
+ $sEscapedValue = $value ? 'true' : 'false';
+ } elseif (is_numeric($value)) {
+ $sEscapedValue = strval($value);
+ } elseif (!$value) {
+ $sEscapedValue = 'false';
+ } else {
+ $sEscapedValue = addQuotes(str_replace("'", "\\'", (string)$value));
+ }
+
+ fwrite($rFile, "@define('CONST_$sConstName', $sEscapedValue);\n");
+}
+
+
function parseLatLon($sQuery)
{
$sFound = null;
namespace Nominatim\Setup;
-require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
-require_once(CONST_BasePath.'/lib/Shell.php');
+require_once(CONST_LibDir.'/setup/AddressLevelParser.php');
+require_once(CONST_LibDir.'/Shell.php');
class SetupFunctions
{
if (isset($aCMDResult['osm2pgsql-cache'])) {
$this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
- } elseif (!is_null(CONST_Osm2pgsql_Flatnode_File)) {
+ } elseif (getSetting('FLATNODE_FILE')) {
// When flatnode files are enabled then disable cache per default.
$this->iCacheMemory = 0;
} else {
$this->iCacheMemory = getCacheMemoryMB();
}
- $this->sModulePath = CONST_Database_Module_Path;
+ $this->sModulePath = getSetting('DATABASE_MODULE_PATH', CONST_InstallDir.'/module');
info('module path: ' . $this->sModulePath);
// parse database string
- $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_Database_DSN);
+ $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
if (!isset($this->aDSNInfo['port'])) {
$this->aDSNInfo['port'] = 5432;
}
$oDB = new \Nominatim\DB;
if ($oDB->checkConnection()) {
- fail('database already exists ('.CONST_Database_DSN.')');
+ fail('database already exists ('.getSetting('DATABASE_DSN').')');
}
$oCmd = (new \Nominatim\Shell('createdb'))
exit(1);
}
- $i = $this->db()->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
+ $sPgUser = getSetting('DATABASE_WEBUSER');
+ $i = $this->db()->getOne("select count(*) from pg_user where usename = '$sPgUser'");
if ($i == 0) {
- echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
- echo "\n createuser ".CONST_Database_Web_User."\n\n";
+ echo "\nERROR: Web user '".$sPgUser."' does not exist. Create it with:\n";
+ echo "\n createuser ".$sPgUser."\n\n";
exit(1);
}
// Try accessing the C module, so we know early if something is wrong
- checkModulePresence(); // raises exception on failure
+ $this->checkModulePresence(); // raises exception on failure
- if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
+ if (!file_exists(CONST_DataDir.'/data/country_osm_grid.sql.gz')) {
echo 'Error: you need to download the country_osm_grid first:';
- echo "\n wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
+ echo "\n wget -O ".CONST_DataDir."/data/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
exit(1);
}
- $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
- $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
- $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
- $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
+ $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_name.sql');
+ $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_osm_grid.sql.gz');
+ $this->pgsqlRunScriptFile(CONST_DataDir.'/data/gb_postcode_table.sql');
+ $this->pgsqlRunScriptFile(CONST_DataDir.'/data/us_postcode_table.sql');
- $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
+ $sPostcodeFilename = CONST_DataDir.'/data/gb_postcode_data.sql.gz';
if (file_exists($sPostcodeFilename)) {
$this->pgsqlRunScriptFile($sPostcodeFilename);
} else {
warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
}
- $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
+ $sPostcodeFilename = CONST_DataDir.'/data/us_postcode_data.sql.gz';
if (file_exists($sPostcodeFilename)) {
$this->pgsqlRunScriptFile($sPostcodeFilename);
} else {
{
info('Import data');
- if (!file_exists(CONST_Osm2pgsql_Binary)) {
- echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
+ if (!file_exists(getOsm2pgsqlBinary())) {
+ echo "Check NOMINATIM_OSM2PGSQL_BINARY in your local .env file.\n";
echo "Normally you should not need to set this manually.\n";
- fail("osm2pgsql not found in '".CONST_Osm2pgsql_Binary."'");
+ fail("osm2pgsql not found in '".getOsm2pgsqlBinary()."'");
}
- $oCmd = new \Nominatim\Shell(CONST_Osm2pgsql_Binary);
- $oCmd->addParams('--style', CONST_Import_Style);
+ $oCmd = new \Nominatim\Shell(getOsm2pgsqlBinary());
+ $oCmd->addParams('--style', getImportStyle());
- if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
- $oCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
+ if (getSetting('FLATNODE_FILE')) {
+ $oCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
}
- if (CONST_Tablespace_Osm2pgsql_Data) {
- $oCmd->addParams('--tablespace-slim-data', CONST_Tablespace_Osm2pgsql_Data);
+ if (getSetting('TABLESPACE_OSM_DATA')) {
+ $oCmd->addParams('--tablespace-slim-data', getSetting('TABLESPACE_OSM_DATA'));
}
- if (CONST_Tablespace_Osm2pgsql_Index) {
- $oCmd->addParams('--tablespace-slim-index', CONST_Tablespace_Osm2pgsql_Index);
+ if (getSetting('TABLESPACE_OSM_INDEX')) {
+ $oCmd->addParams('--tablespace-slim-index', getSetting('TABLESPACE_OSM_INDEX'));
}
- if (CONST_Tablespace_Place_Data) {
- $oCmd->addParams('--tablespace-main-data', CONST_Tablespace_Place_Data);
+ if (getSetting('TABLESPACE_PLACE_DATA')) {
+ $oCmd->addParams('--tablespace-main-data', getSetting('TABLESPACE_PLACE_DATA'));
}
- if (CONST_Tablespace_Place_Index) {
- $oCmd->addParams('--tablespace-main-index', CONST_Tablespace_Place_Index);
+ if (getSetting('TABLESPACE_PLACE_INDEX')) {
+ $oCmd->addParams('--tablespace-main-index', getSetting('TABLESPACE_PLACE_INDEX'));
}
$oCmd->addParams('--latlong', '--slim', '--create');
$oCmd->addParams('--output', 'gazetteer');
info('Create Functions');
// Try accessing the C module, so we know early if something is wrong
- checkModulePresence(); // raises exception on failure
+ $this->checkModulePresence(); // raises exception on failure
$this->createSqlFunctions();
}
{
info('Create Tables');
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/tables.sql');
$sTemplate = $this->replaceSqlPatterns($sTemplate);
$this->pgsqlRunScript($sTemplate, false);
$this->dropTable('search_name');
}
- $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
+ $oAlParser = new AddressLevelParser(getSettingConfig('ADDRESS_LEVEL_CONFIG', 'address-levels.json'));
$oAlParser->createTable($this->db(), 'address_levels');
}
{
info('Create Tables');
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/table-triggers.sql');
$sTemplate = $this->replaceSqlPatterns($sTemplate);
$this->pgsqlRunScript($sTemplate, false);
{
info('Create Partition Tables');
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-tables.src.sql');
$sTemplate = $this->replaceSqlPatterns($sTemplate);
$this->pgsqlRunPartitionScript($sTemplate);
{
info('Create Partition Functions');
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-functions.src.sql');
$this->pgsqlRunPartitionScript($sTemplate);
}
public function importWikipediaArticles()
{
- $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
+ $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_DataDir.'/data');
+ $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
if (file_exists($sWikiArticlesFile)) {
info('Importing wikipedia articles and redirects');
$this->dropTable('wikipedia_article');
// used by getorcreate_word_id to ignore frequent partial words
$sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
- $sSQL .= '$$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
+ $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
$oDB->exec($sSQL);
echo ".\n";
// pre-create the word list
if (!$bDisableTokenPrecalc) {
info('Loading word list');
- $this->pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
+ $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
}
info('Load Data');
$iLoadThreads = max(1, $this->iInstances - 1);
for ($i = 0; $i < $iLoadThreads; $i++) {
// https://secure.php.net/manual/en/function.pg-connect.php
- $DSN = CONST_Database_DSN;
+ $DSN = getSetting('DATABASE_DSN');
$DSN = preg_replace('/^pgsql:/', '', $DSN);
$DSN = preg_replace('/;/', ' ', $DSN);
$aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
// last thread for interpolation lines
// https://secure.php.net/manual/en/function.pg-connect.php
- $DSN = CONST_Database_DSN;
+ $DSN = getSetting('DATABASE_DSN');
$DSN = preg_replace('/^pgsql:/', '', $DSN);
$DSN = preg_replace('/;/', ' ', $DSN);
$aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
}
}
- public function importTigerData()
+ public function importTigerData($sTigerPath)
{
info('Import Tiger data');
- $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
- info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
+ $aFilenames = glob($sTigerPath.'/*.sql');
+ info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
if (empty($aFilenames)) {
- warn('Tiger data import selected but no files found in path '.CONST_Tiger_Data_Path);
+ warn('Tiger data import selected but no files found in path '.$sTigerPath);
return;
}
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
$sTemplate = $this->replaceSqlPatterns($sTemplate);
$this->pgsqlRunScript($sTemplate, false);
$aDBInstances = array();
for ($i = 0; $i < $this->iInstances; $i++) {
// https://secure.php.net/manual/en/function.pg-connect.php
- $DSN = CONST_Database_DSN;
+ $DSN = getSetting('DATABASE_DSN');
$DSN = preg_replace('/^pgsql:/', '', $DSN);
$DSN = preg_replace('/;/', ' ', $DSN);
$aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
}
info('Creating indexes on Tiger data');
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
$sTemplate = $this->replaceSqlPatterns($sTemplate);
$this->pgsqlRunScript($sTemplate, false);
public function index($bIndexNoanalyse)
{
- checkModulePresence(); // raises exception on failure
+ $this->checkModulePresence(); // raises exception on failure
- $oBaseCmd = (new \Nominatim\Shell(CONST_BasePath.'/nominatim/nominatim.py'))
+ $oBaseCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
->addParams('--database', $this->aDSNInfo['database'])
->addParams('--port', $this->aDSNInfo['port'])
->addParams('--threads', $this->iInstances);
$this->db()->exec("DROP INDEX $sIndexName;");
}
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
if (!$this->bDrop) {
- $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_updates.src.sql');
+ $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
}
if (!$this->dbReverseOnly()) {
- $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
+ $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
}
$sTemplate = $this->replaceSqlPatterns($sTemplate);
$this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
$sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
.'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
- if (CONST_Languages) {
+ $sLanguages = getSetting('LANGUAGES');
+ if ($sLanguages) {
$sSQL .= 'in ';
$sDelim = '(';
- foreach (explode(',', CONST_Languages) as $sLang) {
+ foreach (explode(',', $sLanguages) as $sLang) {
$sSQL .= $sDelim."'name:$sLang'";
$sDelim = ',';
}
}
/**
- * Setup settings-frontend.php in the build/website directory
+ * Setup the directory for the API scripts.
*
* @return null
*/
public function setupWebsite()
{
- $rOutputFile = fopen(CONST_InstallPath.'/settings/settings-frontend.php', 'w');
-
- fwrite($rOutputFile, "<?php
-@define('CONST_BasePath', '".CONST_BasePath."');
-if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));
-
-@define('CONST_Database_DSN', '".CONST_Database_DSN."');
-@define('CONST_Default_Language', ".(CONST_Default_Language ? ("'".CONST_Default_Language."'") : 'false').");
-@define('CONST_Log_DB', ".(CONST_Log_DB ? 'true' : 'false').");
-@define('CONST_Log_File', ".(CONST_Log_File ? ("'".CONST_Log_File."'") : 'false').");
-@define('CONST_Max_Word_Frequency', '".CONST_Max_Word_Frequency."');
-@define('CONST_NoAccessControl', ".CONST_NoAccessControl.");
-@define('CONST_Places_Max_ID_count', ".CONST_Places_Max_ID_count.");
-@define('CONST_PolygonOutput_MaximumTypes', ".CONST_PolygonOutput_MaximumTypes.");
-@define('CONST_Search_AreaPolygons', ".CONST_Search_AreaPolygons.");
-@define('CONST_Search_BatchMode', ".(CONST_Search_BatchMode ? 'true' : 'false').");
-@define('CONST_Search_NameOnlySearchFrequencyThreshold', ".CONST_Search_NameOnlySearchFrequencyThreshold.");
-@define('CONST_Search_ReversePlanForAll', ".CONST_Search_ReversePlanForAll.");
-@define('CONST_Term_Normalization_Rules', \"".CONST_Term_Normalization_Rules."\");
-@define('CONST_Use_Aux_Location_data', ".(CONST_Use_Aux_Location_data ? 'true' : 'false').");
-@define('CONST_Use_US_Tiger_Data', ".(CONST_Use_US_Tiger_Data ? 'true' : 'false').");
-@define('CONST_MapIcon_URL', ".(CONST_MapIcon_URL ? ("'".CONST_MapIcon_URL."'") : 'false').');
-');
- info(CONST_InstallPath.'/settings/settings-frontend.php has been set up successfully');
+ if (!is_dir(CONST_InstallDir.'/website')) {
+ info('Creating directory for website scripts at: '.CONST_InstallDir.'/website');
+ mkdir(CONST_InstallDir.'/website');
+ }
+
+ $aScripts = array(
+ 'deletable.php',
+ 'details.php',
+ 'lookup.php',
+ 'polygons.php',
+ 'reverse.php',
+ 'search.php',
+ 'status.php'
+ );
+
+ foreach ($aScripts as $sScript) {
+ $rFile = fopen(CONST_InstallDir.'/website/'.$sScript, 'w');
+
+ fwrite($rFile, "<?php\n\n");
+ fwrite($rFile, '@define(\'CONST_Debug\', $_GET[\'debug\'] ?? false);'."\n\n");
+
+ fwriteConstDef($rFile, 'LibDir', CONST_LibDir);
+ fwriteConstDef($rFile, 'DataDir', CONST_DataDir);
+ fwriteConstDef($rFile, 'InstallDir', CONST_InstallDir);
+
+ fwrite($rFile, "if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));\n\n");
+
+ fwriteConstDef($rFile, 'Database_DSN', getSetting('DATABASE_DSN'));
+ fwriteConstDef($rFile, 'Default_Language', getSetting('DEFAULT_LANGUAGE'));
+ fwriteConstDef($rFile, 'Log_DB', getSettingBool('LOG_DB'));
+ fwriteConstDef($rFile, 'Log_File', getSetting('LOG_FILE'));
+ fwriteConstDef($rFile, 'Max_Word_Frequency', (int)getSetting('MAX_WORD_FREQUENCY'));
+ fwriteConstDef($rFile, 'NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
+ fwriteConstDef($rFile, 'Places_Max_ID_count', (int)getSetting('LOOKUP_MAX_COUNT'));
+ fwriteConstDef($rFile, 'PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
+ fwriteConstDef($rFile, 'Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
+ fwriteConstDef($rFile, 'Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
+ fwriteConstDef($rFile, 'Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
+ fwriteConstDef($rFile, 'Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
+ fwriteConstDef($rFile, 'Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
+ fwriteConstDef($rFile, 'MapIcon_URL', getSetting('MAPICON_URL'));
+
+ // XXX scripts should go into the library.
+ fwrite($rFile, 'require_once(\''.CONST_DataDir.'/website/'.$sScript."');\n");
+ fclose($rFile);
+
+ chmod(CONST_InstallDir.'/website/'.$sScript, 0755);
+ }
}
/**
private function removeFlatnodeFile()
{
- if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
- if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
- if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
- unlink(CONST_Osm2pgsql_Flatnode_File);
- }
+ $sFName = getSetting('FLATNODE_FILE');
+ if ($sFName && file_exists($sFName)) {
+ if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
+ unlink($sFName);
}
}
private function createSqlFunctions()
{
- $sBasePath = CONST_BasePath.'/sql/functions/';
+ $sBasePath = CONST_DataDir.'/sql/functions/';
$sTemplate = file_get_contents($sBasePath.'utils.sql');
$sTemplate .= file_get_contents($sBasePath.'normalization.sql');
$sTemplate .= file_get_contents($sBasePath.'ranking.sql');
if ($this->bEnableDebugStatements) {
$sTemplate = str_replace('--DEBUG:', '', $sTemplate);
}
- if (CONST_Limit_Reindexing) {
+ if (getSettingBool('LIMIT_REINDEXING')) {
$sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
}
- if (!CONST_Use_US_Tiger_Data) {
+ if (!getSettingBool('USE_US_TIGER_DATA')) {
$sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
}
- if (!CONST_Use_Aux_Location_data) {
+ if (!getSettingBool('USE_AUX_LOCATION_DATA')) {
$sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
}
private function replaceSqlPatterns($sSql)
{
- $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
+ $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
$aPatterns = array(
- '{ts:address-data}' => CONST_Tablespace_Address_Data,
- '{ts:address-index}' => CONST_Tablespace_Address_Index,
- '{ts:search-data}' => CONST_Tablespace_Search_Data,
- '{ts:search-index}' => CONST_Tablespace_Search_Index,
- '{ts:aux-data}' => CONST_Tablespace_Aux_Data,
- '{ts:aux-index}' => CONST_Tablespace_Aux_Index,
+ '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
+ '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
+ '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
+ '{ts:search-index}' => getSetting('TABLESPACE_SEARCH_INDEX'),
+ '{ts:aux-data}' => getSetting('TABLESPACE_AUX_DATA'),
+ '{ts:aux-index}' => getSetting('TABLESPACE_AUX_INDEX')
);
foreach ($aPatterns as $sPattern => $sTablespace) {
{
return !($this->db()->tableExists('search_name'));
}
+
+ /**
+ * Try accessing the C module, so we know early if something is wrong.
+ *
+ * Raises Nominatim\DatabaseError on failure
+ */
+ private function checkModulePresence()
+ {
+ $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
+ $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
+ $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
+
+ $oDB = new \Nominatim\DB();
+ $oDB->connect();
+ $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');
+ }
}
}
}
-function checkModulePresence()
+function getOsm2pgsqlBinary()
{
- // Try accessing the C module, so we know early if something is wrong.
- // Raises Nominatim\DatabaseError on failure
+ $sBinary = getSetting('OSM2PGSQL_BINARY');
+ if (!$sBinary) {
+ $sBinary = CONST_InstallDir.'/osm2pgsql/osm2pgsql';
+ }
+
+ return $sBinary;
+}
- $sModulePath = CONST_Database_Module_Path;
- $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
- $sSQL .= $sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
- $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
+function getImportStyle()
+{
+ $sStyle = getSetting('IMPORT_STYLE');
+
+ if (in_array($sStyle, array('admin', 'street', 'address', 'full', 'extratags'))) {
+ return CONST_DataDir.'/settings/import-'.$sStyle.'.style';
+ }
- $oDB = new \Nominatim\DB();
- $oDB->connect();
- $oDB->exec($sSQL, null, 'Database server failed to load '.$sModulePath.'/nominatim.so module');
+ return $sStyle;
}
+++ /dev/null
-<?php
-@define('CONST_BasePath', '@CMAKE_SOURCE_DIR@');
-@define('CONST_InstallPath', '@CMAKE_BINARY_DIR@');
-if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));
-if (file_exists(CONST_InstallPath.'/settings/local.php')) require_once(CONST_InstallPath.'/settings/local.php');
-
-// General settings
-@define('CONST_Database_DSN', 'pgsql:dbname=nominatim'); // or add ;host=...;port=...;user=...;password=...
-@define('CONST_Database_Web_User', 'www-data');
-@define('CONST_Database_Module_Path', CONST_InstallPath.'/module');
-@define('CONST_Max_Word_Frequency', '50000');
-@define('CONST_Limit_Reindexing', true);
-// Restrict search languages.
-// Normally Nominatim will include all language variants of name:XX
-// in the search index. Set this to a comma separated list of language
-// codes, to restrict import to a subset of languages.
-// Currently only affects the import of country names and special phrases.
-@define('CONST_Languages', false);
-// Rules for normalizing terms for comparison before doing comparisons.
-// The default is to remove accents and punctuation and to lower-case the
-// term. Spaces are kept but collapsed to one standard space.
-@define('CONST_Term_Normalization_Rules', ":: NFD (); [[:Nonspacing Mark:] [:Cf:]] >; :: lower (); [[:Punctuation:][:Space:]]+ > ' '; :: NFC ();");
-
-/* Set to true after importing Tiger house number data for the US.
- Note: The tables must already exist or queries will throw errors.
- After changing this setting run ./utils/setup --create-functions
- again. */
-@define('CONST_Use_US_Tiger_Data', false);
-/* Set to true after importing other external house number data.
- Note: the aux tables must already exist or queries will throw errors.
- After changing this setting run ./utils/setup --create-functions
- again. */
-@define('CONST_Use_Aux_Location_data', false);
-
-// Proxy settings
-@define('CONST_HTTP_Proxy', false);
-@define('CONST_HTTP_Proxy_Host', 'proxy.mydomain.com');
-@define('CONST_HTTP_Proxy_Port', '3128');
-@define('CONST_HTTP_Proxy_Login', '');
-@define('CONST_HTTP_Proxy_Password', '');
-
-// Paths
-@define('CONST_ExtraDataPath', CONST_BasePath.'/data');
-@define('CONST_Osm2pgsql_Binary', CONST_InstallPath.'/osm2pgsql/osm2pgsql');
-@define('CONST_Pyosmium_Binary', '@PYOSMIUM_PATH@');
-@define('CONST_Tiger_Data_Path', CONST_ExtraDataPath.'/tiger');
-@define('CONST_Wikipedia_Data_Path', CONST_ExtraDataPath);
-@define('CONST_Phrase_Config', CONST_BasePath.'/settings/phrase_settings.php');
-@define('CONST_Address_Level_Config', CONST_BasePath.'/settings/address-levels.json');
-@define('CONST_Import_Style', CONST_BasePath.'/settings/import-full.style');
-
-// osm2pgsql settings
-@define('CONST_Osm2pgsql_Flatnode_File', null);
-
-// tablespace settings
-// osm2pgsql caching tables (aka slim mode tables) - update only
-@define('CONST_Tablespace_Osm2pgsql_Data', false);
-@define('CONST_Tablespace_Osm2pgsql_Index', false);
-// osm2pgsql output tables (aka main table) - update only
-@define('CONST_Tablespace_Place_Data', false);
-@define('CONST_Tablespace_Place_Index', false);
-// address computation tables - update only
-@define('CONST_Tablespace_Address_Data', false);
-@define('CONST_Tablespace_Address_Index', false);
-// search tables - needed for lookups
-@define('CONST_Tablespace_Search_Data', false);
-@define('CONST_Tablespace_Search_Index', false);
-// additional data, e.g. TIGER data, type searches - needed for lookups
-@define('CONST_Tablespace_Aux_Data', false);
-@define('CONST_Tablespace_Aux_Index', false);
-
-//// Replication settings
-
-// Base URL of replication service
-@define('CONST_Replication_Url', 'https://planet.openstreetmap.org/replication/minute');
-
-// Maximum size in MB of data to download per batch
-@define('CONST_Replication_Max_Diff_size', '30');
-// How long until the service publishes the next diff
-// (relative to the age of data in the diff).
-@define('CONST_Replication_Update_Interval', '75');
-// How long to sleep when no update could be found
-@define('CONST_Replication_Recheck_Interval', '60');
-
-// If true, send CORS headers to allow access
-@define('CONST_NoAccessControl', true);
-
-// Set this to the /mapicon directory of your nominatim-ui to enable returning
-// icon URLs with the results.
-@define('CONST_MapIcon_URL', false);
-// Language to assume when none is supplied with the query.
-// When set to false, the local language (i.e. the name tag without suffix)
-// will be used.
-@define('CONST_Default_Language', false);
-
-@define('CONST_Search_AreaPolygons', true);
-
-@define('CONST_Search_BatchMode', false);
-
-@define('CONST_Search_NameOnlySearchFrequencyThreshold', 500);
-// If set to true, then reverse order of queries will be tried by default.
-// When set to false only selected languages allow reverse search.
-@define('CONST_Search_ReversePlanForAll', true);
-
-// Maximum number of OSM ids that may be queried at once
-// for the places endpoint.
-@define('CONST_Places_Max_ID_count', 50);
-
-// Number of different geometry formats that may be queried in parallel.
-// Set to zero to disable polygon output.
-@define('CONST_PolygonOutput_MaximumTypes', 1);
-
-// Log settings
-// Set to true to log into new_query_log table.
-// You should set up a cron job that regularly clears out this table.
-@define('CONST_Log_DB', false);
-// Set to a file name to enable logging to a file.
-@define('CONST_Log_File', false);
--- /dev/null
+# .env
+# Default configuration settings for Nominatim.
+# This file uses the dotenv format.
+
+# Database connection string.
+# Add host, port, user etc through additional semicolon-separated attributes.
+# e.g. ;host=...;port=...;user=...;password=...
+# Changing this variable requires to run 'setup.php --setup-website'.
+NOMINATIM_DATABASE_DSN="pgsql:dbname=nominatim"
+
+# Database web user.
+# Nominatim sets up read-only access for this user during installation.
+NOMINATIM_DATABASE_WEBUSER="www-data"
+
+# Directory where to find the PostgreSQL server module.
+# When empty the module is expected to be located in the 'module' subdirectory
+# in the project directory.
+# Changing this value requires to run ./utils/setup --create-functions.
+NOMINATIM_DATABASE_MODULE_PATH=
+
+# Number of occurances of a word before it is considered frequent.
+# Similar to the concept of stop words. Frequent partial words get ignored
+# or handled differently during search.
+# Changing this value requires a reimport.
+NOMINATIM_MAX_WORD_FREQUENCY=50000
+
+# If true, admin level changes on places with many contained children are blocked.
+NOMINATIM_LIMIT_REINDEXING=yes
+
+# Restrict search languages.
+# Normally Nominatim will include all language variants of name:XX
+# in the search index. Set this to a comma separated list of language
+# codes, to restrict import to a subset of languages.
+# Currently only affects the initial import of country names and special phrases.
+NOMINATIM_LANGUAGES=
+
+# Rules for normalizing terms for comparisons.
+# The default is to remove accents and punctuation and to lower-case the
+# term. Spaces are kept but collapsed to one standard space.
+# Changing this value requires a reimport.
+NOMINATIM_TERM_NORMALIZATION=":: NFD (); [[:Nonspacing Mark:] [:Cf:]] >; :: lower (); [[:Punctuation:][:Space:]]+ > ' '; :: NFC ();"
+
+# Search in the Tiger house number data for the US.
+# Note: The tables must already exist or queries will throw errors.
+# Changing this value requires to run ./utils/setup --create-functions --setup-website.
+NOMINATIM_USE_US_TIGER_DATA=no
+
+# Search in the auxilary housenumber table.
+# Changing this value requires to run ./utils/setup --create-functions --setup-website.
+NOMINATIM_USE_AUX_LOCATION_DATA=no
+
+# Proxy settings
+# The following settings allow to set a proxy to use when remotely downloading
+# data. Host and port are required. Login and password are optional.
+NOMINATIM_HTTP_PROXY=no
+NOMINATIM_HTTP_PROXY_HOST=proxy.mydomain.com
+NOMINATIM_HTTP_PROXY_PORT=3128
+NOMINATIM_HTTP_PROXY_LOGIN=
+NOMINATIM_HTTP_PROXY_PASSWORD=
+
+# Location of the osm2pgsql binary.
+# When empty, osm2pgsql is expected to reside in the osm2pgsql directory in
+# the project directory.
+# EXPERT ONLY. You should usually use the supplied osm2pgsql.
+NOMINATIM_OSM2PGSQL_BINARY=
+
+# Location of pyosmium-get-changes.
+# Only needed when running updates.
+NOMINATIM_PYOSMIUM_BINARY=
+
+# Directory where to find US Tiger data files to import.
+# Used with setup.php --import-tiger-data. When unset, the data is expected
+# to be located under 'data/tiger' in the source tree.
+NOMINATIM_TIGER_DATA_PATH=
+
+# Directory where to find pre-computed Wikipedia importance files.
+# When unset, the data is expected to be located in the 'data' directory
+# in the source tree.
+NOMINATIM_WIKIPEDIA_DATA_PATH=
+
+# Configuration file for special phrase import.
+# When unset, the internal default settings from 'settings/phrase_settings.php'
+# are used.
+NOMINATIM_PHRASE_CONFIG=
+
+# Configuration file for rank assignments.
+# When unset, the internal default settings from 'settings/address-levels.json'
+# are used.
+NOMINATIM_ADDRESS_LEVEL_CONFIG=
+
+# Configuration file for OSM data import.
+# This may either be the name of one of an internal style or point
+# to a file with a custom style.
+# Internal styles are: admin, street, address, full, extratags
+NOMINATIM_IMPORT_STYLE=extratags
+
+# Location of the flatnode file used by osm2pgsql to store node locations.
+# When unset, osm2pgsql stores the location in the PostgreSQL database. This
+# is especially useful for imports of larger areas, like continents or the
+# full planet. The file needs at least 70GB storage.
+NOMINATIM_FLATNODE_FILE=
+
+### Tablespace settings
+#
+# The following settings allow to move parts of the database tables into
+# different tablespaces. This is especially interesting if you have disks
+# with different speeds. When unset, the default tablespace is used.
+# Only has an effect during import.
+
+# Tablespace used for tables used when searching.
+NOMINATIM_TABLESPACE_SEARCH_DATA=
+# Tablespace used for indexes used when searching.
+NOMINATIM_TABLESPACE_SEARCH_INDEX=
+
+# Tablespace used for the OSM data cache tables. Used for import and update only.
+NOMINATIM_TABLESPACE_OSM_DATA=
+# Tablespace used for the OSM data cache indexes. Used for import and update only.
+NOMINATIM_TABLESPACE_OSM_INDEX=
+
+# Tablespace used for place import table. Used for import and update only.
+NOMINATIM_TABLESPACE_PLACE_DATA=
+# Tablespace used for place import indexes. Used for import and update only.
+NOMINATIM_TABLESPACE_PLACE_INDEX=
+
+# Tablespace for tables used during address computation. Used for import and update only.
+NOMINATIM_TABLESPACE_ADDRESS_DATA=
+# Tablespace for indexes used during address computation. Used for import and update only.
+NOMINATIM_TABLESPACE_ADDRESS_INDEX=
+
+# Tablespace for tables for auxilary data, e.g. TIGER data, postcodes.
+NOMINATIM_TABLESPACE_AUX_DATA=
+# Tablespace for indexes for auxilary data, e.g. TIGER data, postcodes.
+NOMINATIM_TABLESPACE_AUX_INDEX=
+
+
+### Replication settings
+#
+# The following settings control where and how updates for the database are
+# retrieved.
+#
+
+#
+# Base URL of replication service.
+# A replication service provides change files of OSM data at regular intervals.
+# These are used to keep the database up to date. Per default it points to
+# the minutely updates for the main OSM database. There are other services
+# geared towards larger update intervals or data extracts.
+# Changing this value requires to rerun 'update/php --init-updates'.
+NOMINATIM_REPLICATION_URL="https://planet.openstreetmap.org/replication/minute"
+
+# Maximum amount of data to download per batch.
+# Size is in MB.
+NOMINATIM_REPLICATION_MAX_DIFF=50
+
+# Publication interval of the replication service.
+# Determines when Nominatim will attempt again to download again a new
+# update. The time is computed from the publication date of the last diff
+# downloaded. Setting this to a slightly higher value than the actual
+# publication interval avoids unnecessary rechecks.
+NOMINATIM_REPLICATION_UPDATE_INTERVAL=75
+
+# Wait time to recheck for a pending update.
+# Time to wait after an expected update was not available on the server.
+NOMINATIM_REPLICATION_RECHECK_INTERVAL=60
+
+### API settings
+#
+# The following settings configure the API responses. You must rerun
+# setup.php --setup-website after changing any of them.
+
+# Send permissive CORS access headers.
+# When enabled, send CORS headers to allow access to everybody.
+NOMINATIM_CORS_NOACCESSCONTROL=yes
+
+# URL for static icon images.
+# Set this to the /mapicon directory of your nominatim-ui to enable returning
+# icon URLs with the results.
+NOMINATIM_MAPICON_URL=
+
+# Language to assume when no particular language is requested.
+# When unset, the local language (i.e. the name tag without suffix) will be used.
+NOMINATIM_DEFAULT_LANGUAGE=
+
+# Enable a special batch query mode.
+# This features is currently undocumented and potentially broken.
+NOMINATIM_SEARCH_BATCH_MODE=no
+
+# Threshold for searches by name only.
+# Threshold where the lookup strategy in the database is switched. If there
+# are less occurences of a tem than given, the search does the lookup only
+# against the name, otherwise it uses indexes for name and address.
+NOMINATIM_SEARCH_NAME_ONLY_THRESHOLD=500
+
+# Maximum number of OSM ids accepted by /lookup.
+NOMINATIM_LOOKUP_MAX_COUNT=50
+
+# Number of different geometry formats that may be queried in parallel.
+# Set to zero to disable polygon output.
+NOMINATIM_POLYGON_OUTPUT_MAX_TYPES=1
+
+### Log settings
+#
+# The following options allow to enable logging of API requests.
+# You must rerun setup.php --setup-website after changing any of them.
+#
+# Enable logging of requests into the DB.
+# The request will be logged into the new_query_log table.
+# You should set up a cron job that regularly clears out this table.
+NOMINATIM_LOG_DB=no
+
+# Enable logging of requests into a file.
+# To enable logging set this setting to the file to log to.
+NOMINATIM_LOG_FILE=
$$
LANGUAGE plpgsql STABLE;
+DROP TYPE IF EXISTS addressdata_place;
+CREATE TYPE addressdata_place AS (
+ place_id BIGINT,
+ country_code VARCHAR(2),
+ housenumber TEXT,
+ postcode TEXT,
+ class TEXT,
+ type TEXT,
+ name HSTORE,
+ address HSTORE,
+ centroid GEOMETRY
+);
-- Compute the list of address parts for the given place.
--
RETURNS setof addressline
AS $$
DECLARE
- place RECORD;
+ place addressdata_place;
location RECORD;
current_rank_address INTEGER;
location_isaddress BOOLEAN;
-- first query osmline (interpolation lines)
IF in_housenumber >= 0 THEN
SELECT parent_place_id as place_id, country_code,
- in_housenumber::text as housenumber, postcode,
+ in_housenumber as housenumber, postcode,
'place' as class, 'house' as type,
- null::hstore as name, null::hstore as address,
+ null as name, null as address,
ST_Centroid(linegeo) as centroid
INTO place
FROM location_property_osmline
--then query tiger data
-- %NOTIGERDATA% IF 0 THEN
IF place IS NULL AND in_housenumber >= 0 THEN
- SELECT parent_place_id as place_id, 'us'::varchar(2) as country_code,
- in_housenumber::text as housenumber, postcode,
+ SELECT parent_place_id as place_id, 'us' as country_code,
+ in_housenumber as housenumber, postcode,
'place' as class, 'house' as type,
- null::hstore as name, null::hstore as address,
+ null as name, null as address,
ST_Centroid(linegeo) as centroid
INTO place
FROM location_property_tiger
-- %NOAUXDATA% IF 0 THEN
IF place IS NULL THEN
- SELECT parent_place_id as place_id, 'us'::varchar(2) as country_code,
+ SELECT parent_place_id as place_id, 'us' as country_code,
housenumber, postcode,
'place' as class, 'house' as type,
- null::hstore as name, null::hstore as address,
+ null as name, null as address,
centroid
INTO place
FROM location_property_aux
SELECT parent_place_id as place_id, country_code,
null::text as housenumber, postcode,
'place' as class, 'postcode' as type,
- null::hstore as name, null::hstore as address,
- null::geometry as centroid
+ null as name, null as address,
+ null as centroid
INTO place
FROM location_postcode
WHERE place_id = in_place_id;
select coalesce(linked_place_id, place_id) as place_id, country_code,
housenumber, postcode,
class, type,
- null::hstore as name, address,
- null::geometry as centroid
+ null as name, address,
+ null as centroid
INTO place
FROM placex where place_id = in_place_id;
END IF;
self.keep_scenario_db = config['KEEP_TEST_DB']
self.code_coverage_path = config['PHPCOV']
self.code_coverage_id = 1
+ self.test_env = None
os.environ['NOMINATIM_SETTINGS'] = self.local_settings_file
self.template_db_done = False
return fn
def write_nominatim_config(self, dbname):
- f = open(self.local_settings_file, 'w')
- # https://secure.php.net/manual/en/ref.pdo-pgsql.connection.php
- f.write("<?php\n @define('CONST_Database_DSN', 'pgsql:dbname=%s%s%s%s%s');\n" %
- (dbname,
+ dsn = 'pgsql:dbname={}{}{}{}{}'.format(
+ dbname,
(';host=' + self.db_host) if self.db_host else '',
(';port=' + self.db_port) if self.db_port else '',
(';user=' + self.db_user) if self.db_user else '',
(';password=' + self.db_pass) if self.db_pass else ''
- ))
+ )
+ self.test_env = os.environ
+ self.test_env['NOMINATIM_DATABASE_DSN'] = dsn
+ self.test_env['NOMINATIM_FLATNODE_FILE'] = ''
+ self.test_env['NOMINATIM_IMPORT_STYLE'] = 'full'
+ self.test_env['NOMINATIM_USE_US_TIGER_DATA'] = 'yes'
+
+ f = open(self.local_settings_file, 'w')
+ # https://secure.php.net/manual/en/ref.pdo-pgsql.connection.php
+ f.write("<?php\n @define('CONST_Database_DSN', '{}');\n".format(dsn))
f.write("@define('CONST_Osm2pgsql_Flatnode_File', null);\n")
- f.write("@define('CONST_Import_Style', CONST_BasePath.'/settings/import-full.style');\n")
+ f.write("@define('CONST_Import_Style', CONST_DataDir.'/settings/import-full.style');\n")
+ f.write("@define('CONST_Use_US_Tiger_Data', true);\n")
f.close()
+
def cleanup(self):
try:
os.remove(self.local_settings_file)
cmd.extend(['--%s' % x for x in args])
for k, v in kwargs.items():
cmd.extend(('--' + k.replace('_', '-'), str(v)))
- proc = subprocess.Popen(cmd, cwd=self.build_dir,
+ proc = subprocess.Popen(cmd, cwd=self.build_dir, env=self.test_env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(outp, outerr) = proc.communicate()
outerr = outerr.decode('utf-8').replace('\\n', '\n')
(outp, err) = proc.communicate()
assert_equals (0, proc.returncode, "query.php failed with message: %s\noutput: %s" % (err, outp))
+ logger.debug("run_nominatim_script: %s\n%s\n" % (cmd, outp.decode('utf-8').replace('\\n', '\n')))
context.response = SearchResponse(outp.decode('utf-8'), 'json')
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/AddressDetails.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/AddressDetails.php');
class AddressDetailsTest extends \PHPUnit\Framework\TestCase
//
// 5) copy&paste into file. Add commas between records
//
- $json = file_get_contents(CONST_BasePath.'/test/php/fixtures/address_details_10_downing_street.json');
+ $json = file_get_contents(CONST_DataDir.'/test/php/fixtures/address_details_10_downing_street.json');
$data = json_decode($json, true);
$this->oDbStub = $this->getMockBuilder(\DB::class)
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/ClassTypes.php');
+require_once(CONST_LibDir.'/ClassTypes.php');
class ClassTypesTest extends \PHPUnit\Framework\TestCase
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/lib.php');
-require_once(CONST_BasePath.'/lib/DB.php');
+require_once(CONST_LibDir.'/lib.php');
+require_once(CONST_LibDir.'/DB.php');
// subclassing so we can set the protected connection variable
class NominatimSubClassedDB extends \Nominatim\DB
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/DatabaseError.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/DatabaseError.php');
class DatabaseErrorTest extends \PHPUnit\Framework\TestCase
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/DebugHtml.php');
+require_once(CONST_LibDir.'/DebugHtml.php');
class DebugTest extends \PHPUnit\Framework\TestCase
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/lib.php');
-require_once(CONST_BasePath.'/lib/ClassTypes.php');
+require_once(CONST_LibDir.'/lib.php');
+require_once(CONST_LibDir.'/ClassTypes.php');
class LibTest extends \PHPUnit\Framework\TestCase
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/output.php');
+require_once(CONST_LibDir.'/output.php');
class OutputTest extends \PHPUnit\Framework\TestCase
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/ParameterParser.php');
+require_once(CONST_LibDir.'/ParameterParser.php');
function userError($sError)
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/Phrase.php');
+require_once(CONST_LibDir.'/Phrase.php');
class TokensFullSet
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/SearchContext.php');
+require_once(CONST_LibDir.'/SearchContext.php');
class SearchContextTest extends \PHPUnit\Framework\TestCase
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/Shell.php');
+require_once(CONST_LibDir.'/Shell.php');
class ShellTest extends \PHPUnit\Framework\TestCase
{
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/DB.php');
-require_once(CONST_BasePath.'/lib/Status.php');
+require_once(CONST_LibDir.'/DB.php');
+require_once(CONST_LibDir.'/Status.php');
class StatusTest extends \PHPUnit\Framework\TestCase
namespace Nominatim;
-require_once(CONST_BasePath.'/lib/TokenList.php');
+require_once(CONST_LibDir.'/TokenList.php');
class TokenTest extends \PHPUnit\Framework\TestCase
<?php
- @define('CONST_BasePath', '../..');
+ @define('CONST_LibDir', '../../lib');
+ @define('CONST_DataDir', '../..');
+
@define('CONST_Debug', true);
@define('CONST_NoAccessControl', false);
-#!/usr/bin/python3
+#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
#
# This file is part of Nominatim.
<?php
-require_once(CONST_BasePath.'/lib/init-cmd.php');
+require_once(CONST_LibDir.'/init-cmd.php');
+
+loadSettings(getcwd());
$term_colors = array(
'green' => "\033[92m",
return !$oDB->tableExists('search_name');
}
+// Check (guess) if the setup.php included --drop
+function isNoUpdateInstallation()
+{
+ global $oDB;
+ return $oDB->tableExists('placex') && !$oDB->tableExists('planet_osm_rels') ;
+}
+
echo 'Checking database got created ... ';
if ($oDB->checkConnection()) {
echo <<< END
Hints:
* Is the database server started?
- * Check the CONST_Database_DSN variable in build/settings/local.php
+ * Check the NOMINATIM_DATABASE_DSN variable in your local .env
* Try connecting to the database with the same settings
END;
exit(1);
}
-echo 'Checking place table ... ';
-if ($oDB->tableExists('place')) {
- $print_success();
-} else {
- $print_fail();
- echo <<< END
- * The import didn't finish.
- Hints:
- * Check the output of the utils/setup.php you ran.
- Usually the osm2pgsql step failed. Check for errors related to
- * the file you imported not containing any places
- * harddrive full
- * out of memory (RAM)
- * osm2pgsql killed by other scripts, for consuming to much memory
-
-END;
- exit(1);
+if (!isNoUpdateInstallation()) {
+ echo 'Checking place table ... ';
+ if ($oDB->tableExists('place')) {
+ $print_success();
+ } else {
+ $print_fail();
+ echo <<< END
+ * The import didn't finish.
+ Hints:
+ * Check the output of the utils/setup.php you ran.
+ Usually the osm2pgsql step failed. Check for errors related to
+ * the file you imported not containing any places
+ * harddrive full
+ * out of memory (RAM)
+ * osm2pgsql killed by other scripts, for consuming to much memory
+
+ END;
+ exit(1);
+ }
}
-
echo 'Checking indexing status ... ';
$iUnindexed = $oDB->getOne('SELECT count(*) FROM placex WHERE indexed_status > 0');
if ($iUnindexed == 0) {
'idx_place_addressline_address_place_id',
'idx_placex_rank_search',
'idx_placex_rank_address',
- 'idx_placex_pendingsector',
'idx_placex_parent_place_id',
'idx_placex_geometry_reverse_lookuppolygon',
'idx_placex_geometry_reverse_placenode',
- 'idx_location_area_country_place_id',
'idx_osmline_parent_place_id',
'idx_osmline_parent_osm_id',
- 'idx_place_osm_unique',
'idx_postcode_id',
'idx_postcode_postcode'
);
'idx_search_name_centroid'
));
}
+if (!isNoUpdateInstallation()) {
+ $aExpectedIndices = array_merge($aExpectedIndices, array(
+ 'idx_placex_pendingsector',
+ 'idx_location_area_country_place_id',
+ 'idx_place_osm_unique',
+ ));
+}
foreach ($aExpectedIndices as $sExpectedIndex) {
echo "Checking index $sExpectedIndex ... ";
-if (CONST_Use_US_Tiger_Data) {
+if (getSettingBool('USE_US_TIGER_DATA')) {
echo 'Checking TIGER table exists ... ';
if ($oDB->tableExists('location_property_tiger')) {
$print_success();
<?php
-require_once(CONST_BasePath.'/lib/init-cmd.php');
+require_once(CONST_LibDir.'/init-cmd.php');
ini_set('memory_limit', '800M');
ini_set('display_errors', 'stderr');
array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
+ array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
);
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
-include(CONST_Phrase_Config);
+loadSettings($aCMDResult['project-dir'] ?? getcwd());
+setupHTTPProxy();
if (true) {
$sURL = 'https://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Country_Codes';
// from a running nominatim instance as CSV data
- require_once(CONST_BasePath.'/lib/init-cmd.php');
- require_once(CONST_BasePath.'/lib/ParameterParser.php');
+ require_once(CONST_LibDir.'/init-cmd.php');
+ require_once(CONST_LibDir.'/ParameterParser.php');
ini_set('memory_limit', '800M');
$aCMDOptions = array(
array('restrict-to-osm-node', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM node'),
array('restrict-to-osm-way', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM way'),
array('restrict-to-osm-relation', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM relation'),
+ array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
"\nAddress ranks: continent, country, state, county, city, suburb, street, path",
'Additional output types: postcode, placeid (placeid for each object)',
"\noutput-format must be a semicolon-separated list of address ranks. Multiple ranks",
);
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
+ loadSettings($aCMDResult['project-dir'] ?? getcwd());
+
$aRankmap = array(
'continent' => 1,
'country' => 4,
<?php
-require_once(CONST_BasePath.'/lib/init-cmd.php');
-require_once(CONST_BasePath.'/lib/Geocode.php');
-require_once(CONST_BasePath.'/lib/ParameterParser.php');
+require_once(CONST_LibDir.'/init-cmd.php');
+require_once(CONST_LibDir.'/Geocode.php');
+require_once(CONST_LibDir.'/ParameterParser.php');
ini_set('memory_limit', '800M');
$aCMDOptions
array('exclude_place_ids', '', 0, 1, 1, 1, 'string', 'Comma-separated list of place ids to exclude from results'),
array('featureType', '', 0, 1, 1, 1, 'string', 'Restrict results to certain features (country, state,city,settlement)'),
array('countrycodes', '', 0, 1, 1, 1, 'string', 'Comma-separated list of countries to restrict search to'),
- array('viewbox', '', 0, 1, 1, 1, 'string', 'Prefer results in given view box')
+ array('viewbox', '', 0, 1, 1, 1, 'string', 'Prefer results in given view box'),
+
+ array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
);
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
+loadSettings($aCMDResult['project-dir'] ?? getcwd());
+
+@define('CONST_Database_DSN', getSetting('DATABASE_DSN'));
+@define('CONST_Default_Language', getSetting('DEFAULT_LANGUAGE', false));
+@define('CONST_Log_DB', getSettingBool('LOG_DB'));
+@define('CONST_Log_File', getSetting('LOG_FILE', false));
+@define('CONST_Max_Word_Frequency', getSetting('MAX_WORD_FREQUENCY'));
+@define('CONST_NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
+@define('CONST_Places_Max_ID_count', getSetting('LOOKUP_MAX_COUNT'));
+@define('CONST_PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
+@define('CONST_Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
+@define('CONST_Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
+@define('CONST_Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
+@define('CONST_Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
+@define('CONST_Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
+@define('CONST_MapIcon_URL', getSetting('MAPICON_URL', false));
+
+
$oDB = new Nominatim\DB;
$oDB->connect();
<?php
-require_once(CONST_BasePath.'/lib/init-cmd.php');
-require_once(CONST_BasePath.'/lib/setup/SetupClass.php');
-require_once(CONST_BasePath.'/lib/setup_functions.php');
+require_once(CONST_LibDir.'/init-cmd.php');
+require_once(CONST_LibDir.'/setup/SetupClass.php');
+require_once(CONST_LibDir.'/setup_functions.php');
ini_set('memory_limit', '800M');
use Nominatim\Setup\SetupFunctions as SetupFunctions;
array('create-country-names', '', 0, 1, 0, 0, 'bool', 'Create default list of searchable country names'),
array('drop', '', 0, 1, 0, 0, 'bool', 'Drop tables needed for updates, making the database readonly (EXPERIMENTAL)'),
array('setup-website', '', 0, 1, 0, 0, 'bool', 'Used to compile environment variables for the website'),
+ array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
);
// $aCMDOptions passed to getCmdOpt by reference
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
+loadSettings($aCMDResult['project-dir'] ?? getcwd());
+setupHTTPProxy();
+
$bDidSomething = false;
//*******************************************************
if ($aCMDResult['import-tiger-data']) {
$bDidSomething = true;
- $oSetup->importTigerData();
+ $sTigerPath = getSetting('TIGER_DATA_PATH');
+ if (!$sTigerPath) {
+ $sTigerPath = CONST_DataDir.'/data/tiger';
+ }
+ $oSetup->importTigerData($sTigerPath);
}
if ($aCMDResult['calculate-postcodes'] || $aCMDResult['all']) {
<?php
-require_once(CONST_BasePath.'/lib/init-cmd.php');
+require_once(CONST_LibDir.'/init-cmd.php');
ini_set('memory_limit', '800M');
ini_set('display_errors', 'stderr');
array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('wiki-import', '', 0, 1, 0, 0, 'bool', 'Create import script for search phrases '),
+ array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
);
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
-include(CONST_Phrase_Config);
+loadSettings($aCMDResult['project-dir'] ?? getcwd());
+setupHTTPProxy();
+
+include(getSettingConfig('PHRASE_CONFIG', 'phrase_settings.php'));
if ($aCMDResult['wiki-import']) {
- $oNormalizer = Transliterator::createFromRules(CONST_Term_Normalization_Rules);
+ $oNormalizer = Transliterator::createFromRules(getSetting('TERM_NORMALIZATION'));
$aPairs = array();
- $sLanguageIn = CONST_Languages ? CONST_Languages :
- ('af,ar,br,ca,cs,de,en,es,et,eu,fa,fi,fr,gl,hr,hu,'.
- 'ia,is,it,ja,mk,nl,no,pl,ps,pt,ru,sk,sl,sv,uk,vi');
+ $sLanguageIn = getSetting(
+ 'LANGUAGES',
+ 'af,ar,br,ca,cs,de,en,es,et,eu,fa,fi,fr,gl,hr,hu,'.
+ 'ia,is,it,ja,mk,nl,no,pl,ps,pt,ru,sk,sl,sv,uk,vi'
+ );
foreach (explode(',', $sLanguageIn) as $sLanguage) {
$sURL = 'https://wiki.openstreetmap.org/wiki/Special:Export/Nominatim/Special_Phrases/'.strtoupper($sLanguage);
echo 'CREATE INDEX idx_placex_classtype ON placex (class, type);';
foreach ($aPairs as $aPair) {
- $sql_tablespace = CONST_Tablespace_Aux_Data ? ' TABLESPACE '.CONST_Tablespace_Aux_Data : '';
+ $sql_tablespace = getSetting('TABLESPACE_AUX_DATA');
+ if ($sql_tablespace) {
+ $sql_tablespace = ' TABLESPACE '.$sql_tablespace;
+ }
printf(
'CREATE TABLE place_classtype_%s_%s'
. ";\n",
pg_escape_string($aPair[0]),
pg_escape_string($aPair[1]),
- CONST_Database_Web_User
+ getSetting('DATABASE_WEBUSER')
);
}
<?php
-require_once(CONST_BasePath.'/lib/init-cmd.php');
-require_once(CONST_BasePath.'/lib/setup_functions.php');
-require_once(CONST_BasePath.'/lib/setup/SetupClass.php');
-require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
+require_once(CONST_LibDir.'/init-cmd.php');
+require_once(CONST_LibDir.'/setup_functions.php');
+require_once(CONST_LibDir.'/setup/SetupClass.php');
+require_once(CONST_LibDir.'/setup/AddressLevelParser.php');
ini_set('memory_limit', '800M');
array('recompute-word-counts', '', 0, 1, 0, 0, 'bool', 'Compute frequency of full-word search terms'),
array('update-address-levels', '', 0, 1, 0, 0, 'bool', 'Reimport address level configuration (EXPERT)'),
- array('recompute-importance', '', 0, 1, 0, 0, 'bool', 'Recompute place importances')
+ array('recompute-importance', '', 0, 1, 0, 0, 'bool', 'Recompute place importances'),
+
+ array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
);
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
+loadSettings($aCMDResult['project-dir'] ?? getcwd());
+setupHTTPProxy();
+
if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
$oDB->connect();
$fPostgresVersion = $oDB->getPostgresVersion();
-$aDSNInfo = Nominatim\DB::parseDSN(CONST_Database_DSN);
+$aDSNInfo = Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
// cache memory to be used by osm2pgsql, should not be more than the available memory
echo "WARNING: resetting cache memory to $iCacheMemory\n";
}
-$oOsm2pgsqlCmd = (new \Nominatim\Shell(CONST_Osm2pgsql_Binary))
+$oOsm2pgsqlCmd = (new \Nominatim\Shell(getOsm2pgsqlBinary()))
->addParams('--hstore')
->addParams('--latlong')
->addParams('--append')
->addParams('--number-processes', 1)
->addParams('--cache', $iCacheMemory)
->addParams('--output', 'gazetteer')
- ->addParams('--style', CONST_Import_Style)
+ ->addParams('--style', getImportStyle())
->addParams('--database', $aDSNInfo['database'])
->addParams('--port', $aDSNInfo['port']);
if (isset($aDSNInfo['password']) && $aDSNInfo['password']) {
$oOsm2pgsqlCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
}
-if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
- $oOsm2pgsqlCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
+if (getSetting('FLATNODE_FILE')) {
+ $oOsm2pgsqlCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
}
if ($fPostgresVersion >= 11.0) {
$oOsm2pgsqlCmd->addEnvPair(
}
-$oIndexCmd = (new \Nominatim\Shell(CONST_BasePath.'/nominatim/nominatim.py'))
+$oIndexCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
->addParams('--database', $aDSNInfo['database'])
->addParams('--port', $aDSNInfo['port'])
->addParams('--threads', $aResult['index-instances']);
$oIndexCmd->addEnvPair('PGPASSWORD', $aDSNInfo['password']);
}
+$sPyosmiumBin = getSetting('PYOSMIUM_BINARY');
+$sBaseURL = getSetting('REPLICATION_URL');
+
if ($aResult['init-updates']) {
// sanity check that the replication URL is correct
- $sBaseState = file_get_contents(CONST_Replication_Url.'/state.txt');
+ $sBaseState = file_get_contents($sBaseURL.'/state.txt');
if ($sBaseState === false) {
echo "\nCannot find state.txt file at the configured replication URL.\n";
echo "Does the URL point to a directory containing OSM update data?\n\n";
fail('replication URL not reachable.');
}
// sanity check for pyosmium-get-changes
- if (!CONST_Pyosmium_Binary) {
- echo "\nCONST_Pyosmium_Binary not configured.\n";
+ if (!$sPyosmiumBin) {
+ echo "\nNOMINATIM_PYOSMIUM_BINARY not configured.\n";
echo "You need to install pyosmium and set up the path to pyosmium-get-changes\n";
- echo "in your local settings file.\n\n";
- fail('CONST_Pyosmium_Binary not configured');
+ echo "in your local .env file.\n\n";
+ fail('NOMINATIM_PYOSMIUM_BINARY not configured');
}
$aOutput = 0;
- $oCMD = new \Nominatim\Shell(CONST_Pyosmium_Binary, '--help');
+ $oCMD = new \Nominatim\Shell($sPyosmiumBin, '--help');
exec($oCMD->escapedCmd(), $aOutput, $iRet);
if ($iRet != 0) {
echo "Cannot execute pyosmium-get-changes.\n";
echo "Make sure you have pyosmium installed correctly\n";
- echo "and have set up CONST_Pyosmium_Binary to point to pyosmium-get-changes.\n";
+ echo "and have set up NOMINATIM_PYOSMIUM_BINARY to point to pyosmium-get-changes.\n";
fail('pyosmium-get-changes not found or not usable');
}
// get the appropriate state id
$aOutput = 0;
- $oCMD = (new \Nominatim\Shell(CONST_Pyosmium_Binary))
+ $oCMD = (new \Nominatim\Shell($sPyosmiumBin))
->addParams('--start-date', $sWindBack)
- ->addParams('--server', CONST_Replication_Url);
+ ->addParams('--server', $sBaseURL);
exec($oCMD->escapedCmd(), $aOutput, $iRet);
if ($iRet != 0 || $aOutput[0] == 'None') {
fail('Updates not set up. Please run ./utils/update.php --init-updates.');
}
- $oCmd = (new \Nominatim\Shell(CONST_BasePath.'/utils/check_server_for_updates.py'))
- ->addParams(CONST_Replication_Url)
+ $oCmd = (new \Nominatim\Shell(CONST_BinDir.'/check_server_for_updates.py'))
+ ->addParams($sBaseURL)
->addParams($aLastState['sequence_id']);
$iRet = $oCmd->run();
if ($aResult['calculate-postcodes']) {
info('Update postcodes centroids');
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/update-postcodes.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/update-postcodes.sql');
runSQLScript($sTemplate, true, true);
}
-$sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
+$sTemporaryFile = CONST_InstallDir.'/osmosischange.osc';
$bHaveDiff = false;
$bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
$sContentURL = '';
if ($aResult['recompute-word-counts']) {
info('Recompute frequency of full-word search terms');
- $sTemplate = file_get_contents(CONST_BasePath.'/sql/words_from_search_name.sql');
+ $sTemplate = file_get_contents(CONST_DataDir.'/sql/words_from_search_name.sql');
runSQLScript($sTemplate, true, true);
}
}
if ($aResult['update-address-levels']) {
- echo 'Updating address levels from '.CONST_Address_Level_Config.".\n";
- $oAlParser = new \Nominatim\Setup\AddressLevelParser(CONST_Address_Level_Config);
+ $sAddressLevelConfig = getSettingConfig('ADDRESS_LEVEL_CONFIG', 'address-levels.json');
+ echo 'Updating address levels from '.$sAddressLevelConfig.".\n";
+ $oAlParser = new \Nominatim\Setup\AddressLevelParser($sAddressLevelConfig);
$oAlParser->createTable($oDB, 'address_levels');
}
if ($aResult['import-osmosis'] || $aResult['import-osmosis-all']) {
//
- if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
+ if (strpos($sBaseURL, 'download.geofabrik.de') !== false && getSetting('REPLICATION_UPDATE_INTERVAL') < 86400) {
fail('Error: Update interval too low for download.geofabrik.de. ' .
"Please check install documentation (https://nominatim.org/release-docs/latest/admin/Import-and-Update#setting-up-the-update-process)\n");
}
- $sImportFile = CONST_InstallPath.'/osmosischange.osc';
+ $sImportFile = CONST_InstallDir.'/osmosischange.osc';
- $oCMDDownload = (new \Nominatim\Shell(CONST_Pyosmium_Binary))
- ->addParams('--server', CONST_Replication_Url)
+ $oCMDDownload = (new \Nominatim\Shell($sPyosmiumBin))
+ ->addParams('--server', $sBaseURL)
->addParams('--outfile', $sImportFile)
- ->addParams('--size', CONST_Replication_Max_Diff_size);
+ ->addParams('--size', getSetting('REPLICATION_MAX_DIFF'));
$oCMDImport = (clone $oOsm2pgsqlCmd)->addParams($sImportFile);
if ($aLastState['indexed']) {
// Sleep if the update interval has not yet been reached.
- $fNextUpdate = $aLastState['unix_ts'] + CONST_Replication_Update_Interval;
+ $fNextUpdate = $aLastState['unix_ts'] + getSetting('REPLICATION_UPDATE_INTERVAL');
if ($fNextUpdate > $fStartTime) {
$iSleepTime = $fNextUpdate - $fStartTime;
echo "Waiting for next update for $iSleepTime sec.";
exec($oCMD->escapedCmd(), $aOutput, $iResult);
if ($iResult == 3) {
- echo 'No new updates. Sleeping for '.CONST_Replication_Recheck_Interval." sec.\n";
- sleep(CONST_Replication_Recheck_Interval);
+ $sSleep = getSetting('REPLICATION_RECHECK_INTERVAL');
+ echo 'No new updates. Sleeping for '.$sSleep." sec.\n";
+ sleep($sSleep);
} elseif ($iResult != 0) {
echo 'ERROR: updates failed.';
exit($iResult);
// get the newest object from the diff file
$sBatchEnd = 0;
$iRet = 0;
- $oCMD = new \Nominatim\Shell(CONST_BasePath.'/utils/osm_file_date.py', $sImportFile);
+ $oCMD = new \Nominatim\Shell(CONST_BinDir.'/osm_file_date.py', $sImportFile);
exec($oCMD->escapedCmd(), $sBatchEnd, $iRet);
if ($iRet == 5) {
echo "Diff file is empty. skipping import.\n";
<?php
-require_once(CONST_BasePath.'/lib/init-cmd.php');
+require_once(CONST_LibDir.'/init-cmd.php');
+require_once(CONST_LibDir.'/log.php');
+require_once(CONST_LibDir.'/Geocode.php');
+require_once(CONST_LibDir.'/PlaceLookup.php');
+require_once(CONST_LibDir.'/ReverseGeocode.php');
+
ini_set('memory_limit', '800M');
$aCMDOptions = array(
array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
array('reverse-only', '', 0, 1, 0, 0, 'bool', 'Warm reverse only'),
array('search-only', '', 0, 1, 0, 0, 'bool', 'Warm search only'),
+ array('project-dir', '', 0, 1, 1, 1, 'realpath', 'Base directory of the Nominatim installation (default: .)'),
);
getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
-require_once(CONST_BasePath.'/lib/log.php');
-require_once(CONST_BasePath.'/lib/Geocode.php');
-require_once(CONST_BasePath.'/lib/PlaceLookup.php');
-require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
+loadSettings($aCMDResult['project-dir'] ?? getcwd());
$oDB = new Nominatim\DB();
$oDB->connect();
# Installing the Required Software
# ================================
#
+# !!! caution
+# These instructions are currently broken because they do not
+# include installation of the required PHP library symfony-dotenv.
+#
# These instructions expect that you have a freshly installed CentOS version 7.
# Make sure all packages are up-to-date by running:
#
# the name of your webserver user:
#DOCS:```sh
-tee settings/local.php << EOF
-<?php
- @define('CONST_Database_Web_User', 'apache');
-EOF
+echo NOMINATIM_DATABASE_WEBUSER="apache" | tee .env
#DOCS:```
# Installing the Required Software
# ================================
#
+# !!! caution
+# These instructions are currently broken because they do not
+# include installation of the required PHP library symfony-dotenv.
+#
# These instructions expect that you have a freshly installed CentOS version 8.
# Make sure all packages are up-to-date by running:
#
# Now you can install all packages needed for Nominatim:
#DOCS: :::sh
- sudo dnf --enablerepo=PowerTools install -y postgresql12-server \
+ sudo dnf --enablerepo=powertools install -y postgresql12-server \
postgresql12-contrib postgresql12-devel postgis30_12 \
wget git cmake make gcc gcc-c++ libtool policycoreutils-python-utils \
llvm-toolset ccache clang-tools-extra \
# the name of your webserver user:
#DOCS:```sh
-tee settings/local.php << EOF
-<?php
- @define('CONST_Database_Web_User', 'apache');
-EOF
+echo NOMINATIM_DATABASE_WEBUSER="apache" | tee .env
#DOCS:```
libbz2-dev libpq-dev libproj-dev \
postgresql-server-dev-10 postgresql-10-postgis-2.4 \
postgresql-contrib-10 postgresql-10-postgis-scripts \
- php php-pgsql php-intl \
+ php php-pgsql php-intl php-symfony-dotenv \
python3-psycopg2 git
libbz2-dev libpq-dev libproj-dev \
postgresql-server-dev-12 postgresql-12-postgis-3 \
postgresql-contrib-12 postgresql-12-postgis-3-scripts \
- php php-pgsql php-intl \
+ php php-pgsql php-intl php-symfony-dotenv \
python3-psycopg2 git
#
<?php
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/log.php');
-require_once(CONST_BasePath.'/lib/output.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/log.php');
+require_once(CONST_LibDir.'/output.php');
ini_set('memory_limit', '200M');
$oParams = new Nominatim\ParameterParser();
$sOutputFormat = $oParams->getSet('format', array('json'), 'json');
set_exception_handler_by_format($sOutputFormat);
-$oDB = new Nominatim\DB();
+$oDB = new Nominatim\DB(CONST_Database_DSN);
$oDB->connect();
$sSQL = 'select placex.place_id, country_code,';
<?php
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/log.php');
-require_once(CONST_BasePath.'/lib/output.php');
-require_once(CONST_BasePath.'/lib/AddressDetails.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/log.php');
+require_once(CONST_LibDir.'/output.php');
+require_once(CONST_LibDir.'/AddressDetails.php');
ini_set('memory_limit', '200M');
$oParams = new Nominatim\ParameterParser();
$bGroupHierarchy = $oParams->getBool('group_hierarchy', false);
$bIncludePolygonAsGeoJSON = $oParams->getBool('polygon_geojson', false);
-$oDB = new Nominatim\DB();
+$oDB = new Nominatim\DB(CONST_Database_DSN);
$oDB->connect();
$sLanguagePrefArraySQL = $oDB->getArraySQL($oDB->getDBQuotedList($aLangPrefOrder));
$aPointDetails['error_x'] = 0;
$aPointDetails['error_y'] = 0;
}
- include(CONST_BasePath.'/lib/template/details-error-'.$sOutputFormat.'.php');
+ include(CONST_LibDir.'/template/details-error-'.$sOutputFormat.'.php');
exit;
}
}
logEnd($oDB, $hLog, 1);
-include(CONST_BasePath.'/lib/template/details-'.$sOutputFormat.'.php');
+include(CONST_LibDir.'/template/details-'.$sOutputFormat.'.php');
<?php
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/log.php');
-require_once(CONST_BasePath.'/lib/PlaceLookup.php');
-require_once(CONST_BasePath.'/lib/output.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/log.php');
+require_once(CONST_LibDir.'/PlaceLookup.php');
+require_once(CONST_LibDir.'/output.php');
ini_set('memory_limit', '200M');
$oParams = new Nominatim\ParameterParser();
// Preferred language
$aLangPrefOrder = $oParams->getPreferredLanguages();
-$oDB = new Nominatim\DB();
+$oDB = new Nominatim\DB(CONST_Database_DSN);
$oDB->connect();
$hLog = logStart($oDB, 'place', $_SERVER['QUERY_STRING'], $aLangPrefOrder);
logEnd($oDB, $hLog, 1);
$sOutputTemplate = ($sOutputFormat == 'jsonv2') ? 'json' : $sOutputFormat;
-include(CONST_BasePath.'/lib/template/search-'.$sOutputTemplate.'.php');
+include(CONST_LibDir.'/template/search-'.$sOutputTemplate.'.php');
<?php
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/log.php');
-require_once(CONST_BasePath.'/lib/output.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/log.php');
+require_once(CONST_LibDir.'/output.php');
ini_set('memory_limit', '200M');
$oParams = new Nominatim\ParameterParser();
$bReduced = $oParams->getBool('reduced', false);
$sClass = $oParams->getString('class', false);
-$oDB = new Nominatim\DB();
+$oDB = new Nominatim\DB(CONST_Database_DSN);
$oDB->connect();
$iTotalBroken = (int) $oDB->getOne('SELECT count(*) FROM import_polygon_error');
<?php
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/log.php');
-require_once(CONST_BasePath.'/lib/PlaceLookup.php');
-require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
-require_once(CONST_BasePath.'/lib/output.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/log.php');
+require_once(CONST_LibDir.'/PlaceLookup.php');
+require_once(CONST_LibDir.'/ReverseGeocode.php');
+require_once(CONST_LibDir.'/output.php');
ini_set('memory_limit', '200M');
$oParams = new Nominatim\ParameterParser();
// Preferred language
$aLangPrefOrder = $oParams->getPreferredLanguages();
-$oDB = new Nominatim\DB();
+$oDB = new Nominatim\DB(CONST_Database_DSN);
$oDB->connect();
$hLog = logStart($oDB, 'reverse', $_SERVER['QUERY_STRING'], $aLangPrefOrder);
}
$sOutputTemplate = ($sOutputFormat == 'jsonv2') ? 'json' : $sOutputFormat;
-include(CONST_BasePath.'/lib/template/address-'.$sOutputTemplate.'.php');
+include(CONST_LibDir.'/template/address-'.$sOutputTemplate.'.php');
<?php
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/log.php');
-require_once(CONST_BasePath.'/lib/Geocode.php');
-require_once(CONST_BasePath.'/lib/output.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/log.php');
+require_once(CONST_LibDir.'/Geocode.php');
+require_once(CONST_LibDir.'/output.php');
ini_set('memory_limit', '200M');
-$oDB = new Nominatim\DB();
+$oDB = new Nominatim\DB(CONST_Database_DSN);
$oDB->connect();
$oParams = new Nominatim\ParameterParser();
$aLangPrefOrder = $oParams->getPreferredLanguages();
$oGeocode->setLanguagePreference($aLangPrefOrder);
-if (CONST_Search_ReversePlanForAll
- || isset($aLangPrefOrder['name:de'])
- || isset($aLangPrefOrder['name:ru'])
- || isset($aLangPrefOrder['name:ja'])
- || isset($aLangPrefOrder['name:pl'])
-) {
- $oGeocode->setReverseInPlan(true);
-}
-
// Format for output
$sOutputFormat = $oParams->getSet('format', array('xml', 'json', 'jsonv2', 'geojson', 'geocodejson'), 'jsonv2');
set_exception_handler_by_format($sOutputFormat);
$aSearchResults = $oBatchGeocode->lookup();
$aBatchResults[] = $aSearchResults;
}
- include(CONST_BasePath.'/lib/template/search-batch-json.php');
+ include(CONST_LibDir.'/template/search-batch-json.php');
exit;
}
if (CONST_Debug) exit;
$sOutputTemplate = ($sOutputFormat == 'jsonv2') ? 'json' : $sOutputFormat;
-include(CONST_BasePath.'/lib/template/search-'.$sOutputTemplate.'.php');
+include(CONST_LibDir.'/template/search-'.$sOutputTemplate.'.php');
<?php
-require_once(CONST_BasePath.'/lib/init-website.php');
-require_once(CONST_BasePath.'/lib/ParameterParser.php');
-require_once(CONST_BasePath.'/lib/Status.php');
+require_once(CONST_LibDir.'/init-website.php');
+require_once(CONST_LibDir.'/ParameterParser.php');
+require_once(CONST_LibDir.'/Status.php');
$oParams = new Nominatim\ParameterParser();
$sOutputFormat = $oParams->getSet('format', array('text', 'json'), 'text');
-$oDB = new Nominatim\DB();
+$oDB = new Nominatim\DB(CONST_Database_DSN);
if ($sOutputFormat == 'json') {
header('content-type: application/json; charset=UTF-8');