2 Helper functions for executing external programs.
6 import urllib.request as urlrequest
7 from urllib.parse import urlencode
9 from ..version import NOMINATIM_VERSION
11 LOG = logging.getLogger()
13 def run_legacy_script(script, *args, nominatim_env=None, throw_on_fail=False):
14 """ Run a Nominatim PHP script with the given arguments.
16 Returns the exit code of the script. If `throw_on_fail` is True
17 then throw a `CalledProcessError` on a non-zero exit.
19 cmd = ['/usr/bin/env', 'php', '-Cq',
20 nominatim_env.phplib_dir / 'admin' / script]
21 cmd.extend([str(a) for a in args])
23 env = nominatim_env.config.get_os_env()
24 env['NOMINATIM_DATADIR'] = str(nominatim_env.data_dir)
25 env['NOMINATIM_BINDIR'] = str(nominatim_env.data_dir / 'utils')
26 if not env['NOMINATIM_DATABASE_MODULE_PATH']:
27 env['NOMINATIM_DATABASE_MODULE_PATH'] = nominatim_env.module_dir
28 if not env['NOMINATIM_OSM2PGSQL_BINARY']:
29 env['NOMINATIM_OSM2PGSQL_BINARY'] = nominatim_env.osm2pgsql_path
31 proc = subprocess.run(cmd, cwd=str(nominatim_env.project_dir), env=env,
34 return proc.returncode
36 def run_api_script(endpoint, project_dir, extra_env=None, phpcgi_bin=None,
38 """ Execute a Nominiatim API function.
40 The function needs a project directory that contains the website
41 directory with the scripts to be executed. The scripts will be run
42 using php_cgi. Query parameters can be added as named arguments.
44 Returns the exit code of the script.
46 log = logging.getLogger()
47 webdir = str(project_dir / 'website')
48 query_string = urlencode(params or {})
50 env = dict(QUERY_STRING=query_string,
51 SCRIPT_NAME='/{}.php'.format(endpoint),
52 REQUEST_URI='/{}.php?{}'.format(endpoint, query_string),
53 CONTEXT_DOCUMENT_ROOT=webdir,
54 SCRIPT_FILENAME='{}/{}.php'.format(webdir, endpoint),
55 HTTP_HOST='localhost',
56 HTTP_USER_AGENT='nominatim-tool',
57 REMOTE_ADDR='0.0.0.0',
60 SERVER_PROTOCOL='HTTP/1.1',
61 GATEWAY_INTERFACE='CGI/1.1',
62 REDIRECT_STATUS='CGI')
67 if phpcgi_bin is None:
68 cmd = ['/usr/bin/env', 'php-cgi']
70 cmd = [str(phpcgi_bin)]
72 proc = subprocess.run(cmd, cwd=str(project_dir), env=env, capture_output=True,
75 if proc.returncode != 0 or proc.stderr:
77 log.error(proc.stderr.decode('utf-8').replace('\\n', '\n'))
79 log.error(proc.stdout.decode('utf-8').replace('\\n', '\n'))
80 return proc.returncode or 1
82 result = proc.stdout.decode('utf-8')
83 content_start = result.find('\r\n\r\n')
85 print(result[content_start + 4:].replace('\\n', '\n'))
91 """ Get the contents from the given URL and return it as a UTF-8 string.
93 headers = {"User-Agent" : "Nominatim/" + NOMINATIM_VERSION}
96 with urlrequest.urlopen(urlrequest.Request(url, headers=headers)) as response:
97 return response.read().decode('utf-8')
99 LOG.fatal('Failed to load URL: %s', url)