23#include "qgsversion.h"
46#include <QDomDocument>
47#include <QNetworkDiskCache>
49#include <QElapsedTimer>
52#include <fcgi_stdio.h>
60QString *QgsServer::sConfigFilePath =
nullptr;
64bool QgsServer::sInitialized =
false;
73 if ( !qobject_cast<QgsApplication *>( qApp ) )
75 qFatal(
"A QgsApplication must exist before a QgsServer instance can be created." );
82QFileInfo QgsServer::defaultAdminSLD()
84 return QFileInfo( QStringLiteral(
"admin.sld" ) );
87void QgsServer::setupNetworkAccessManager()
89 const QSettings settings;
91 QNetworkDiskCache *cache =
new QNetworkDiskCache(
nullptr );
92 const QString cacheDirectory = sSettings()->cacheDirectory();
93 cache->setCacheDirectory( cacheDirectory );
94 qint64 cacheSize = sSettings()->cacheSize();
95 cache->setMaximumCacheSize( cacheSize );
98 nam->setCache( cache );
101QFileInfo QgsServer::defaultProjectFile()
103 const QDir currentDir;
104 fprintf( FCGI_stderr,
"current directory: %s\n", currentDir.absolutePath().toUtf8().constData() );
105 QStringList nameFilterList;
106 nameFilterList << QStringLiteral(
"*.qgs" )
107 << QStringLiteral(
"*.qgz" );
108 const QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name );
109 for (
int x = 0; x < projectFiles.size(); x++ )
113 if ( projectFiles.isEmpty() )
117 return projectFiles.at( 0 );
120void QgsServer::printRequestParameters(
const QMap< QString, QString> ¶meterMap,
Qgis::MessageLevel logLevel )
127 QMap< QString, QString>::const_iterator pIt = parameterMap.constBegin();
128 for ( ; pIt != parameterMap.constEnd(); ++pIt )
134QString QgsServer::configPath(
const QString &defaultConfigPath,
const QString &configPath )
136 QString cfPath( defaultConfigPath );
137 const QString projectFile = sSettings()->projectFile();
138 if ( !projectFile.isEmpty() )
140 cfPath = projectFile;
141 QgsDebugMsgLevel( QStringLiteral(
"QGIS_PROJECT_FILE:%1" ).arg( cfPath ), 2 );
145 if ( configPath.isEmpty() )
148 if ( getenv(
"QGIS_PROJECT_FILE" ) )
150 cfPath = getenv(
"QGIS_PROJECT_FILE" );
153 else if ( ! defaultConfigPath.isEmpty() )
167void QgsServer::initLocale()
170 if ( ! sSettings()->overrideSystemLocale().isEmpty() )
172 QLocale::setDefault( QLocale( sSettings()->overrideSystemLocale() ) );
175 QLocale currentLocale;
176 if ( sSettings()->showGroupSeparator() )
178 currentLocale.setNumberOptions( currentLocale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator );
182 currentLocale.setNumberOptions( currentLocale.numberOptions() |= QLocale::NumberOption::OmitGroupSeparator );
184 QLocale::setDefault( currentLocale );
187bool QgsServer::init()
203#if defined(SERVER_SKIP_ECW)
216 if ( ! sSettings()->logFile().isEmpty() )
220 else if ( sSettings()->logStderr() )
247 gridMessage.append( QStringLiteral(
"This transformation requires the grid file '%1', which is not available for use on the system.\n" ).arg( grid.
shortName ) );
270 gridMessage.append( QStringLiteral(
"This transformation requires the grid file '%1', which is not available for use on the system.\n" ).arg( grid.
shortName ) );
271 if ( !grid.
url.isEmpty() )
275 gridMessage.append( QStringLiteral(
"This grid is part of the '%1' package, available for download from %2.\n" ).arg( grid.
packageName, grid.
url ) );
279 gridMessage.append( QStringLiteral(
"This grid is available for download from %1.\n" ).arg( grid.
url ) );
285 QString accuracyMessage;
287 accuracyMessage = QStringLiteral(
"Current transform '%1' has an accuracy of %2 meters, while the preferred transformation '%3' has accuracy %4 meters.\n" ).arg( availableOperation.
name )
288 .arg( availableOperation.
accuracy ).arg( preferredOperation.
name ).arg( preferredOperation.
accuracy );
289 else if ( preferredOperation.
accuracy >= 0 )
290 accuracyMessage = QStringLiteral(
"Current transform '%1' has an unknown accuracy, while the preferred transformation '%2' has accuracy %3 meters.\n" )
291 .arg( availableOperation.
name, preferredOperation.
name )
292 .arg( preferredOperation.
accuracy );
294 const QString longMessage = QStringLiteral(
"The preferred transform between '%1' and '%2' is not available for use on the system.\n" ).arg( sourceCrs.
userFriendlyIdentifier(),
296 + gridMessage + accuracyMessage;
304 const QString longMessage = QStringLiteral(
"No transform is available between %1 and %2: %3" )
315 sSettings()->logSummary();
317 setupNetworkAccessManager();
318 QDomImplementation::setInvalidDataPolicy( QDomImplementation::DropInvalidChars );
338 QString defaultConfigFilePath;
339 const QFileInfo projectFileInfo = defaultProjectFile();
340 if ( projectFileInfo.exists() )
342 defaultConfigFilePath = projectFileInfo.absoluteFilePath();
347 const QFileInfo adminSLDFileInfo = defaultAdminSLD();
348 if ( adminSLDFileInfo.exists() )
350 defaultConfigFilePath = adminSLDFileInfo.absoluteFilePath();
354 sConfigFilePath =
new QString( defaultConfigFilePath );
368 sServiceRegistry->
init( modulePath, sServerInterface );
386 qunsetenv( var.toUtf8().data() );
390 qputenv( var.toUtf8().data(), val.toUtf8() );
392 sSettings()->load( var );
402 qApp->processEvents();
408#ifdef HAVE_SERVER_PYTHON_PLUGINS
410 if ( accessControls )
443 const QString configFilePath = configPath( *sConfigFilePath, request.
serverParameters().
map() );
455 responseDecorator.
start();
460 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
470 printRequestParameters( params.
toMap(), logLevel );
475 const QString configFilePath = configPath( *sConfigFilePath, params.
map() );
478 if ( ! configFilePath.isEmpty() )
499 responseDecorator.
ready();
519 throw QgsServerException( QStringLiteral(
"Project file error. For OWS services: please provide a SERVICE and a MAP parameter pointing to a valid QGIS project file" ) );
522 if ( ! params.
fileName().isEmpty() )
524 const QString value = QString(
"attachment; filename=\"%1\"" ).arg( params.
fileName() );
525 requestHandler.
setResponseHeader( QStringLiteral(
"Content-Disposition" ), value );
537 QStringLiteral(
"Service unknown or unsupported. Current supported services (case-sensitive): WMS WFS WCS WMTS SampleService, or use a WFS3 (OGC API Features) endpoint" ) );
543 responseDecorator.
write( ex );
550 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
559 responseDecorator.
finish();
564 response.
sendError( 500, QStringLiteral(
"Internal Server Error" ) );
576 if ( sSettings->logProfile() )
578 std::function <void(
const QModelIndex &,
int )> profileFormatter;
579 profileFormatter = [ &profileFormatter ](
const QModelIndex & idx,
int level )
582 .arg( level > 0 ? QString().fill(
'-', level ) +
' ' : QString() )
590 profileFormatter( subIdx, level + 1 );
598 profileFormatter( idx, 0 );
614#ifdef HAVE_SERVER_PYTHON_PLUGINS
615void QgsServer::initPython()
@ ShortString
A heavily abbreviated string, for use when a compact representation is required.
MessageLevel
Level for messages This will be used both for message log and message bar in application.
@ Warning
Warning message.
@ Critical
Critical/error message.
@ Info
Information message.
A helper class that centralizes restrictions given by all the access control filter plugins.
void unresolveFilterFeatures()
Clear expression's cache computed from resolveFilterFeatures
static void skipGdalDriver(const QString &driver)
Sets the GDAL_SKIP environment variable to include the specified driver and then calls GDALDriverMana...
static QString pluginPath()
Returns the path to the application plugin directory.
static bool createDatabase(QString *errorMessage=nullptr)
initialize qgis.db
static void init(QString profileFolder=QString())
This method initializes paths etc for QGIS.
static QString pkgDataPath()
Returns the common root path of all application data directories.
static QString libexecPath()
Returns the path with utility executables (help viewer, crssync, ...)
static QStringList svgPaths()
Returns the paths to svg directories.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
static const char * QGIS_APPLICATION_NAME
static const char * QGIS_ORGANIZATION_DOMAIN
static QString prefixPath()
Returns the path to the application prefix directory.
static const char * QGIS_ORGANIZATION_NAME
static QString qgisAuthDatabaseUri()
Returns the URI to the user authentication database.
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
static QString qgisUserDatabaseFilePath()
Returns the path to the user qgis.db file.
void setup(const QString &pluginPath=QString(), const QString &authDatabasePath=QString())
Sets up the authentication manager configuration.
A cache for capabilities xml documents (by configuration file path)
void removeCapabilitiesDocument(const QString &path)
Removes capabilities document.
static QgsConfigCache * instance()
Returns the current instance.
static void initialize(QgsServerSettings *settings)
Initialize from settings.
void projectRemovedFromCache(const QString &path)
Emitted whenever a project is removed from the cache.
const QgsProject * project(const QString &path, const QgsServerSettings *settings=nullptr)
If the project is not cached yet, then the project is read from the path.
This class represents a coordinate reference system (CRS).
QString userFriendlyIdentifier(Qgis::CrsIdentifierType type=Qgis::CrsIdentifierType::MediumString) const
Returns a user friendly identifier for the CRS.
Defines a QGIS exception class.
Class defining decorator for calling filter's hooks.
void start()
Call filters requestReady() method.
void finish() override
Finish the response, ending the transaction.
void ready()
Call filters projectReady() method.
static bool loadStandardTestFonts(const QStringList &loadstyles)
Loads standard test fonts from filesystem or qrc resource.
Exception class for WMS service exceptions (for compatibility only).
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
network access manager for QGIS
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
Exception base class for service exceptions.
QString message() const
Returns the exception message.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
static void setInstance(QgsProject *project)
Set the current project singleton instance to project.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
This class is an interface hiding the details of reading input and writing output from/to a wms reque...
bool exceptionRaised() const
Pointer to last raised exception.
void parseInput()
Parses the input and creates a request neutral Parameter/Value map.
void setServiceException(const QgsServerException &ex)
Allow plugins to return a QgsMapServiceException.
void setResponseHeader(const QString &name, const QString &value)
Sets an HTTP response header.
@ Elapsed
Node elapsed time.
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const override
int rowCount(const QModelIndex &parent=QModelIndex()) const override
void clear(const QString &group="startup")
clear Clear all profile data.
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
Scoped object for logging of the runtime for a single operation or group of operations.
The QgsServerApiContext class encapsulates the resources for a particular client request: the request...
Server generic API endpoint abstract base class.
virtual void executeRequest(const QgsServerApiContext &context) const =0
Executes a request by passing the given context to the API handlers.
virtual const QString rootPath() const =0
Returns the root path for the API.
Exception base class for server exceptions.
virtual QByteArray formatResponse(QString &responseFormat) const
Formats the exception for sending to client.
Interfaces exposed by QGIS Server and made available to plugins.
QgsServerSettings * serverSettings() override
Returns the server settings.
void setRequestHandler(QgsRequestHandler *requestHandler) override
Set the request handler.
void clearRequestHandler() override
Clear the request handler.
QgsServerFiltersMap filters() override
Returns the list of current QgsServerFilter.
void setConfigFilePath(const QString &configFilePath) override
Set the configuration file path.
QgsAccessControl * accessControls() const override
Gets the helper over all the registered access control filters.
static QgsServerLogger * instance()
Gets the singleton instance.
Qgis::MessageLevel logLevel() const
Gets the current log level.
void setLogLevel(Qgis::MessageLevel level)
Set the current log level.
void setLogFile(const QString &filename=QString())
Set the current log file.
void setLogStderr()
Activates logging to stderr.
void logMessage(const QString &message, const QString &tag, Qgis::MessageLevel level) override
Log a message from the server context.
QgsServerParameters provides an interface to retrieve and manipulate global parameters received from ...
QMap< QString, QString > toMap() const
Returns all parameters in a map.
QString map() const
Returns MAP parameter as a string or an empty string if not defined.
QString service() const
Returns SERVICE parameter as a string or an empty string if not defined.
QString fileName() const
Returns FILE_NAME parameter as a string or an empty string if not defined.
virtual QString version() const
Returns VERSION parameter as a string or an empty string if not defined.
static bool initPlugins(QgsServerInterface *interface)
Initializes the Python plugins.
QgsServerRequest Class defining request interface passed to services QgsService::executeRequest() met...
QgsServerParameters serverParameters() const
Returns parameters.
QgsServerResponse Class defining response interface passed to services QgsService::executeRequest() m...
virtual void write(const QString &data)
Write string This is a convenient method that will write directly to the underlying I/O device.
virtual void clear()=0
Reset all headers and content for this response.
virtual void sendError(int code, const QString &message)=0
Send error This method delegates error handling at the server level.
Provides a way to retrieve settings by prioritizing according to environment variables,...
QgsServer()
Creates the server instance.
void handleRequest(QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project=nullptr)
Handles the request.
void putenv(const QString &var, const QString &val)
Set environment variable.
QgsServiceRegistry Class defining the registry manager for QGIS server services.
QgsServerApi * apiForRequest(const QgsServerRequest &request) const
Searches the API register for an API matching the request and returns a (possibly NULL) pointer to it...
void init(const QString &nativeModulepath, QgsServerInterface *serverIface=nullptr)
Initialize registry, load modules and auto register services.
QgsService * getService(const QString &name, const QString &version=QString())
Retrieve a service from its name.
QgsService Class defining interfaces for QGIS server services.
virtual void executeRequest(const QgsServerRequest &request, QgsServerResponse &response, const QgsProject *project)=0
Execute the requests and set result in QgsServerRequest.
#define QgsDebugMsgLevel(str, level)
Q_GLOBAL_STATIC(QgsServerSettings, sSettings)