Compare commits

..
46 Commits
Author SHA1 Message Date
fromme 11f46d0acf fix: use utf8mb4 for the database connection and new tables 2026-10-20 11:48:10 +02:00
fromme 4279669aa3 fix: add TCA default 0 to relation selects in TCA overrides for MySQL strict mode 2026-10-20 10:16:40 +02:00
fromme aa3d81102e chore: re-activate chatbot in page footer 2026-10-19 09:12:37 +02:00
frommeandClaude Opus 5.5 739a4c49f7 fix: write cachetool temp script to shared typo3temp
PHP workers with a stale realpath cache still resolve the current symlink
to the previous release and returned 404 for the script placed in the new
one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-18 18:21:06 +02:00
fromme 88e0488b49 fix: adopt text orientation in page footer on mobile screens 2026-10-18 18:13:39 +02:00
fromme f57671b4d4 fix: single column in footer menu on mobile screens 2026-10-18 18:11:13 +02:00
fromme 313fb151bc fix: add missing customer code pattern 2026-10-13 17:09:06 +02:00
fromme 6350742084 feat: show pickups table below bus section on product detail pages 2026-10-13 16:10:23 +02:00
fromme ef7d81fe99 feat: remove the feature flag for the pickups table on product detail pages 2026-10-13 14:26:22 +02:00
fromme 0477589a7a feat: fall back to the travel code for dates without a customer selection 2026-10-13 14:26:17 +02:00
fromme 38962845d3 chore: cleanup htaccess 2026-10-08 17:34:15 +02:00
fromme c7f43ad02c feat: add a feature flag for the pickups table on product detail pages 2026-10-08 17:22:21 +02:00
fromme 1111c180f8 feat: hide pickups of group travel dates on product detail pages 2026-10-08 17:20:31 +02:00
fromme 69f9b42757 feat: flag group travel dates from the BusPro customer selection 2026-10-08 16:09:43 +02:00
fromme 5bb4b6254a chore: update http client config 2026-10-08 11:40:57 +02:00
fromme 32b70f9b70 feat: require the CMS API key on /api/hotel and /api/product 2026-10-08 11:37:57 +02:00
fromme 7839b97e63 chore: add a PhpStorm HTTP client suite for the chatbot content feed 2026-10-08 09:41:27 +02:00
fromme 416ac5c13d feat: add a kill switch for the chatbot content feed 2026-10-08 09:36:16 +02:00
fromme 992ec19c33 feat: add the key-protected content-only page type for the chatbot feed 2026-10-08 09:36:12 +02:00
fromme 57b09624f4 feat: serve chatbot content records at /api/content/records 2026-10-08 09:36:06 +02:00
fromme 81724c818b feat: serve the chatbot content manifest at /api/content/manifest 2026-10-08 09:36:01 +02:00
fromme b4a9156df6 feat: add the API key check and settings for the chatbot content feed 2026-10-08 09:35:55 +02:00
fromme 41d188a8cc feat: display pickups data on product detail page
addresses #869cgn2fm
2026-10-07 17:01:13 +02:00
fromme c6ab02305b fix: load captcha image in Chrome on initial page load 2026-10-05 12:01:21 +02:00
fromme 306c6b809f feat: show hotel icons on hotel and product detail pages
addresses #86965w970
2026-10-01 14:17:28 +02:00
fromme 4095c4a068 fix: stop malformed captcha requests from poisoning the page cache 2026-09-30 15:24:50 +02:00
fromme b41aeb7a25 fix: carry pickup times as local clock readings, not instants 2026-09-30 14:57:46 +02:00
fromme c2dc88b8ab fix: match API whitespace handling and skip matchcodes of hidden hotels 2026-09-30 14:57:39 +02:00
fromme 27832d6548 fix: stop truncating imported prices to whole euros 2026-09-30 14:57:20 +02:00
fromme b510299032 feat: import products from the MyE&P export API 2026-09-30 14:57:13 +02:00
fromme 1b6f480bee feat: read the BusPro XML export through XmlProductReader 2026-09-30 14:57:07 +02:00
fromme b9851943d0 fix: key imported services by BusPro id and match selection groups by id 2026-09-30 14:56:50 +02:00
fromme d338529afc chore: cleanup .htaccess 2026-09-26 10:05:12 +02:00
fromme e3099bac5f feat: preconnect to the CDN host 2026-09-26 09:53:58 +02:00
fromme 322a59b31c feat: offer brotli for the assets the webhost now serves itself 2026-09-26 09:40:11 +02:00
fromme e96dd0f06d fix: resolve leaflet marker images through webpack 2026-09-26 09:35:58 +02:00
fromme f10d784a5c fix: serve theme assets from the production host, keep images on the CDN 2026-09-25 17:35:07 +02:00
fromme b5d0c484c0 fix: add missing template for date fields 2026-09-25 14:49:39 +02:00
fromme d8bb376424 fix: send form date values as YYYY-MM-DD strings to epteam api 2026-09-25 14:46:44 +02:00
fromme 38d575cbe9 fix: point the application form finisher at epteam 2026-09-23 09:26:12 +02:00
fromme f9e8704046 fix: datepicker obscured by logo in header searchbar 2026-09-23 09:24:25 +02:00
fromme 49547ecda3 fix: reuse the MyEP api connection instead of a client per call 2026-09-22 16:49:44 +02:00
fromme eb096bd8b5 chore: update project dependencies 2026-09-22 15:49:34 +02:00
fromme b3541b21fb feat: modernize fe tooling and drop weight 2026-09-22 15:29:34 +02:00
fromme 93ed5c6962 fix: harden encoded filter settings against malformed and stale input 2026-09-22 14:49:04 +02:00
fromme 942724fdd1 feat: derive room type from occupancy instead of a mapping table 2026-09-22 14:47:04 +02:00
139 changed files with 6458 additions and 2878 deletions

No files matched your search

+2 -1
View File
@@ -26,8 +26,9 @@ timezone: Europe/Berlin
composer_version: "2"
web_environment:
- TYPO3_CONTEXT=Development
nodejs_version: "18"
nodejs_version: "24"
corepack_enable: false
omit_containers: [ddev-ssh-agent]
# Key features of DDEV's config.yaml:
+1
View File
@@ -20,3 +20,4 @@ public/typo3conf/l10n
public/typo3temp
public/uploads
var
http-client.private.env.json
+1 -1
View File
@@ -1 +1 @@
18
24
+37 -7
View File
@@ -1,12 +1,42 @@
# Backchannel endpoints MyE&P reads hotel and product data from. Same environment files and key
# as content-feed.http: pick "local" and put cmsApiKey in http-client.private.env.json.
### GET product data for myep
GET https://ep-reisen.ddev.site/api/product
?product=SSTMR
&hotel=SSTGR
&key=abcabc123
GET {{host}}/api/product?product=3VIIN&hotel=VLTS
X-Api-Key: {{cmsApiKey}}
> {%
client.test("200 with key", function () {
client.assert(response.status === 200, "expected 200, got " + response.status);
});
%}
### GET hotel data for myep
GET https://ep-reisen.ddev.site/api/hotel
?hotel=DPWGRP
&key=abcabc123
GET {{host}}/api/hotel?hotel=DPWGRP
X-Api-Key: {{cmsApiKey}}
> {%
client.test("200 with key", function () {
client.assert(response.status === 200, "expected 200, got " + response.status);
});
%}
### Transition form: key as query parameter, as MyE&P sends it today (still accepted)
GET {{host}}/api/hotel?hotel=DPWGRP&key={{cmsApiKey}}
> {%
client.test("200 with query key", function () {
client.assert(response.status === 200, "expected 200, got " + response.status);
});
%}
### Any other value is refused now - this used to pass
GET {{host}}/api/hotel?hotel=DPWGRP&key=AbcAbc123
> {%
client.test("403 with the old dummy key", function () {
client.assert(response.status === 403, "expected 403, got " + response.status);
});
%}
###
Generated
+8 -7
View File
@@ -1817,21 +1817,22 @@
},
{
"name": "league/oauth2-client",
"version": "2.9.0",
"version": "2.9.1",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/oauth2-client.git",
"reference": "26e8c5da4f3d78cede7021e09b1330a0fc093d5e"
"reference": "8cedfef9d01a8d1fd2ecfabb41734b17592c4b71"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/26e8c5da4f3d78cede7021e09b1330a0fc093d5e",
"reference": "26e8c5da4f3d78cede7021e09b1330a0fc093d5e",
"url": "https://api.github.com/repos/thephpleague/oauth2-client/zipball/8cedfef9d01a8d1fd2ecfabb41734b17592c4b71",
"reference": "8cedfef9d01a8d1fd2ecfabb41734b17592c4b71",
"shasum": ""
},
"require": {
"ext-json": "*",
"guzzlehttp/guzzle": "^6.5.8 || ^7.4.5",
"guzzlehttp/guzzle": "^6.5.8 || ^7.8.2 || ^8.0",
"guzzlehttp/psr7": "^1.9.1 || ^2.6.3 || ^3.0",
"php": "^7.1 || >=8.0.0 <8.6.0"
},
"require-dev": {
@@ -1876,9 +1877,9 @@
],
"support": {
"issues": "https://github.com/thephpleague/oauth2-client/issues",
"source": "https://github.com/thephpleague/oauth2-client/tree/2.9.0"
"source": "https://github.com/thephpleague/oauth2-client/tree/2.9.1"
},
"time": "2025-11-25T22:17:17+00:00"
"time": "2026-09-16T13:14:31+00:00"
},
{
"name": "league/period",
+141
View File
@@ -0,0 +1,141 @@
# Chatbot content feed (see .ddev/plans/CHATBOT-MCP-01-TYPO3-CONTENT-FEED.md)
#
# Pick the "local" environment in PhpStorm and run the whole file top to bottom: the manifest
# request stores uids and a content URL that the later requests use.
#
# Needs, locally:
# - http-client.private.env.json with {"local": {"cmsApiKey": "<your key>"}} (gitignored)
# - the same key in TYPO3, e.g.
# ddev exec vendor/bin/typo3cms configuration:set EXTENSIONS/ep_products/cmsApiKey <your key>
# plus contentFeedSites etc. - or open and save the ep_products extension configuration once
# in the backend, which writes all the defaults.
#
# The kill switch (contentFeedEnabled = 0) cannot be toggled from here; with it off, every keyed
# request below answers 503.
### Manifest without a key is refused
GET {{host}}/api/content/manifest
> {%
client.test("403 without key", function () {
client.assert(response.status === 403, "expected 403, got " + response.status);
});
%}
### Manifest
GET {{host}}/api/content/manifest
X-Api-Key: {{cmsApiKey}}
> {%
client.test("manifest is complete and well-formed", function () {
client.assert(response.status === 200, "expected 200, got " + response.status);
client.assert(response.body.items.length > 0, "manifest is empty");
client.assert(response.body.sites.length > 0, "no sites");
client.assert(
response.body.items.every(function (item) { return item.type && item.uid && item.modified; }),
"an item lacks type, uid or modified"
);
});
var uidsOf = function (type, limit) {
return response.body.items
.filter(function (item) { return item.type === type; })
.slice(0, limit)
.map(function (item) { return item.uid; })
.join(",");
};
client.global.set("productUids", uidsOf("product", 5));
client.global.set("hotelUids", uidsOf("hotel", 5));
client.global.set("regionUids", uidsOf("region", 5));
client.global.set("newsUids", uidsOf("news", 3));
var page = response.body.items.filter(function (item) { return item.type === "page" && item.contentUrl; })[0];
client.global.set("contentUrl", page.contentUrl);
var tooMany = [];
for (var i = 1; i <= 101; i++) { tooMany.push(i); }
client.global.set("tooManyUids", tooMany.join(","));
%}
### Products (with FAQs)
GET {{host}}/api/content/records?type=product&uids={{productUids}}
X-Api-Key: {{cmsApiKey}}
> {%
client.test("every requested product comes back, links resolved", function () {
client.assert(response.status === 200, "expected 200, got " + response.status);
client.assert(response.body.items.length === client.global.get("productUids").split(",").length, "products missing");
client.assert(JSON.stringify(response.body).indexOf("t3://") === -1, "unresolved t3:// link");
});
%}
### Hotels (codes include matchcode aliases)
GET {{host}}/api/content/records?type=hotel&uids={{hotelUids}}
X-Api-Key: {{cmsApiKey}}
> {%
client.test("hotels carry their codes", function () {
client.assert(response.status === 200, "expected 200, got " + response.status);
client.assert(response.body.items.every(function (hotel) { return Array.isArray(hotel.codes); }), "hotel without codes");
});
%}
### Regions
GET {{host}}/api/content/records?type=region&uids={{regionUids}}
X-Api-Key: {{cmsApiKey}}
### Blog articles
GET {{host}}/api/content/records?type=news&uids={{newsUids}}
X-Api-Key: {{cmsApiKey}}
### Unknown type is a 400
GET {{host}}/api/content/records?type=page&uids=1
X-Api-Key: {{cmsApiKey}}
> {%
client.test("400 for unknown type", function () {
client.assert(response.status === 400, "expected 400, got " + response.status);
});
%}
### More than 100 uids is a 400
GET {{host}}/api/content/records?type=product&uids={{tooManyUids}}
X-Api-Key: {{cmsApiKey}}
> {%
client.test("400 above 100 uids", function () {
client.assert(response.status === 400, "expected 400, got " + response.status);
});
%}
### Content-only render of the first page in the manifest
GET {{contentUrl}}
X-Api-Key: {{cmsApiKey}}
> {%
client.test("bare article, never cached by proxies", function () {
client.assert(response.status === 200, "expected 200, got " + response.status);
client.assert(response.body.indexOf("<article>") === 0, "not a bare <article> fragment");
client.assert(response.headers.valueOf("Cache-Control") === "private, no-store", "unexpected Cache-Control");
});
%}
### Content-only render without a key is a 404 (the type must not be discoverable)
GET {{contentUrl}}
> {%
client.test("404 without key", function () {
client.assert(response.status === 404, "expected 404, got " + response.status);
});
%}
### Content-only render with a wrong key is a 404
GET {{contentUrl}}
X-Api-Key: definitely-wrong
> {%
client.test("404 with wrong key", function () {
client.assert(response.status === 404, "expected 404, got " + response.status);
});
%}
+8 -3
View File
@@ -38,7 +38,6 @@ $rsyncOptions = [
'var',
'.editorconfig',
'.gitignore',
'.htaccess_prod',
'deploy.php',
'package.json',
'package-lock.json',
@@ -52,7 +51,10 @@ $rsyncOptions = [
'filter' => [],
'filter-file' => false,
'filter-perdir' => false,
'flags' => 'rz',
// -t preserves mtimes: without it every file lands with a fresh timestamp, so unchanged
// files get a new Last-Modified on every deploy and every conditional request revalidates
// into a full response instead of a 304.
'flags' => 'rzt',
'options' => ['delete', 'links', 'chmod=D755,F664'],
'timeout' => 300,
];
@@ -68,7 +70,10 @@ host('prod')
->set('writable_mode', 'chmod')
->set('rsync_src', __DIR__)
->set('rsync', $rsyncOptions)
->set('cachetool_args', '--web=SymfonyHttpClient --web-path={{current_path}}/{{typo3_webroot}}/ --web-url=https://www.ep-reisen.de')
// The temp script goes into the shared typo3temp, which resolves to the same directory from every
// release: PHP workers with a stale realpath cache still map "current" to the previous release and
// would 404 on a script placed inside the new one.
->set('cachetool_args', '--web=SymfonyHttpClient --web-path={{deploy_path}}/shared/{{typo3_webroot}}/typo3temp/ --web-url=https://www.ep-reisen.de/typo3temp')
;
task('deploy', [
+8
View File
@@ -0,0 +1,8 @@
{
"local": {
"host": "https://ep-reisen.ddev.site"
},
"prod": {
"host": "https://www.ep-reisen.de"
}
}
+1415 -1590
View File
File diff suppressed because it is too large. Load diff
+9 -21
View File
@@ -1,25 +1,22 @@
{
"name": "eptheme",
"description": "EP Reisen TYPO3 website package",
"version": "3.0.0",
"author": "Björn Fromme, [email protected]",
"license": "proprietary",
"scripts": {
"dev": "./node_modules/.bin/encore dev --watch",
"build": "NODE_ENV=production ./node_modules/.bin/encore production"
},
"engines": {
"node": ">=16"
"node": ">=20.19.0"
},
"browserslist": [
"defaults"
],
"dependencies": {
"@hotwired/stimulus": "^3.2.1",
"@hotwired/stimulus-webpack-helpers": "^1.0.1",
"@iframe-resizer/parent": "^5.3.2",
"@splidejs/splide": "^2.4.21",
"axios": "^1.6.2",
"cooltipz-css": "^1.6.8",
"dayjs": "^1.10.6",
"es6-slide-up-down": "^1.0.0",
"flatpickr": "^4.6.9",
"glightbox": "^3.0.9",
"htmx.org": "^1.9.12",
@@ -30,31 +27,22 @@
"sticky-js": "^1.3.0",
"stimulus-use": "^0.52.0",
"vue": "^2.6.14",
"vue-router": "^3.5.2",
"vue-session": "^1.0.0",
"vuex": "^3.6.2",
"whatwg-fetch": "^3.6.2"
"vue-session": "^1.0.0"
},
"devDependencies": {
"@babel/plugin-proposal-object-rest-spread": "^7.16.0",
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/preset-env": "^7.16.0",
"@symfony/webpack-encore": "^2.1.0",
"@symfony/webpack-encore": "^4.7.0",
"@tailwindcss/aspect-ratio": "^0.4.0",
"@tailwindcss/forms": "^0.5.2",
"autoprefixer": "^10.4.8",
"core-js": "^3.22.5",
"document-register-element": "^1.14.10",
"file-loader": "^6.2.0",
"postcss": "^8.4.16",
"postcss-loader": "^6.2.1",
"postcss-loader": "^8.2.1",
"sass": "^1.53.0",
"sass-loader": "^12.6.0",
"sass-mq": "^6.0.0",
"smoothscroll-polyfill": "^0.4.4",
"sass-loader": "^14.2.1",
"sass-mq": "^7.0.1",
"tailwindcss": "^3.1.8",
"tailwindcss-alt": "^3.0.0",
"vue-custom-element": "^3.3.0",
"vue-loader": "^15.11.1",
"vue-template-compiler": "^2.6.14"
}
+114 -10
View File
@@ -75,6 +75,58 @@ AddType image/webp .webp
</IfModule>
</IfModule>
# Brotli, where the host has the module. It beats gzip by roughly 15-20% on the theme's
# minified css/js at no measurable cost, and falls back to the mod_deflate block above for
# clients that do not announce `br` - which is also what happens wholesale if the module is
# missing, because the whole block is then skipped.
#
# The type list is deliberately the same one mod_deflate gets: `no-gzip` below switches gzip
# off for every br-capable client, so a type listed for DEFLATE only would reach those
# clients uncompressed.
<IfModule mod_brotli.c>
# Both filters would otherwise run for a client announcing `br, gzip` and gzip the brotli
# output on top of itself. mod_deflate honours `no-gzip`, so brotli wins where it is
# offered and gzip keeps everyone else.
<IfModule mod_setenvif.c>
SetEnvIfNoCase Accept-Encoding "(^|[\s,])br($|[\s,;])" no-gzip
</IfModule>
<IfModule mod_filter.c>
AddOutputFilterByType BROTLI_COMPRESS application/atom+xml \
application/javascript \
application/json \
application/ld+json \
application/manifest+json \
application/rdf+xml \
application/rss+xml \
application/schema+json \
application/vnd.geo+json \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/x-javascript \
application/x-web-app-manifest+json \
application/xhtml+xml \
application/xml \
font/eot \
font/opentype \
image/bmp \
image/svg+xml \
image/vnd.microsoft.icon \
image/x-icon \
text/cache-manifest \
text/css \
text/html \
text/javascript \
text/plain \
text/vcard \
text/vnd.rim.location.xloc \
text/vtt \
text/x-component \
text/x-cross-domain-policy \
text/xml
</IfModule>
</IfModule>
### End: Compression ###
@@ -139,6 +191,16 @@ AddType image/webp .webp
</IfModule>
# Webpack writes an 8-hex-character content hash into the filename of everything it emits, so
# these URLs can never change meaning - a new build is a new URL. `immutable` stops browsers
# revalidating them on reload, and overrides the per-type rules above, which would otherwise
# expire the hashed fonts after a month.
<IfModule mod_headers.c>
<FilesMatch "\.[0-9a-f]{8}\.(js|css|woff2?|jpe?g|png|gif|svg|webp|avif)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>
### End: Browser caching of resource files ###
@@ -223,9 +285,6 @@ AddDefaultCharset utf-8
<FilesMatch "\.(eot|otf|tt[cf]|woff2?)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
<FilesMatch "\.(png|gif|jpe?g)$">
Header append Vary Accept
</FilesMatch>
</IfModule>
### End: Cross Origin ###
@@ -241,7 +300,58 @@ AddDefaultCharset utf-8
# Enable URL rewriting
RewriteEngine On
# Force SSL
# Legacy and campaign domains, consolidated onto their current host. These have to stay
# ahead of the Force SSL block and of TYPO3's catch-all at the end of this file, or a
# request for one of them reaches index.php before it is ever redirected.
#
# Maintained here rather than on the host: the deploy rsyncs this file into every release
# (deploy.php), so anything edited live is gone after the next one.
RewriteRule ^buchung/(.*)$ https://bpn.ep-reisen.de/$1 [R=302,L,QSA]
RewriteCond %{HTTP_HOST} ^cllt\-touristik\.at$ [NC]
RewriteRule ^(.*) https://www.cllt-touristik.at/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^alpinevacation\.ch$ [NC]
RewriteRule ^(.*) https://www.alpinevacation.ch/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^(www\.)?semesterendeskireisen\.de$ [NC]
RewriteRule ^(.*) https://www.semesterende-skireisen.de/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^semesterende\-skireisen\.de$ [NC]
RewriteRule ^(.*) https://www.semesterende-skireisen.de/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^snowzone\.net$ [NC]
RewriteRule ^(.*) https://www.snowzone.net/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^ski\-boarderweek\.de$ [NC]
RewriteRule ^(.*) https://www.ski-boarderweek.de/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ski\-boarderweek\.(com|eu)$ [NC]
RewriteRule ^(.*) https://www.ski-boarderweek.de/$1 [L,R=301]
RewriteCond %{HTTP_HOST} skiboarderweek\.(de|eu)$ [NC]
RewriteRule ^(.*) https://www.ski-boarderweek.de/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^ski\-wochenenden\.de$ [NC]
RewriteRule ^(.*) https://www.ski-wochenenden.de/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^ep\-events\.de$ [NC]
RewriteRule ^(.*) https://www.ep-events.de/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^ep\-reisen\.de$ [NC]
RewriteRule ^(.*) https://www.ep-reisen.de/$1 [L,R=301]
# The dropped path is deliberate: snow-break sends every deep link to the snowbreak
# landing page, unlike unichamp below, which keeps it.
RewriteCond %{HTTP_HOST} ^(www\.)?snow\-break\.(de|com) [NC]
RewriteRule (.*) https://snowbreak.ep-reisen.de/ [R=302,L]
# Matches the bare domain as well, so it lands on snowbreak in one hop - a separate
# unichamp.de -> www.unichamp.de rule used to run first and cost an extra 301.
RewriteCond %{HTTP_HOST} ^(www\.)?unichamp\.de$ [NC]
RewriteRule ^(.*) https://snowbreak.ep-reisen.de/$1 [L,R=302]
# Force SSL
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
@@ -282,12 +392,6 @@ AddDefaultCharset utf-8
# NOTE: Add your additional local storages here
RewriteRule ^(?:typo3/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L]
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{REQUEST_FILENAME} (.*)\.(png|gif|jpe?g)$
RewriteCond %{REQUEST_FILENAME}\.webp -f
RewriteRule ^ %{REQUEST_FILENAME}\.webp [L,T=image/webp]
### Begin: StaticFileCache (preparation) ####
# Document root configuration
@@ -90,6 +90,14 @@ $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['rootline']
// by the CDN, so stop generating them. mod_deflate still compresses direct origin hits.
$GLOBALS['TYPO3_CONF_VARS']['FE']['compressionLevel'] = 0;
// utf8 in MySQL/MariaDB is utf8mb3 (max. 3 bytes) and rejects 4-byte characters like emoji.
// Set here because LocalConfiguration.php is a Deployer shared file and not deployed from the repo.
$GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['charset'] = 'utf8mb4';
$GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['tableoptions'] = [
'charset' => 'utf8mb4',
'collate' => 'utf8mb4_unicode_ci',
];
// suppress php deprecation warnings flooding typo3 logs
$GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors'] =
$GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors'] & ~E_DEPRECATED & ~E_USER_DEPRECATED;
@@ -59,6 +59,7 @@ call_user_func(function() {
'label' => 'Reiseart',
'config' => [
'type' => 'select',
'default' => 0,
'renderType' => 'selectSingle',
'items' => [
['Keine Zuordnung', 0],
@@ -74,6 +75,7 @@ call_user_func(function() {
'label' => 'Angebot/Beispielangebot',
'config' => [
'type' => 'select',
'default' => 0,
'renderType' => 'selectSingle',
'items' => [
['Keine Zuordnung', 0],
@@ -55,7 +55,6 @@
</template>
<script>
import axios from 'axios';
import $ from 'jquery';
export default {
@@ -82,13 +81,21 @@
load() {
this.loading = true;
sessionStorage.setItem('filterSettings', JSON.stringify(this.filterSettings));
axios({
url: this.endpointUri,
method: 'post',
data: $.param({'tx_epevents_ajax[filterSettings]': this.filterSettings})
fetch(this.endpointUri, {
method: 'POST',
credentials: 'same-origin',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: $.param({'tx_epevents_ajax[filterSettings]': this.filterSettings})
}).then(response => {
this.offers = response.data.offers;
this.filterOptions = response.data.filterOptions;
// fetch only rejects on network errors, so surface HTTP errors here
// to keep the previous behaviour of falling through to .catch()
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
}).then(data => {
this.offers = data.offers;
this.filterOptions = data.filterOptions;
this.loading = false;
}).catch(() => {
this.loading = false;
@@ -1,7 +1,10 @@
@use "breakpoints";
@use "mixins";
.badge {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
position: relative;
z-index: 10;
@@ -27,15 +30,15 @@
font-size: 20px;
font-weight: 700;
line-height: 130%;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 32px;
}
}
.badge__outline {
@include sectionFills(0.15);
@include mixins.sectionFills(0.15);
}
.badge__inner {
@include sectionFills();
@include mixins.sectionFills();
}
@@ -1,3 +1,5 @@
@use "mixins";
.banner {
position: relative;
margin-bottom: 20px;
@@ -8,7 +10,7 @@
min-height: 300px;
padding: 48px 0;
color: white;
@include sectionBackgrounds(0.8);
@include mixins.sectionBackgrounds(0.8);
display: flex;
justify-content: space-around;
align-items: center;
@@ -1,14 +1,20 @@
@use "breakpoints";
@use "colors";
@use "fonts";
@use "mixins";
@use "variables";
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-family: $font-main, Sans-Serif;
font-family: fonts.$font-main, Sans-Serif;
font-weight: 400;
font-size: 16px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 18px;
}
@@ -41,13 +47,13 @@ html {
height: auto;
margin-left: auto;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: none;
}
}
.navtoggle__icon {
fill: $color-font-main;
fill: colors.$color-font-main;
transition: all 0.25s ease-in-out;
.mobilenav--open & {
@@ -62,7 +68,7 @@ html {
right: 2%;
width: 40px;
height: 40px;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
opacity: 0.75;
}
@@ -76,12 +82,12 @@ a {
&.anchor {
display: block;
height: 0;
padding-top: $header-height-mobile;
margin-top: -$header-height-mobile;
padding-top: variables.$header-height-mobile;
margin-top: -(variables.$header-height-mobile);
@include mq($from: tablet) {
padding-top: $header-height-desktop;
margin-top: -$header-height-desktop;
@include breakpoints.mq($from: tablet) {
padding-top: variables.$header-height-desktop;
margin-top: -(variables.$header-height-desktop);
}
}
}
@@ -126,7 +132,7 @@ ul {
left: 0;
content: "\25CF";
font-size: 18px;
@include sectionColoursFromParent();
@include mixins.sectionColoursFromParent();
}
}
}
@@ -144,8 +150,8 @@ p {
hr {
max-width: 25%;
margin: 32px auto 32px 0;
color: $color-ruler;
background-color: $color-ruler;
color: colors.$color-ruler;
background-color: colors.$color-ruler;
height: 1px;
border: none;
}
@@ -161,7 +167,7 @@ h3,
}
.headline {
@include sectionColoursFromParent();
@include mixins.sectionColoursFromParent();
&--icon {
display: flex;
@@ -186,7 +192,7 @@ h1,
text-transform: uppercase;
padding-bottom: 18px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 32px;
padding-bottom: 24px;
}
@@ -200,11 +206,11 @@ h1,
display: block;
font-size: 16px;
line-height: 120%;
color: $color-brand-primary;
color: colors.$color-brand-primary;
text-transform: none;
@include sectionColoursFromParent();
@include mixins.sectionColoursFromParent();
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 24px;
}
@@ -221,7 +227,7 @@ h2,
padding-bottom: 16px;
font-weight: 400;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 24px;
padding-bottom: 24px;
}
@@ -231,7 +237,7 @@ h3 {
font-weight: 400;
font-size: 16px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 18px;
padding-bottom: 8px;
}
@@ -243,7 +249,7 @@ h3 {
height: auto;
padding-right: 16px;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
width: 96px;
}
}
@@ -1,3 +1,6 @@
@use "breakpoints";
@use "colors";
.box {
width: 100%;
}
@@ -13,7 +16,7 @@
color: white;
text-align: center;
text-decoration: none;
background-color: $color-brand-secondary;
background-color: colors.$color-brand-secondary;
border: none;
width: 100%;
font-size: 20px;
@@ -23,18 +26,18 @@
.box__content {
padding: 32px 16px;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
}
.box__form {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
width: 100%;
height: auto;
fill: $color-brand-primary;
fill: colors.$color-brand-primary;
}
&--top {
@@ -52,7 +55,7 @@
font-size: 16px;
line-height: 32px;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
font-size: 20px;
line-height: 32px;
@@ -66,7 +69,7 @@
.box__nav {
margin-top: -32px;
padding-bottom: 32px;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
}
.box__nav__item {
@@ -78,7 +81,7 @@
&--active,
&:hover {
background-color: $color-brand-light;
background-color: colors.$color-brand-light;
}
}
@@ -1,6 +1,9 @@
@use "breakpoints";
@use "colors";
.brands {
padding-top: 32px;
border-top: 1px solid $color-divider;
border-top: 1px solid colors.$color-divider;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
@@ -9,7 +12,7 @@
.brands__item {
width: 50%;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 25%;
}
}
@@ -1,7 +1,9 @@
$mq-breakpoints: (
mobile: $viewport-width-mobile,
tablet: $viewport-width-tablet,
desktop: $viewport-width-desktop
);
@use "variables";
@import "~sass-mq";
@forward "sass-mq" with (
$breakpoints: (
mobile: variables.$viewport-width-mobile,
tablet: variables.$viewport-width-tablet,
desktop: variables.$viewport-width-desktop
)
);
@@ -1,3 +1,7 @@
@use "breakpoints";
@use "colors";
@use "mixins";
.button {
display: inline-block;
font-weight: 700;
@@ -5,7 +9,7 @@
&--default {
display: inline-block;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
padding: 4px 16px;
}
@@ -13,7 +17,7 @@
&--page-header {
display: block;
min-width: 186px;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
font-size: 18px;
padding: 0 32px 0 24px;
@@ -26,14 +30,14 @@
display: block;
min-width: 220px;
text-align: center;
background-color: $color-brand-primary;
@include sectionBackgroundsFromParent();
background-color: colors.$color-brand-primary;
@include mixins.sectionBackgroundsFromParent();
color: white;
line-height: 48px;
border: none;
outline: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
box-shadow: 8px 8px 8px rgba(black, 0.2);
font-size: 24px;
}
@@ -43,7 +47,7 @@
width: 100%;
display: inline-block;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: auto;
}
}
@@ -56,7 +60,7 @@
&:hover {
background: white;
color: $color-font-main;
color: colors.$color-font-main;
}
}
@@ -65,7 +69,7 @@
}
&--icon {
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
width: 16px;
height: 16px;
@@ -1,5 +1,8 @@
@use "breakpoints";
@use "mixins";
.card {
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
&:not(.card--no-form) {
padding-bottom: 48px;
}
@@ -20,12 +23,12 @@
padding: 16px;
color: white;
text-transform: uppercase;
@include sectionBackgrounds(0.75);
@include mixins.sectionBackgrounds(0.75);
transition: background-color 0.25s ease-in-out;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
.card:hover & {
@include sectionBackgrounds();
@include mixins.sectionBackgrounds();
}
}
}
@@ -33,7 +36,7 @@
.card__form {
display: none;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
display: block;
opacity: 0;
transition: opacity 0.25s ease-in-out;
@@ -50,7 +53,7 @@
}
polygon {
@include sectionFills();
@include mixins.sectionFills();
}
}
@@ -1,21 +1,25 @@
@use "colors";
@use "mixins";
@use "variables";
.carousel {
&--background {
background-color: $color-background;
background-color: colors.$color-background;
padding-bottom: 48px;
margin-bottom: 8px;
}
@include sectionBackgrounds(0.25);
@include mixins.sectionBackgrounds(0.25);
}
.carousel__outer {
@include container($viewport-width-max);
@include mixins.container(variables.$viewport-width-max);
position: relative;
}
.carousel__inner {
@include container($content-width-max);
@include mixins.container(variables.$content-width-max);
}
.carousel__item {
@@ -36,7 +40,7 @@
height: 32px;
fill: white;
@include sectionColoursFromParent;
@include mixins.sectionColoursFromParent;
&--prev {
left: -5px;
@@ -59,7 +63,7 @@
}
.testimonials & {
fill: $color-brand-primary;
fill: colors.$color-brand-primary;
}
}
@@ -1,8 +1,10 @@
@use "sass:color";
//$color-brand-primary: #0084d4;
$color-brand-primary: #19a0d2;
$color-brand-secondary: #1e314b;
$color-brand-light: #8CCFE8;
$color-background: lighten(#dbdee2, 5%);
$color-background: color.adjust(#dbdee2, $lightness: 5%);
$color-font-main: #1e314b;
$color-divider: rgba($color-background, 0.8);
@@ -1,3 +1,6 @@
@use "breakpoints";
@use "colors";
.configurator {
background: url(../images/bg_configurator.jpg) no-repeat top left;
background-size: cover;
@@ -39,7 +42,7 @@
flex-wrap: wrap;
justify-content: center;
align-items: center;
background-color: rgba($color-brand-secondary, 0.85);
background-color: rgba(colors.$color-brand-secondary, 0.85);
color: white;
}
@@ -51,7 +54,7 @@
display: none;
color: white;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
display: block;
}
}
@@ -83,11 +86,11 @@
text-decoration: none;
text-transform: uppercase;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
flex-wrap: nowrap;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
align-items: center;
}
}
@@ -98,12 +101,12 @@
margin-bottom: 8px;
font-weight: 700;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 30%;
margin-bottom: 0;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 20%;
margin-bottom: 0;
}
@@ -113,11 +116,11 @@
width: 100%;
padding-right: 40px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 70%;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 80%;
}
}
@@ -131,11 +134,11 @@
font-size: 14px;
font-weight: 700;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 16px;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
margin-bottom: 0;
}
}
@@ -151,13 +154,13 @@
text-decoration: none;
text-align: center;
color: white;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
border-radius: 16px;
font-family: "fontello";
&.closed {
background-color: white;
color: $color-brand-primary;
color: colors.$color-brand-primary;
&:before {
content: '\e800';
@@ -204,7 +207,7 @@
margin-bottom: 8px;
}
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
width: 50%;
.active & {
@@ -212,7 +215,7 @@
}
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 25%;
.active & {
@@ -240,10 +243,10 @@
}
.selected &:after {
background-color: rgba($color-brand-secondary, 0.75);
background-color: rgba(colors.$color-brand-secondary, 0.75);
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
&:hover:after {
content: "";
width: 100%;
@@ -251,7 +254,7 @@
position: absolute;
top: 0;
left: 0;
background-color: rgba($color-brand-primary, 0.5);
background-color: rgba(colors.$color-brand-primary, 0.5);
}
}
@@ -260,12 +263,12 @@
background-position: center 32px;
background-size: 96px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
background-position: center 16px;
background-size: 128px;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
background-position: center 8px;
background-size: 96px;
}
@@ -382,7 +385,7 @@
flex-wrap: wrap;
justify-content: space-between;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
flex-wrap: nowrap;
}
}
@@ -391,7 +394,7 @@
width: 100%;
padding-bottom: 16px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 66.6666%;
padding-right: 32px;
}
@@ -401,7 +404,7 @@
width: 100%;
padding-bottom: 16px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 33.3333%;
}
}
@@ -456,7 +459,7 @@
line-height: 32px;
text-align: center;
background-color: white;
color: $color-brand-primary;
color: colors.$color-brand-primary;
border-radius: 16px;
font-family: 'fontello';
@@ -1,3 +1,6 @@
// .headline* live in _base.scss; @extend needs that module loaded explicitly.
@use "base";
.cookiefirst {
h2 {
@extend .headline;
@@ -1,10 +1,14 @@
@use "breakpoints";
@use "colors";
@use "mixins";
.form {
margin: 0;
padding: 0;
position: relative;
max-width: 100%;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
&:not(&--horizontal) {
max-width: 75%;
}
@@ -16,7 +20,7 @@
&--horizontal {
width: 100%;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: flex;
justify-content: space-between;
align-items: center;
@@ -42,7 +46,7 @@
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
background-color: $color-brand-light;
background-color: colors.$color-brand-light;
color: white;
border-radius: 8px;
}
@@ -50,7 +54,7 @@
&--mobile {
display: block;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: none;
}
}
@@ -58,7 +62,7 @@
&--tablet {
display: none;
@include mq($from: tablet, $until: desktop) {
@include breakpoints.mq($from: tablet, $until: desktop) {
display: block;
}
}
@@ -66,7 +70,7 @@
&--desktop {
display: none;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
display: block;
}
}
@@ -79,7 +83,7 @@
padding-top: 20px;
}
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 33.3333%;
}
}
@@ -88,20 +92,20 @@
.form__item__error {
padding: 8px;
font-size: 90%;
color: $color-formerror;
color: colors.$color-formerror;
}
.form__field {
@include nooutline;
@include mixins.nooutline;
border: none;
border-radius: 8px;
width: 100%;
padding: 8px 16px;
color: white;
background-color: $color-brand-light;
background-color: colors.$color-brand-light;
.form--box & {
background-color: $color-brand-light;
background-color: colors.$color-brand-light;
color: white;
}
@@ -114,10 +118,10 @@
display: block;
padding: 8px;
width: 100%;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 50%;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 25%;
}
}
@@ -127,7 +131,7 @@
}
.has-errors & {
border: 1px solid $color-formerror;
border: 1px solid colors.$color-formerror;
}
}
@@ -158,7 +162,7 @@
display: block;
width: 100%;
color: white;
background-color: $color-brand-secondary;
background-color: colors.$color-brand-secondary;
border: none;
font-weight: 700;
text-decoration: none;
@@ -166,7 +170,7 @@
padding: 8px 32px;
margin-bottom: 16px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: inline-block;
width: auto;
margin-bottom: 0;
@@ -189,10 +193,10 @@
flex-wrap: wrap;
justify-content: center;
align-items: center;
background-color: rgba($color-divider, 0.75);
background-color: rgba(colors.$color-divider, 0.75);
.form--box & {
background-color: rgba($color-brand-primary, 0.75);
background-color: rgba(colors.$color-brand-primary, 0.75);
}
}
@@ -1,7 +1,10 @@
@use "breakpoints";
@use "colors";
.helpernav {
display: none;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
display: block;
position: relative;
}
@@ -24,7 +27,7 @@
z-index: 10;
min-width: 300px;
padding: 16px 32px;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
}
.helpernav__item {
@@ -32,7 +35,7 @@
&:hover:not(.helpernav__item--disabled) {
& > .helpernav__link {
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
}
& > .helpernav__subnav {
@@ -1,11 +1,16 @@
@use "breakpoints";
@use "colors";
@use "mixins";
@use "variables";
.herounit {
position: relative;
width: 100%;
max-width: $viewport-width-max;
max-width: variables.$viewport-width-max;
margin: 0 auto;
&--indent {
max-width: $content-width-max - 16px;
max-width: variables.$content-width-max - 16px;
}
}
@@ -16,22 +21,22 @@
height: 240px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
height: 384px;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
height: 420px;
}
.herounit--large & {
height: 300px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
height: 480px;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
height: 700px;
}
}
@@ -39,7 +44,7 @@
.herounit--indent & {
height: 320px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
height: 480px;
}
}
@@ -48,7 +53,7 @@
.herounit__mask {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
position: absolute;
z-index: 10;
top: 0;
@@ -67,9 +72,9 @@
width: 100%;
height: 100%;
padding: 32px;
background-color: rgba($color-brand-secondary, 0.2);
background-color: rgba(colors.$color-brand-secondary, 0.2);
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
background-color: transparent;
padding: 64px 16px 0 96px;
max-width: 45%;
@@ -83,7 +88,7 @@
font-size: 32px;
line-height: 95%;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
font-size: 48px;
}
@@ -101,10 +106,10 @@
span {
font-weight: 700;
text-transform: uppercase;
color: $color-brand-primary;
color: colors.$color-brand-primary;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
font-size: 56px;
}
}
@@ -120,7 +125,7 @@
color: white;
text-transform: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 20px;
}
@@ -128,12 +133,12 @@
font-size: 22px;
font-weight: 700;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 24px;
padding-bottom: 48px;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
font-size: 32px;
padding-bottom: 96px;
}
@@ -146,7 +151,7 @@
line-height: 120%;
color: white;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
}
}
@@ -154,7 +159,7 @@
.herounit__icon {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
width: 100%;
height: auto;
@@ -173,11 +178,11 @@
left: 50%;
transform: translateX(-50%);
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
top: 85%;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
@@ -190,34 +195,34 @@
height: 48px;
border: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
}
& > polygon {
fill: $color-brand-primary;
@include sectionFills();
fill: colors.$color-brand-primary;
@include mixins.sectionFills();
}
}
#gradient__from {
stop-color: $color-brand-secondary;
stop-color: colors.$color-brand-secondary;
}
#gradient__to {
.section-default & {
stop-color: $color-brand-primary;
stop-color: colors.$color-brand-primary;
}
.section-incentives & {
stop-color: $color-incentives;
stop-color: colors.$color-incentives;
}
.section-teambuilding & {
stop-color: $color-teambuilding;
stop-color: colors.$color-teambuilding;
}
.secolor-meeting & {
stop-color: $color-meetings;
stop-color: colors.$color-meetings;
}
.secolor-events & {
stop-color: $color-events;
stop-color: colors.$color-events;
}
}
@@ -1,9 +1,12 @@
@use "breakpoints";
@use "colors";
.iconbar {
@apply hidden lg:block fixed z-100 top-[30vh] right-0 overflow-hidden;
}
.iconbar {
display: none;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
display: block;
}
position: fixed;
@@ -20,7 +23,7 @@
display: flex;
flex-wrap: nowrap;
align-items: center;
background-color: $color-brand-light;
background-color: colors.$color-brand-light;
margin-bottom: 2px;
&:hover {
@@ -30,7 +33,7 @@
.iconbar__icon {
padding: 4px;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
svg {
display: block;
@@ -1,3 +1,6 @@
@use "breakpoints";
@use "mixins";
.iconnav {
display: flex;
flex-wrap: wrap;
@@ -21,7 +24,7 @@
opacity: 1;
}
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
width: 25%;
}
}
@@ -36,5 +39,5 @@
.iconnav__label {
text-transform: uppercase;
font-weight: 700;
@include sectionColours();
@include mixins.sectionColours();
}
@@ -1,7 +1,10 @@
@use "breakpoints";
@use "mixins";
main {
padding-top: 96px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
padding-top: 140px;
}
}
@@ -10,7 +13,7 @@ main {
width: 100%;
padding-top: 32px;
padding-bottom: 32px;
@include clearfix();
@include mixins.clearfix();
&.nopad {
&--bottom {
@@ -23,18 +26,18 @@ main {
}
.content__title {
@include container();
@include mixins.container();
text-align: center;
}
.content__inner {
@include container();
@include mixins.container();
.content--has-sidebar & {
display: flex;
flex-wrap: wrap;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
flex-wrap: nowrap;
}
}
@@ -45,40 +48,40 @@ main {
padding: 0 0 32px;
overflow: hidden;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
padding: 0;
}
}
.content__plain {
@include clearfix();
@include mq($from: tablet) {
@include mixins.clearfix();
@include breakpoints.mq($from: tablet) {
padding-right: 96px;
}
}
.content__background {
@include clearfix();
@include sectionBackgrounds(0.15);
@include mixins.clearfix();
@include mixins.sectionBackgrounds(0.15);
padding: 24px 48px 24px 32px;
}
.content__float {
@include clearfix();
@include mixins.clearfix();
}
.content__sidebar {
width: 100%;
padding: 32px 0;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
flex: 0 0 320px;
padding: 0 0 0 32px;
}
}
.content__form {
@include sectionFills(0.15);
@include mixins.sectionFills(0.15);
width: 100%;
height: auto;
display: block;
@@ -93,7 +96,7 @@ main {
.desktop-only {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
}
}
@@ -1,4 +1,6 @@
@use "sass:math";
@use "variables" as *;
@use "colors" as *;
@mixin clearfix {
&::after {
@@ -1,3 +1,6 @@
@use "breakpoints";
@use "colors";
.mobilenav {
position: fixed;
z-index: 50;
@@ -7,10 +10,10 @@
height: 0;
padding-top: 96px;
overflow: hidden;
background: rgba($color-brand-secondary, 0.9);
background: rgba(colors.$color-brand-secondary, 0.9);
transition: height 0.25s ease-in-out;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
display: none;
}
@@ -1,3 +1,5 @@
@use "breakpoints";
.news-entry {
width: 100%;
&:not(:last-child) {
@@ -13,7 +15,7 @@
display: flex;
flex-direction: column;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
flex-direction: row;
}
}
@@ -22,7 +24,7 @@
width: 100%;
margin-bottom: 8px;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 50%;
}
}
@@ -39,7 +41,7 @@
.news-entry__teaser {
width: 100%;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
padding-left: 24px;
width: 50%;
}
@@ -1,3 +1,5 @@
@use "breakpoints";
.offerlist {
position: relative;
}
@@ -13,7 +15,7 @@
}
.offerlist__teasers {
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: flex;
flex-wrap: wrap;
}
@@ -24,13 +26,13 @@
text-decoration: none;
margin-bottom: 32px;
display: block;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
display: flex;
}
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 50%;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 33.3333%;
}
}
@@ -1,25 +1,30 @@
@use "breakpoints";
@use "colors";
@use "mixins";
@use "variables";
.page-footer {
width: 100%;
background: linear-gradient(to right, $color-brand-secondary, $color-brand-primary);
background: linear-gradient(to right, colors.$color-brand-secondary, colors.$color-brand-primary);
color: white;
padding-top: 16px;
padding-bottom: 16px;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
padding-top: 48px;
padding-bottom: 48px;
}
}
.page-footer__inner {
@include container($content-width-max);
@include mixins.container(variables.$content-width-max);
display: flex;
align-items: flex-start;
flex-wrap: wrap;
justify-content: center;
border-bottom: 1px solid white;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
padding-bottom: 48px;
}
}
@@ -33,14 +38,14 @@
text-align: left;
}
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 20%;
}
&--hide-mobile {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
}
}
@@ -60,14 +65,14 @@
}
.page-footer__bottom {
@include container($content-width-max);
@include mixins.container(variables.$content-width-max);
padding-top: 32px;
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: space-around;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
align-items: flex-start;
justify-content: space-between;
}
@@ -76,7 +81,7 @@
.page-footer__bottom__column {
width: 100%;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 33.3333%;
}
}
@@ -86,7 +91,7 @@
justify-content: center;
align-items: flex-start;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
justify-content: flex-start;
}
}
@@ -106,7 +111,7 @@
font-weight: 700;
text-align: center;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
text-align: left;
}
}
@@ -115,7 +120,7 @@
text-align: center;
padding-top: 32px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
text-align: right;
padding-top: 0;
}
@@ -138,7 +143,7 @@
text-align: center;
padding-top: 32px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
text-align: left;
padding-top: 0;
}
@@ -1,3 +1,7 @@
@use "breakpoints";
@use "colors";
@use "mixins";
.page-header {
width: 100%;
position: fixed;
@@ -5,28 +9,28 @@
left: 0;
z-index: 1000;
background: white;
box-shadow: 0 2px 2px rgba($color-background, 0.5);
box-shadow: 0 2px 2px rgba(colors.$color-background, 0.5);
}
.page-header__bar {
background: linear-gradient(to right, $color-brand-primary 50%, $color-brand-secondary);
background: linear-gradient(to right, colors.$color-brand-primary 50%, colors.$color-brand-secondary);
}
.page-header__bar__main {
@include container();
@include mixins.container();
color: white;
display: flex;
justify-content: center;
align-items: center;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
justify-content: space-between;
}
}
.page-header__bar__search {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
width: 50%;
}
@@ -37,7 +41,7 @@
justify-content: center;
align-items: center;
width: 100%;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 50%;
justify-content: flex-end;
}
@@ -53,14 +57,14 @@
.page-header__bar__divider {
display: none;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
display: inline-block;
padding: 12px 8px;
}
}
.page-header__main {
@include container();
@include mixins.container();
padding: 16px;
display: flex;
display: -ms-flexbox;
@@ -68,11 +72,11 @@
align-items: center;
-ms-flex-align: center;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
padding: 32px 16px 24px;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
justify-content: space-between;
align-items: baseline;
-ms-flex-align: end;
@@ -98,7 +102,7 @@
.page-header__sitenav {
display: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
display: block;
}
}
@@ -106,7 +110,7 @@
.page-header__button {
display: none;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
position: relative;
display: block;
min-width: 220px;
@@ -128,6 +132,6 @@
border: none;
& > polygon {
fill: $color-brand-primary;
fill: colors.$color-brand-primary;
}
}
@@ -1,3 +1,5 @@
@use "colors";
.paginator {
list-style: none;
margin: 0;
@@ -10,7 +12,7 @@
.paginator__item {
display: inline-block;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
padding: 4px;
text-decoration: none;
@@ -19,8 +21,8 @@
}
&--current {
border: 1px solid $color-brand-primary;
border: 1px solid colors.$color-brand-primary;
background-color: white;
color: $color-brand-primary;
color: colors.$color-brand-primary;
}
}
@@ -1,24 +1,27 @@
@use "breakpoints";
@use "mixins";
.searchresult {}
.searchresult__info {
@include container();
@include mixins.container();
}
.searchresult-item {
text-decoration: none;
margin-bottom: 32px;
display: block;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
display: flex;
}
}
.searchresult-item__card {
width: 100%;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
width: 240px;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 33.3333%;
}
}
@@ -27,8 +30,8 @@
margin: 0 8px;
padding: 32px;
color: white;
@include sectionBackgrounds();
@include mq($from: mobile) {
@include mixins.sectionBackgrounds();
@include breakpoints.mq($from: mobile) {
margin: 0;
flex: 1;
}
@@ -1,5 +1,8 @@
@use "breakpoints";
@use "mixins";
.sitenav {
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
padding-right: 64px;
}
}
@@ -25,7 +28,7 @@
&--active,
&:hover {
border-bottom: 3px solid;
@include sectionColours();
@include mixins.sectionColours();
}
}
@@ -1,3 +1,5 @@
@use "breakpoints";
.slider {}
.slider__arrow {
@@ -38,7 +40,7 @@
top: 30%;
}
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 16px;
height: 16px;
}
@@ -1,11 +1,14 @@
@use "breakpoints";
@use "mixins";
.statement {
@include container();
@include mixins.container();
padding-top: 32px;
padding-bottom: 48px;
}
.statement__inner {
@include sectionBackgrounds();
@include mixins.sectionBackgrounds();
box-shadow: 0 5px 10px rgba(black, 0.2);
text-align: center;
padding-top: 48px;
@@ -18,7 +21,7 @@
font-size: 24px;
line-height: 105%;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 48px;
}
}
@@ -1,3 +1,6 @@
@use "breakpoints";
@use "colors";
.team {
display: flex;
justify-content: space-between;
@@ -12,11 +15,11 @@
max-width: 400px;
padding: 0 16px 64px;
@include mq($until: desktop) {
@include breakpoints.mq($until: desktop) {
margin: 0 auto;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 50%;
max-width: 100%;
}
@@ -57,10 +60,10 @@
.team__position {
display: block;
color: $color-brand-primary;
color: colors.$color-brand-primary;
}
.team__contact__link {
text-decoration: none;
color: $color-brand-primary;
color: colors.$color-brand-primary;
}
@@ -1,12 +1,15 @@
@use "breakpoints";
@use "mixins";
.teasers {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
@include sectionBackgrounds(0.15);
@include mixins.sectionBackgrounds(0.15);
margin: 0 -16px 0;
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
flex-direction: row;
}
}
@@ -19,15 +22,15 @@
cursor: pointer;
}
@include mq($until: tablet) {
@include breakpoints.mq($until: tablet) {
padding-bottom: 16px;
}
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 50%;
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 33.3333%;
}
}
@@ -40,12 +43,12 @@
}
.teaser__caption {
@include sectionBackgroundsFromParent();
@include mixins.sectionBackgroundsFromParent();
padding: 16px 16px 0;
}
.teaser__form {
@include sectionFills();
@include mixins.sectionFills();
width: 100%;
height: auto;
display: block;
@@ -1,17 +1,20 @@
@use "breakpoints";
@use "colors";
.testimonial {
width: 100%;
padding: 0 32px;
text-align: center;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 80%;
width: 50%;
&:not(:last-child) {
border-right: 1px solid $color-divider;
border-right: 1px solid colors.$color-divider;
}
}
@include mq($from: desktop) {
@include breakpoints.mq($from: desktop) {
width: 25%;
}
}
@@ -1,3 +1,7 @@
@use "breakpoints";
@use "colors";
@use "mixins";
.tiles {
padding-bottom: 0;
}
@@ -15,7 +19,7 @@
padding: 16px;
text-decoration: none;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 50%;
padding: 16px;
}
@@ -26,12 +30,12 @@
background-size: cover;
background-position: center;
@include mq($from: mobile) {
@include breakpoints.mq($from: mobile) {
min-height: 250px;
padding: 32px;
}
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
padding: 32px 32px 0;
min-height: 375px;
}
@@ -42,33 +46,33 @@
color: white;
text-align: center;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
width: 70%;
margin: 0 auto;
}
}
.tile__caption__inner {
@include sectionBackgrounds(0.75);
@include mixins.sectionBackgrounds(0.75);
width: 100%;
padding: 24px 0;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
padding: 32px 0;
.tile:hover .section-incentives & {
background-color: $color-incentives;
background-color: colors.$color-incentives;
}
.tile:hover .section-teambuilding & {
background-color: $color-teambuilding;
background-color: colors.$color-teambuilding;
}
.tile:hover .section-meetings & {
background-color: $color-meetings;
background-color: colors.$color-meetings;
}
.tile:hover .section-events & {
background-color: $color-events;
background-color: colors.$color-events;
}
}
}
@@ -77,7 +81,7 @@
display: none;
padding: 16px 32px 0;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
.tile:hover & {
display: block;
}
@@ -91,10 +95,10 @@
margin-top: -1px;
polygon {
@include sectionFills();
@include mixins.sectionFills();
}
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
.tile:hover & {
display: block;
}
@@ -114,7 +118,7 @@
font-weight: 700;
min-height: 54px;
@include mq($from: tablet) {
@include breakpoints.mq($from: tablet) {
font-size: 24px;
}
}
@@ -1,5 +1,7 @@
@use "mixins";
.video {
@include container();
@include mixins.container();
padding-top: 32px;
padding-bottom: 32px;
}
@@ -1,39 +1,39 @@
@import "variables";
@import "mixins";
@import "breakpoints";
@use "variables";
@use "mixins";
@use "breakpoints";
@import "colors";
@import "fonts";
@use "colors";
@use "fonts";
@import "base";
@import "buttons";
@import "page-header";
@import "page-footer";
@import "layout";
@import "sitenav";
@import "helpernav";
@import "mobilenav";
@import "herounit";
@import "carousel";
@import "slider";
@import "configurator";
@import "statement";
@import "testimonial";
@import "brands";
@import "iconbar";
@import "tiles";
@import "card";
@import "box";
@import "banner";
@import "iconnav";
@import "forms";
@import "teasers";
@import "badge";
@import "team";
@import "search";
@import "offerlist";
@import "paginator";
@import "news";
@import "datepicker";
@import "cookiefirst";
@import "video";
@use "base";
@use "buttons";
@use "page-header";
@use "page-footer";
@use "layout";
@use "sitenav";
@use "helpernav";
@use "mobilenav";
@use "herounit";
@use "carousel";
@use "slider";
@use "configurator";
@use "statement";
@use "testimonial";
@use "brands";
@use "iconbar";
@use "tiles";
@use "card";
@use "box";
@use "banner";
@use "iconnav";
@use "forms";
@use "teasers";
@use "badge";
@use "team";
@use "search";
@use "offerlist";
@use "paginator";
@use "news";
@use "datepicker";
@use "cookiefirst";
@use "video";
@@ -1,18 +1,14 @@
@import "mixins";
@import "colors";
@use "mixins";
@use "colors";
@font-face {
font-family: 'Cairo';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('../fonts/cairo-v2-latin-ext_latin-regular.eot'); /* IE9 Compat Modes */
src: local('Cairo'), local('Cairo-Regular'),
url('../fonts/cairo-v2-latin-ext_latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/cairo-v2-latin-ext_latin-regular.woff2') format('woff2'), /* Super Modern Browsers */
url('../fonts/cairo-v2-latin-ext_latin-regular.woff') format('woff'), /* Modern Browsers */
url('../fonts/cairo-v2-latin-ext_latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/cairo-v2-latin-ext_latin-regular.svg#Cairo') format('svg'); /* Legacy iOS */
url('../fonts/cairo-v2-latin-ext_latin-regular.woff2') format('woff2'),
url('../fonts/cairo-v2-latin-ext_latin-regular.woff') format('woff');
}
@font-face {
@@ -20,13 +16,9 @@
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('../fonts/cairo-v2-latin-ext_latin-700.eot'); /* IE9 Compat Modes */
src: local('Cairo Bold'), local('Cairo-Bold'),
url('../fonts/cairo-v2-latin-ext_latin-700.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/cairo-v2-latin-ext_latin-700.woff2') format('woff2'), /* Super Modern Browsers */
url('../fonts/cairo-v2-latin-ext_latin-700.woff') format('woff'), /* Modern Browsers */
url('../fonts/cairo-v2-latin-ext_latin-700.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/cairo-v2-latin-ext_latin-700.svg#Cairo') format('svg'); /* Legacy iOS */
url('../fonts/cairo-v2-latin-ext_latin-700.woff2') format('woff2'),
url('../fonts/cairo-v2-latin-ext_latin-700.woff') format('woff');
}
$font-main: 'Cairo';
@@ -34,12 +26,8 @@ $font-main: 'Cairo';
@font-face {
font-family: 'fontello';
font-display: swap;
src: url('../fonts/fontello.eot?39986861');
src: url('../fonts/fontello.eot?39986861#iefix') format('embedded-opentype'),
url('../fonts/fontello.woff2?39986861') format('woff2'),
url('../fonts/fontello.woff?39986861') format('woff'),
url('../fonts/fontello.ttf?39986861') format('truetype'),
url('../fonts/fontello.svg?39986861#fontello') format('svg');
src: url('../fonts/fontello.woff2?39986861') format('woff2'),
url('../fonts/fontello.woff?39986861') format('woff');
font-weight: normal;
font-style: normal;
}
@@ -123,7 +111,7 @@ ul {
left: 0;
content: "\25CF";
font-size: 18px;
@include sectionColoursFromParent();
@include mixins.sectionColoursFromParent();
}
}
}
@@ -141,8 +129,8 @@ p {
hr {
max-width: 25%;
margin: 32px auto 32px 0;
color: $color-ruler;
background-color: $color-ruler;
color: colors.$color-ruler;
background-color: colors.$color-ruler;
height: 1px;
border: none;
}
@@ -158,7 +146,7 @@ h3,
}
.headline {
@include sectionColoursFromParent();
@include mixins.sectionColoursFromParent();
&--icon {
display: flex;
@@ -192,9 +180,9 @@ h1,
display: block;
font-size: 16px;
line-height: 120%;
color: $color-brand-primary;
color: colors.$color-brand-primary;
text-transform: none;
@include sectionColoursFromParent();
@include mixins.sectionColoursFromParent();
&--box {
color: white;
@@ -229,7 +217,7 @@ h3 {
&--default {
display: inline-block;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
padding: 4px 16px;
}
@@ -237,7 +225,7 @@ h3 {
&--page-header {
display: block;
min-width: 186px;
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
font-size: 18px;
padding: 0 32px 0 24px;
@@ -250,8 +238,8 @@ h3 {
display: block;
min-width: 220px;
text-align: center;
background-color: $color-brand-primary;
@include sectionBackgroundsFromParent();
background-color: colors.$color-brand-primary;
@include mixins.sectionBackgroundsFromParent();
color: white;
line-height: 48px;
border: none;
@@ -271,7 +259,7 @@ h3 {
&:hover {
background: white;
color: $color-font-main;
color: colors.$color-font-main;
}
}
@@ -280,7 +268,7 @@ h3 {
}
&--icon {
background-color: $color-brand-primary;
background-color: colors.$color-brand-primary;
color: white;
width: 16px;
height: 16px;
@@ -88,14 +88,14 @@ class DateCommandController extends Command
public function execute(InputInterface $input, OutputInterface $output): int
{
$importSource = $this->importSourceFactory->get();
$path = $importSource->acquire();
if ($path === null) {
$import = $importSource->acquire();
if ($import === null) {
$output->writeln('No new import available.');
return 0;
}
$count = $this->dateImportService->import($path);
$importSource->markImported($path);
$count = $this->dateImportService->import($import->getRows());
$importSource->markImported($import);
$output->writeln(sprintf('%d rows imported.', $count ));
$settings = $this->getSettings();
$resellerPageUid = $settings['resellerExportPageUid'];
@@ -0,0 +1,165 @@
<?php
namespace EP\EpProducts\ContentFeed;
use EP\EpProducts\Http\ApiKeyAuthenticator;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* The chatbot content feed's backchannel endpoints under /api/content/.
*
* See .ddev/plans/CHATBOT-MCP-01-TYPO3-CONTENT-FEED.md.
*/
class ContentFeedApi
{
public const PATH_PREFIX = '/api/content/';
private const MANIFEST_CACHE_IDENTIFIER = 'content_feed_manifest';
// The consumer polls every 15 minutes, so this caps the build at once per poll however
// often it retries. Edits reach the chatbot within about 25 minutes.
private const MANIFEST_CACHE_LIFETIME = 600;
private const MAX_RECORDS_PER_REQUEST = 100;
private const DISABLED_RETRY_AFTER = 3600;
private const JSON_FLAGS = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
/**
* @var ApiKeyAuthenticator
*/
private $authenticator;
/**
* @var ContentFeedConfiguration
*/
private $configuration;
/**
* @var ManifestBuilder
*/
private $manifestBuilder;
/**
* @var RecordSerializer
*/
private $recordSerializer;
/**
* @var FrontendInterface
*/
private $cache;
public function __construct(
ApiKeyAuthenticator $authenticator,
ContentFeedConfiguration $configuration,
ManifestBuilder $manifestBuilder,
RecordSerializer $recordSerializer,
CacheManager $cacheManager
) {
$this->authenticator = $authenticator;
$this->configuration = $configuration;
$this->manifestBuilder = $manifestBuilder;
$this->recordSerializer = $recordSerializer;
$this->cache = $cacheManager->getCache('ep_products_cache');
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
if (!$this->authenticator->isAuthorized($request)) {
return $this->error('Invalid or missing api key', 403);
}
if (!$this->configuration->isEnabled()) {
return self::disabledResponse();
}
if ([] === $this->configuration->getSites()) {
// An empty feed would read as "everything was deleted". Refuse instead.
return $this->error('Content feed has no sites configured', 503);
}
$path = substr($request->getUri()->getPath(), strlen(self::PATH_PREFIX));
if ('manifest' === $path) {
return new JsonResponse($this->getManifest(), 200, [], self::JSON_FLAGS);
}
if ('records' === $path) {
return $this->handleRecordsRequest($request);
}
return $this->error('Not found', 404);
}
/**
* Uids that are not (or no longer) eligible are left out rather than answered with an error:
* the manifest may have changed between the consumer's two calls, and it reads a requested
* but absent uid as deleted.
*/
private function handleRecordsRequest(ServerRequestInterface $request): ResponseInterface
{
$type = (string) ($request->getQueryParams()['type'] ?? '');
if (!isset(RecordFinder::TYPES[$type])) {
return $this->error('Unknown type, expected one of: ' . implode(', ', array_keys(RecordFinder::TYPES)), 400);
}
$uids = array_values(array_unique(array_filter(
GeneralUtility::intExplode(',', (string) ($request->getQueryParams()['uids'] ?? ''), true),
function (int $uid): bool {
return $uid > 0;
}
)));
if ([] === $uids) {
return $this->error('No uids given', 400);
}
if (count($uids) > self::MAX_RECORDS_PER_REQUEST) {
return $this->error(sprintf('At most %d uids per request', self::MAX_RECORDS_PER_REQUEST), 400);
}
return new JsonResponse([
'type' => $type,
'items' => $this->recordSerializer->serialize($type, $uids),
], 200, [], self::JSON_FLAGS);
}
private function getManifest(): array
{
$manifest = $this->cache->get(self::MANIFEST_CACHE_IDENTIFIER);
if (!is_array($manifest)) {
$manifest = $this->manifestBuilder->build();
$this->cache->set(self::MANIFEST_CACHE_IDENTIFIER, $manifest, [], self::MANIFEST_CACHE_LIFETIME);
}
return $manifest;
}
/**
* The kill switch: contentFeedEnabled = 0 in the extension configuration, for when the host
* is struggling. The consumer stops its run, keeps everything it has and tries again later -
* nothing is deleted on the chatbot side.
*/
public static function disabledResponse(): ResponseInterface
{
return new JsonResponse(
['message' => 'Content feed is switched off'],
503,
['Retry-After' => (string) self::DISABLED_RETRY_AFTER],
self::JSON_FLAGS
);
}
private function error(string $message, int $status): ResponseInterface
{
return new JsonResponse(['message' => $message], $status, [], self::JSON_FLAGS);
}
}
@@ -0,0 +1,75 @@
<?php
namespace EP\EpProducts\ContentFeed;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* The chatbot content feed's extension configuration.
*
* Missing keys fall back to "feed is on, but covers nothing": a key added to ext_conf_template.txt
* is absent until the extension configuration is saved in the backend, and an empty feed is
* refused by the consumer rather than read as "everything was deleted".
*/
class ContentFeedConfiguration
{
/**
* @var array
*/
private $configuration;
public function __construct(ExtensionConfiguration $extensionConfiguration)
{
$this->configuration = (array) $extensionConfiguration->get('ep_products');
}
public function isEnabled(): bool
{
return (bool) ($this->configuration['contentFeedEnabled'] ?? true);
}
/**
* @return string[] site identifiers
*/
public function getSites(): array
{
return GeneralUtility::trimExplode(',', (string) ($this->configuration['contentFeedSites'] ?? ''), true);
}
/**
* @return int[] language ids; the default language when unset
*/
public function getLanguages(): array
{
$languages = GeneralUtility::intExplode(',', (string) ($this->configuration['contentFeedLanguages'] ?? '0'), true);
return [] === $languages ? [0] : $languages;
}
/**
* @return int[] page uids whose whole subtree stays out of the feed
*/
public function getExcludedPages(): array
{
return GeneralUtility::intExplode(',', (string) ($this->configuration['contentFeedExcludedPages'] ?? ''), true);
}
/**
* @return array<string, int> site identifier => news detail page uid
*/
public function getNewsDetailPages(): array
{
$pages = [];
foreach (GeneralUtility::trimExplode(',', (string) ($this->configuration['contentFeedNewsDetailPages'] ?? ''), true) as $entry) {
$parts = GeneralUtility::trimExplode(':', $entry, true);
if (2 === count($parts) && (int) $parts[1] > 0) {
$pages[$parts[0]] = (int) $parts[1];
}
}
return $pages;
}
}
@@ -0,0 +1,379 @@
<?php
namespace EP\EpProducts\ContentFeed;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Site\Entity\Site;
/**
* Builds GET /api/content/manifest: everything the content feed publishes, with a modification
* marker per item and no bodies. The list is complete - an item missing from it is gone - so the
* consumer never has to infer deletions from timestamps.
*
* See .ddev/plans/CHATBOT-MCP-01-TYPO3-CONTENT-FEED.md §4.
*/
class ManifestBuilder
{
public const CONTENT_PAGE_TYPE = 1730;
private const DOKTYPE_DEFAULT = 1;
// Recycler and backend user section: nothing below them is public.
private const DOKTYPES_NOT_TRAVERSED = [6, 255];
// l18n_cfg bit 1: "hide default translation of page".
private const L18N_HIDE_DEFAULT_LANGUAGE = 1;
private const RECORD_FIELDS = [
'product' => ['uid', 'tstamp', 'detail_page'],
'hotel' => ['uid', 'tstamp', 'detail_page'],
'region' => ['uid', 'tstamp', 'detail_page'],
'country' => ['uid', 'tstamp', 'detail_page'],
'city' => ['uid', 'tstamp', 'detail_page'],
'concept' => ['uid', 'tstamp', 'detail_page'],
'news' => ['uid', 'tstamp', 'pid'],
];
/**
* @var PageTree
*/
private $pageTree;
/**
* @var UrlResolver
*/
private $urlResolver;
/**
* @var RecordFinder
*/
private $recordFinder;
/**
* @var ContentFeedConfiguration
*/
private $configuration;
/**
* @var ConnectionPool
*/
private $connectionPool;
public function __construct(
PageTree $pageTree,
UrlResolver $urlResolver,
RecordFinder $recordFinder,
ContentFeedConfiguration $configuration,
ConnectionPool $connectionPool
) {
$this->pageTree = $pageTree;
$this->urlResolver = $urlResolver;
$this->recordFinder = $recordFinder;
$this->configuration = $configuration;
$this->connectionPool = $connectionPool;
}
public function build(): array
{
$sites = $this->urlResolver->getIncludedSites();
$records = $this->buildRecordItems();
return [
'generatedAt' => date('c'),
'sites' => array_map([$this, 'describeSite'], $sites),
'items' => array_merge($this->buildPageItems($sites, $this->collectDetailPages()), $records),
];
}
private function describeSite(Site $site): array
{
$languages = [];
foreach ($site->getLanguages() as $language) {
$languages[] = $language->getTwoLetterIsoCode();
}
$title = trim((string) ($site->getConfiguration()['websiteTitle'] ?? ''));
if ('' === $title) {
$title = trim($site->getDefaultLanguage()->getWebsiteTitle());
}
return [
'identifier' => $site->getIdentifier(),
'title' => '' !== $title ? $title : $site->getIdentifier(),
'base' => (string) $site->getBase(),
'languages' => $languages,
];
}
/**
* @param Site[] $sites
* @param array<int, array> $detailPages detailOf entries by page uid
*/
private function buildPageItems(array $sites, array $detailPages): array
{
$content = $this->findContentStatistics();
$excluded = array_flip($this->configuration->getExcludedPages());
$feedLanguages = $this->configuration->getLanguages();
$items = [];
foreach ($sites as $site) {
$languageIds = [];
foreach ($site->getLanguages() as $language) {
if (in_array($language->getLanguageId(), $feedLanguages, true)) {
$languageIds[$language->getLanguageId()] = $language->getTwoLetterIsoCode();
}
}
$context = [
'site' => $site,
'languages' => $languageIds,
'excluded' => $excluded,
'content' => $content,
'detailPages' => $detailPages,
];
$breadcrumbs = array_fill_keys(array_keys($languageIds), []);
$this->walk($site->getRootPageId(), $context, $breadcrumbs, true, $items);
}
return $items;
}
/**
* @param array<int, string[]> $breadcrumbs titles above this page, by language id
*/
private function walk(int $uid, array $context, array $breadcrumbs, bool $isRoot, array &$items): void
{
$page = $this->pageTree->getPage($uid);
if (null === $page || isset($context['excluded'][$uid])) {
return;
}
if (in_array((int) $page['doktype'], self::DOKTYPES_NOT_TRAVERSED, true)) {
return;
}
$visible = $this->pageTree->isVisible($page);
if (!$visible && (int) $page['extendToSubpages'] === 1) {
return;
}
$childBreadcrumbs = $breadcrumbs;
foreach ($context['languages'] as $languageId => $isoCode) {
$row = $this->getLanguageRow($page, $languageId);
if ($visible && null !== $row && $this->isPublishable($page, $row, $languageId)) {
$item = $this->buildPageItem($page, $row, $languageId, $isoCode, $breadcrumbs[$languageId], $context);
if (null !== $item) {
$items[] = $item;
}
}
if (!$isRoot) {
$source = $row ?? $page;
$childBreadcrumbs[$languageId][] = '' !== trim((string) $source['nav_title'])
? trim((string) $source['nav_title'])
: trim((string) $source['title']);
}
}
foreach ($this->pageTree->getChildren($uid) as $childUid) {
$this->walk($childUid, $context, $childBreadcrumbs, false, $items);
}
}
private function getLanguageRow(array $page, int $languageId): ?array
{
if (0 === $languageId) {
return $page;
}
$overlay = $this->pageTree->getOverlay((int) $page['uid'], $languageId);
return null !== $overlay && $this->pageTree->isVisible($overlay) ? $overlay : null;
}
/**
* Mirrors the XML sitemap: standard pages only, nothing marked no_index. If Google is not
* meant to see a page, the chatbot is not either.
*/
private function isPublishable(array $page, array $row, int $languageId): bool
{
if ((int) $page['doktype'] !== self::DOKTYPE_DEFAULT || (int) $row['no_index'] === 1) {
return false;
}
return 0 !== $languageId || 0 === ((int) $page['l18n_cfg'] & self::L18N_HIDE_DEFAULT_LANGUAGE);
}
private function buildPageItem(array $page, array $row, int $languageId, string $isoCode, array $breadcrumb, array $context): ?array
{
$uid = (int) $page['uid'];
// "Show content from page": the elements live on another page, and so do their changes.
// The site answers 404 when that page is hidden.
$contentPid = (int) $page['content_from_pid'] ?: $uid;
$contentPage = $this->pageTree->getPage($contentPid);
if (null === $contentPage || !$this->pageTree->isVisible($contentPage)) {
return null;
}
// Without a visible element other than plugins, the content-only render is empty (it
// leaves plugins out), so there is nothing to fetch. That is most product and hotel
// detail pages: their text comes through the records endpoint.
$content = $context['content'][$contentPid] ?? [];
$textElements = ($content[$languageId]['text'] ?? 0) + ($content[-1]['text'] ?? 0);
if (0 === $textElements) {
return null;
}
$url = $this->urlResolver->getPageUrl($uid, $languageId);
if (null === $url) {
return null;
}
$modified = max(
(int) $row['tstamp'],
$content[$languageId]['tstamp'] ?? 0,
$content[-1]['tstamp'] ?? 0
);
return [
'type' => 'page',
'uid' => $uid,
'language' => $isoCode,
'site' => $context['site']->getIdentifier(),
'url' => $url,
'contentUrl' => $this->urlResolver->getPageUrl($uid, $languageId, ['type' => self::CONTENT_PAGE_TYPE]),
'title' => trim((string) $row['title']),
'description' => $this->nullIfEmpty((string) $row['description']),
'breadcrumb' => $breadcrumb,
'detailOf' => $context['detailPages'][$uid] ?? [],
'modified' => date('c', $modified),
];
}
/**
* Per page and language: the latest change to any content element, and how many visible
* elements are not plugins.
* Deleted and hidden elements count towards the change - removing or hiding one changes the
* page - which is also why SYS_LASTCHANGED is no use here: it only moves on render.
*
* @return array<int, array<int, array{tstamp: int, text: int}>>
*/
private function findContentStatistics(): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tt_content');
$queryBuilder->getRestrictions()->removeAll();
$rows = $queryBuilder
->selectLiteral(
'pid',
'sys_language_uid',
'MAX(tstamp) AS tstamp',
"SUM(CASE WHEN deleted = 0 AND hidden = 0 AND CType <> 'list' THEN 1 ELSE 0 END) AS text_elements"
)
->from('tt_content')
->groupBy('pid', 'sys_language_uid')
->execute()
->fetchAllAssociative()
;
$statistics = [];
foreach ($rows as $row) {
$statistics[(int) $row['pid']][(int) $row['sys_language_uid']] = [
'tstamp' => (int) $row['tstamp'],
'text' => (int) $row['text_elements'],
];
}
return $statistics;
}
/**
* Which records name a page as their detail page. Keyed by the page the record points at,
* not by where a shortcut leads: a shortcut is not in the manifest, and the page it leads to
* usually describes something broader (product detail shortcuts point at region pages).
*
* @return array<int, array>
*/
private function collectDetailPages(): array
{
$detailPages = [];
foreach (self::RECORD_FIELDS as $type => $fields) {
if (!in_array('detail_page', $fields, true)) {
continue;
}
foreach ($this->recordFinder->find($type, ['uid', 'detail_page']) as $uid => $row) {
$pageUid = $this->urlResolver->parsePageReference((string) $row['detail_page']);
if (null !== $pageUid) {
$detailPages[$pageUid][] = ['type' => $type, 'uid' => $uid];
}
}
}
return $detailPages;
}
private function buildRecordItems(): array
{
$faqTimestamps = $this->recordFinder->findFaqTimestamps();
$matchcodeTimestamps = $this->recordFinder->findMatchcodeTimestamps();
$items = [];
foreach (self::RECORD_FIELDS as $type => $fields) {
foreach ($this->recordFinder->find($type, $fields) as $uid => $row) {
if ('news' === $type) {
$link = $this->urlResolver->getNewsLink((int) $row['uid'], (int) $row['pid']);
// News has no detail_page of its own: an article stored outside the feed's
// sites (the retired ep-events) is not part of the feed at all.
if (null === $link) {
continue;
}
} else {
$link = $this->urlResolver->getRecordLink((string) $row['detail_page']);
}
$modified = (int) $row['tstamp'];
if ('product' === $type) {
$modified = max($modified, $faqTimestamps[$uid] ?? 0);
}
if ('hotel' === $type) {
$modified = max($modified, $matchcodeTimestamps[$uid] ?? 0);
}
$items[] = [
'type' => $type,
'uid' => $uid,
'language' => 'de',
'site' => $link['site'],
'url' => $link['url'],
'modified' => date('c', $modified),
];
}
}
return $items;
}
private function nullIfEmpty(string $value): ?string
{
$value = trim($value);
return '' === $value ? null : $value;
}
}
@@ -0,0 +1,131 @@
<?php
namespace EP\EpProducts\ContentFeed;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
/**
* The whole page table in memory, for the content feed's tree walk and shortcut resolution.
*
* About 2 900 rows: one query and a PHP walk is far cheaper than a query per tree level.
* Visibility is evaluated here, not in SQL, because a hidden page still has to be traversed
* (its subpages stay reachable unless extendToSubpages is set).
*/
class PageTree
{
private const FIELDS = [
'uid', 'pid', 'sorting', 'doktype', 'hidden', 'starttime', 'endtime', 'fe_group',
'extendToSubpages', 'no_index', 'title', 'nav_title', 'description', 'shortcut',
'shortcut_mode', 'content_from_pid', 'tstamp', 'sys_language_uid', 'l10n_parent', 'l18n_cfg',
];
/**
* @var ConnectionPool
*/
private $connectionPool;
/**
* @var int
*/
private $now;
/**
* @var array<int, array>|null default-language rows by uid
*/
private $pages;
/**
* @var array<int, int[]> child uids by parent uid, in sorting order
*/
private $children = [];
/**
* @var array<int, array<int, array>> overlay rows by default-language uid and language id
*/
private $overlays = [];
public function __construct(ConnectionPool $connectionPool, Context $context)
{
$this->connectionPool = $connectionPool;
$this->now = (int) $context->getPropertyFromAspect('date', 'timestamp');
}
public function getPage(int $uid): ?array
{
$this->load();
return $this->pages[$uid] ?? null;
}
public function getOverlay(int $uid, int $languageId): ?array
{
$this->load();
return $this->overlays[$uid][$languageId] ?? null;
}
/**
* @return int[]
*/
public function getChildren(int $uid): array
{
$this->load();
return $this->children[$uid] ?? [];
}
/**
* Visible to an anonymous frontend visitor: not hidden, inside its start/end window, and not
* restricted to a frontend user group.
*/
public function isVisible(array $row): bool
{
if ((int) $row['hidden'] === 1) {
return false;
}
if ((int) $row['starttime'] > $this->now) {
return false;
}
if ((int) $row['endtime'] !== 0 && (int) $row['endtime'] <= $this->now) {
return false;
}
return in_array((string) $row['fe_group'], ['', '0'], true);
}
private function load(): void
{
if (null !== $this->pages) {
return;
}
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll()->add(new DeletedRestriction());
$rows = $queryBuilder
->select(...self::FIELDS)
->from('pages')
->orderBy('sorting')
->execute()
->fetchAllAssociative()
;
$this->pages = [];
foreach ($rows as $row) {
$uid = (int) $row['uid'];
if ((int) $row['sys_language_uid'] > 0) {
$this->overlays[(int) $row['l10n_parent']][(int) $row['sys_language_uid']] = $row;
continue;
}
$this->pages[$uid] = $row;
$this->children[(int) $row['pid']][] = $uid;
}
}
}
@@ -0,0 +1,152 @@
<?php
namespace EP\EpProducts\ContentFeed;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
/**
* Which records the content feed publishes. The manifest and the records endpoint both go
* through here, so a uid the manifest lists is exactly a uid the records endpoint returns.
*
* The default restrictions apply: deleted, hidden, starttime and endtime.
*/
class RecordFinder
{
public const TYPES = [
'product' => 'tx_epproducts_domain_model_product',
'hotel' => 'tx_epproducts_domain_model_hotel',
'region' => 'tx_epproducts_domain_model_region',
'country' => 'tx_epproducts_domain_model_country',
'city' => 'tx_epproducts_domain_model_city',
'concept' => 'tx_epproducts_domain_model_concept',
'news' => 'tx_news_domain_model_news',
];
/**
* @var ConnectionPool
*/
private $connectionPool;
public function __construct(ConnectionPool $connectionPool)
{
$this->connectionPool = $connectionPool;
}
/**
* @param string[] $fields
* @param int[]|null $uids null for all eligible records
* @return array<int, array> rows by uid, in uid order
*/
public function find(string $type, array $fields, ?array $uids = null): array
{
$table = self::TYPES[$type];
$queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
$queryBuilder
->select(...$fields)
->from($table)
->where($queryBuilder->expr()->in('sys_language_uid', [0, -1]))
->orderBy('uid')
;
if (null !== $uids) {
if ([] === $uids) {
return [];
}
$queryBuilder->andWhere($queryBuilder->expr()->in(
'uid',
$queryBuilder->createNamedParameter($uids, Connection::PARAM_INT_ARRAY)
));
}
$this->addTypeConstraints($type, $queryBuilder);
$rows = [];
foreach ($queryBuilder->execute()->fetchAllAssociative() as $row) {
$rows[(int) $row['uid']] = $row;
}
return $rows;
}
/**
* Latest change to a product's FAQs, by product uid. Deleted and hidden FAQs count: removing
* one is a change to the product's text.
*
* @return array<int, int>
*/
public function findFaqTimestamps(): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_faq');
$queryBuilder->getRestrictions()->removeAll();
$rows = $queryBuilder
->selectLiteral('mm.uid_local AS product', 'MAX(faq.tstamp) AS tstamp')
->from('tx_epproducts_product_faq_mm', 'mm')
->join('mm', 'tx_epproducts_domain_model_faq', 'faq', 'faq.uid = mm.uid_foreign')
->groupBy('mm.uid_local')
->execute()
->fetchAllAssociative()
;
return $this->indexTimestamps($rows, 'product');
}
/**
* Latest change to a hotel's matchcode aliases, by hotel uid. They are part of the hotel's
* `codes`, which the consumer joins its trip data on.
*
* @return array<int, int>
*/
public function findMatchcodeTimestamps(): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_matchcode');
$queryBuilder->getRestrictions()->removeAll();
$rows = $queryBuilder
->selectLiteral('entity AS hotel', 'MAX(tstamp) AS tstamp')
->from('tx_epproducts_domain_model_matchcode')
->where($queryBuilder->expr()->eq('entity_type', $queryBuilder->createNamedParameter('hotel')))
->groupBy('entity')
->execute()
->fetchAllAssociative()
;
return $this->indexTimestamps($rows, 'hotel');
}
/**
* @return array<int, int>
*/
private function indexTimestamps(array $rows, string $key): array
{
$timestamps = [];
foreach ($rows as $row) {
$timestamps[(int) $row[$key]] = (int) $row['tstamp'];
}
return $timestamps;
}
private function addTypeConstraints(string $type, QueryBuilder $queryBuilder): void
{
$expr = $queryBuilder->expr();
if ('product' === $type) {
// A product that is neither searchable nor bookable is an internal record.
$queryBuilder->andWhere($expr->orX($expr->eq('searchable', 1), $expr->eq('bookable', 1)));
}
if ('news' === $type) {
// Type 0 is a regular article; 1 and 2 are just links to a page or an external URL.
$queryBuilder->andWhere(
$expr->eq('type', $queryBuilder->createNamedParameter('0')),
$expr->in('fe_group', $queryBuilder->createNamedParameter(['', '0'], Connection::PARAM_STR_ARRAY))
);
}
}
}
@@ -0,0 +1,513 @@
<?php
namespace EP\EpProducts\ContentFeed;
use EP\EpProducts\Utility\HotelIconUtility;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
/**
* Builds GET /api/content/records: the editorial content of products, hotels, destinations,
* concepts and blog articles. Filter attributes and text only - no dates, prices or images.
* Dates and prices are the consumer's own data; images play no part in a text chatbot.
*
* Rich-text fields go out as stored HTML with `t3://` links resolved; the consumer converts
* them to Markdown together with the rendered pages, so there is one HTML-to-text step.
*
* See .ddev/plans/CHATBOT-MCP-01-TYPO3-CONTENT-FEED.md §5.
*/
class RecordSerializer
{
/**
* @var RecordFinder
*/
private $recordFinder;
/**
* @var UrlResolver
*/
private $urlResolver;
/**
* @var RteLinkResolver
*/
private $rteLinkResolver;
/**
* @var ConnectionPool
*/
private $connectionPool;
public function __construct(
RecordFinder $recordFinder,
UrlResolver $urlResolver,
RteLinkResolver $rteLinkResolver,
ConnectionPool $connectionPool
) {
$this->recordFinder = $recordFinder;
$this->urlResolver = $urlResolver;
$this->rteLinkResolver = $rteLinkResolver;
$this->connectionPool = $connectionPool;
}
/**
* @param int[] $uids
* @return array[] one item per eligible uid; ineligible uids are left out
*/
public function serialize(string $type, array $uids): array
{
$rows = $this->recordFinder->find($type, ['*'], $uids);
if ([] === $rows) {
return [];
}
switch ($type) {
case 'product':
return $this->serializeProducts($rows);
case 'hotel':
return $this->serializeHotels($rows);
case 'news':
return $this->serializeNews($rows);
default:
return array_values(array_map(function (array $row) use ($type): array {
return $this->serializeDestination($type, $row);
}, $rows));
}
}
private function serializeProducts(array $rows): array
{
$uids = array_keys($rows);
$hotels = $this->findMmUids('tx_epproducts_product_hotel_mm', 'uid_local', 'uid_foreign', $uids);
$regions = $this->findMmUids('tx_epproducts_product_region_mm', 'uid_local', 'uid_foreign', $uids);
$faqs = $this->findFaqs($uids);
$faqTimestamps = $this->recordFinder->findFaqTimestamps();
$infoboxes = $this->findInfoboxTexts(array_column($rows, 'non_bookable_info'));
$items = [];
foreach ($rows as $uid => $row) {
$season = trim((string) $row['season']);
$items[] = $this->withLink($row, max((int) $row['tstamp'], $faqTimestamps[$uid] ?? 0)) + [
'code' => $this->text($row['code']),
'busProId' => (int) $row['bus_pro_id'] ?: null,
'name' => $this->text($row['name']),
'subline' => $this->text($row['subline']),
'headline' => $this->text($row['headline']),
'season' => '' === $season ? 'w' : $season,
'daytrip' => (bool) $row['daytrip'],
'bookable' => (bool) $row['bookable'],
'searchable' => (bool) $row['searchable'],
'skipassIncluded' => (bool) $row['skipass_included'],
'conceptUid' => (int) $row['concept'] ?: null,
'countryUid' => (int) $row['country'] ?: null,
'regionUid' => (int) $row['region'] ?: null,
'cityUid' => (int) $row['city'] ?: null,
'additionalRegionUids' => $regions[$uid] ?? [],
'hotelUids' => $hotels[$uid] ?? [],
'keywords' => $this->text($row['keywords']),
'text' => [
'teaser' => $this->html($row['teaser']),
'teaserLong' => $this->html($row['teaser_long']),
'feature' => $this->text($row['feature']),
'conceptDescription' => $this->html($row['concept_description']),
'boardDescription' => $this->html($row['board_description']),
'includedServices' => $this->html($row['included_services']),
'additionalServices' => $this->html($row['additional_services']),
'programmeDescription' => $this->html($row['programme_description']),
'skiPassDescription' => $this->html($row['ski_pass_description']),
'nonBookableInfo' => $infoboxes[(int) $row['non_bookable_info']] ?? null,
],
'faqs' => $faqs[$uid] ?? [],
];
}
return $items;
}
private function serializeHotels(array $rows): array
{
$uids = array_keys($rows);
$aliases = $this->findMatchcodes($uids);
$matchcodeTimestamps = $this->recordFinder->findMatchcodeTimestamps();
$products = $this->findMmUids('tx_epproducts_product_hotel_mm', 'uid_foreign', 'uid_local', $uids, 'sorting_foreign');
$eligibleProducts = $this->recordFinder->find('product', ['uid'], array_values(array_unique(array_merge([], ...array_values($products)))));
$items = [];
foreach ($rows as $uid => $row) {
$code = trim((string) $row['code']);
$codes = array_values(array_unique(array_filter(array_merge([$code], $aliases[$uid] ?? []), 'strlen')));
$items[] = $this->withLink($row, max((int) $row['tstamp'], $matchcodeTimestamps[$uid] ?? 0)) + [
'code' => '' === $code ? null : $code,
'codes' => $codes,
'name' => $this->text($row['name']),
'shortName' => $this->text($row['short_name']),
'headline' => $this->text($row['headline']),
'type' => (int) $row['type'],
'category' => (int) $row['category'],
'new' => (bool) $row['new'],
'earlybird' => (bool) $row['earlybird'],
'countryUid' => (int) $row['country'] ?: null,
'regionUid' => (int) $row['region'] ?: null,
'cityUid' => (int) $row['city'] ?: null,
'productUids' => array_values(array_filter($products[$uid] ?? [], function (int $productUid) use ($eligibleProducts): bool {
return isset($eligibleProducts[$productUid]);
})),
'address' => $this->text($row['address']),
'latitude' => $this->text($row['latitude']),
'longitude' => $this->text($row['longitude']),
'facts' => [
'bedsCount' => (int) $row['beds_count'] ?: null,
'parkingCount' => (int) $row['parking_count'] ?: null,
'altitude' => $this->text($row['altitude']),
'distanceBus' => $this->text($row['distance_bus']),
'distanceLift' => $this->text($row['distance_lift']),
'shower' => $this->text($row['shower']),
'partyroom' => (bool) $row['partyroom'],
'gamesroom' => (bool) $row['gamesroom'],
'sauna' => (bool) $row['sauna'],
'wifi' => (bool) $row['wifi'],
],
'icons' => HotelIconUtility::getIcons($row),
'keywords' => $this->text($row['keywords']),
'text' => [
'teaser' => $this->html($row['teaser']),
'description' => $this->html($row['description']),
'features' => $this->html($row['features']),
'roomTypes' => $this->html($row['room_types']),
'additionalInformation' => $this->html($row['additional_information']),
],
];
}
return $items;
}
private function serializeDestination(string $type, array $row): array
{
$item = $this->withLink($row, (int) $row['tstamp']) + [
'name' => $this->text($row['name']),
'headline' => $this->text($row['headline']),
];
switch ($type) {
case 'region':
return $item + [
'season' => $this->text($row['season']),
'keywords' => $this->text($row['keywords']),
'countryUid' => (int) $row['country'] ?: null,
'facts' => [
'length' => $this->text($row['length']),
'height' => $this->text($row['height']),
'lifts' => $this->text($row['lifts']),
],
'webcam' => $this->findWebcamUrl((int) $row['webcam']),
'text' => [
'teaser' => $this->html($row['teaser']),
'description' => $this->html($row['description']),
'feature' => $this->text($row['feature']),
'skiArea' => $this->html($row['ski_area']),
'skiAreaExtended' => $this->html($row['ski_area_extended']),
'skiPass' => $this->html($row['ski_pass']),
'news' => $this->html($row['news']),
],
];
case 'country':
return $item + [
'code' => $this->text($row['code']),
'season' => $this->text($row['season']),
'keywords' => $this->text($row['keywords']),
'text' => [
'teaser' => $this->html($row['teaser']),
'description' => $this->html($row['description']),
'descriptionExtended' => $this->html($row['description_extended']),
],
];
case 'city':
return $item + [
'season' => $this->text($row['season']),
'keywords' => $this->text($row['keywords']),
'countryUid' => (int) $row['country'] ?: null,
'regionUid' => (int) $row['region'] ?: null,
'text' => [
'teaser' => $this->html($row['teaser']),
'description' => $this->html($row['description']),
'descriptionExtended' => $this->html($row['description_extended']),
'party' => $this->html($row['party']),
'leisure' => $this->html($row['leisure']),
],
];
default: // concept
return $item + [
'code' => $this->text($row['code']),
'text' => [
'teaser' => $this->html($row['teaser']),
'description' => $this->html($row['description']),
'descriptionExtended' => $this->html($row['description_extended']),
'popupText' => $this->html($row['popup_text']),
],
];
}
}
private function serializeNews(array $rows): array
{
$uids = array_keys($rows);
$tags = $this->findNewsTags($uids);
$categories = $this->findNewsCategories($uids);
$items = [];
foreach ($rows as $uid => $row) {
$link = $this->urlResolver->getNewsLink($uid, (int) $row['pid']);
if (null === $link) {
continue;
}
$items[] = [
'uid' => $uid,
'url' => $link['url'],
'site' => $link['site'],
'modified' => date('c', (int) $row['tstamp']),
'title' => $this->text($row['title']),
'teaser' => $this->html($row['teaser']),
'bodytext' => $this->html($row['bodytext']),
'datetime' => (int) $row['datetime'] > 0 ? date('c', (int) $row['datetime']) : null,
'tags' => $tags[$uid] ?? [],
'categories' => $categories[$uid] ?? [],
];
}
return $items;
}
/**
* The identity and link fields every record carries, with the same values as the manifest.
*/
private function withLink(array $row, int $modified): array
{
$link = $this->urlResolver->getRecordLink((string) $row['detail_page']);
return [
'uid' => (int) $row['uid'],
'url' => $link['url'],
'site' => $link['site'],
'modified' => date('c', $modified),
];
}
/**
* @param int[] $uids
* @return array<int, int[]> related uids by $keyField, in $sortField order
*/
private function findMmUids(string $table, string $keyField, string $valueField, array $uids, string $sortField = 'sorting'): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable($table);
$rows = $queryBuilder
->select($keyField, $valueField)
->from($table)
->where($queryBuilder->expr()->in($keyField, $queryBuilder->createNamedParameter($uids, Connection::PARAM_INT_ARRAY)))
->orderBy($keyField)
->addOrderBy($sortField)
->execute()
->fetchAllAssociative()
;
$related = [];
foreach ($rows as $row) {
$related[(int) $row[$keyField]][] = (int) $row[$valueField];
}
return $related;
}
/**
* @param int[] $productUids
* @return array<int, array[]> FAQs by product uid, in the order the editor arranged them
*/
private function findFaqs(array $productUids): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_faq');
$rows = $queryBuilder
->select('mm.uid_local AS product', 'faq.question', 'faq.answer', 'faq.category')
->from('tx_epproducts_domain_model_faq', 'faq')
->join('faq', 'tx_epproducts_product_faq_mm', 'mm', 'mm.uid_foreign = faq.uid')
->where($queryBuilder->expr()->in('mm.uid_local', $queryBuilder->createNamedParameter($productUids, Connection::PARAM_INT_ARRAY)))
->orderBy('mm.uid_local')
->addOrderBy('mm.sorting')
->execute()
->fetchAllAssociative()
;
$faqs = [];
foreach ($rows as $row) {
$faqs[(int) $row['product']][] = [
'question' => $this->text($row['question']),
'answer' => $this->html($row['answer']),
'category' => $this->text($row['category']),
];
}
return $faqs;
}
/**
* Matchcode aliases by hotel uid. With the hotel's own code they are every code BusPro may use
* for it - the same set DateImportService::getHotelMappings() resolves.
*
* @param int[] $hotelUids
* @return array<int, string[]>
*/
private function findMatchcodes(array $hotelUids): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_matchcode');
$rows = $queryBuilder
->select('entity', 'code')
->from('tx_epproducts_domain_model_matchcode')
->where(
$queryBuilder->expr()->eq('entity_type', $queryBuilder->createNamedParameter('hotel')),
$queryBuilder->expr()->in('entity', $queryBuilder->createNamedParameter($hotelUids, Connection::PARAM_INT_ARRAY))
)
->orderBy('code')
->execute()
->fetchAllAssociative()
;
$codes = [];
foreach ($rows as $row) {
$codes[(int) $row['entity']][] = trim((string) $row['code']);
}
return $codes;
}
/**
* @param array $infoboxUids
* @return array<int, string|null>
*/
private function findInfoboxTexts(array $infoboxUids): array
{
$infoboxUids = array_values(array_filter(array_map('intval', $infoboxUids)));
if ([] === $infoboxUids) {
return [];
}
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_infobox');
$rows = $queryBuilder
->select('uid', 'text')
->from('tx_epproducts_domain_model_infobox')
->where($queryBuilder->expr()->in('uid', $queryBuilder->createNamedParameter(array_unique($infoboxUids), Connection::PARAM_INT_ARRAY)))
->execute()
->fetchAllAssociative()
;
$texts = [];
foreach ($rows as $row) {
$texts[(int) $row['uid']] = $this->html($row['text']);
}
return $texts;
}
private function findWebcamUrl(int $webcamUid): ?string
{
if (0 === $webcamUid) {
return null;
}
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_epproducts_domain_model_webcam');
$url = $queryBuilder
->select('url')
->from('tx_epproducts_domain_model_webcam')
->where($queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($webcamUid, \PDO::PARAM_INT)))
->execute()
->fetchOne()
;
return false === $url ? null : $this->text($url);
}
/**
* @param int[] $newsUids
* @return array<int, string[]>
*/
private function findNewsTags(array $newsUids): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('tx_news_domain_model_tag');
$rows = $queryBuilder
->select('mm.uid_local AS news', 'tag.title')
->from('tx_news_domain_model_tag', 'tag')
->join('tag', 'tx_news_domain_model_news_tag_mm', 'mm', 'mm.uid_foreign = tag.uid')
->where($queryBuilder->expr()->in('mm.uid_local', $queryBuilder->createNamedParameter($newsUids, Connection::PARAM_INT_ARRAY)))
->orderBy('mm.sorting')
->execute()
->fetchAllAssociative()
;
$tags = [];
foreach ($rows as $row) {
$tags[(int) $row['news']][] = trim((string) $row['title']);
}
return $tags;
}
/**
* @param int[] $newsUids
* @return array<int, string[]>
*/
private function findNewsCategories(array $newsUids): array
{
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_category');
$rows = $queryBuilder
->select('mm.uid_foreign AS news', 'category.title')
->from('sys_category', 'category')
->join('category', 'sys_category_record_mm', 'mm', 'mm.uid_local = category.uid')
->where(
$queryBuilder->expr()->eq('mm.tablenames', $queryBuilder->createNamedParameter('tx_news_domain_model_news')),
$queryBuilder->expr()->eq('mm.fieldname', $queryBuilder->createNamedParameter('categories')),
$queryBuilder->expr()->in('mm.uid_foreign', $queryBuilder->createNamedParameter($newsUids, Connection::PARAM_INT_ARRAY))
)
->orderBy('mm.sorting_foreign')
->execute()
->fetchAllAssociative()
;
$categories = [];
foreach ($rows as $row) {
$categories[(int) $row['news']][] = trim((string) $row['title']);
}
return $categories;
}
/**
* Rich text as stored, with internal links made absolute.
*/
private function html($value): ?string
{
$value = trim((string) $value);
return '' === $value ? null : $this->rteLinkResolver->resolve($value);
}
/**
* Plain text with whitespace collapsed. Product names carry literal line breaks the website
* splits on for layout ("Apartments \nVal Thorens"); the chatbot needs them as one line.
*/
private function text($value): ?string
{
$value = trim((string) preg_replace('/\s+/u', ' ', (string) $value));
return '' === $value ? null : $value;
}
}
@@ -0,0 +1,104 @@
<?php
namespace EP\EpProducts\ContentFeed;
use TYPO3\CMS\Core\LinkHandling\LinkService;
use TYPO3\CMS\Core\Resource\File;
/**
* Rewrites `t3://` links in stored RTE HTML to absolute URLs.
*
* parseFunc_RTE would do this, but it needs a TSFE and the API middleware runs before one exists.
* Only links are touched; the rest of the HTML is passed on as stored. A link that cannot be
* resolved to something public (a page outside the feed's sites, a deleted page) loses its href
* and keeps its text.
*/
class RteLinkResolver
{
/**
* @var LinkService
*/
private $linkService;
/**
* @var UrlResolver
*/
private $urlResolver;
public function __construct(LinkService $linkService, UrlResolver $urlResolver)
{
$this->linkService = $linkService;
$this->urlResolver = $urlResolver;
}
public function resolve(string $html): string
{
if (false === strpos($html, 't3://')) {
return $html;
}
return (string) preg_replace_callback(
'/\shref=(["\'])(t3:\/\/[^"\']*)\1/i',
function (array $matches): string {
$url = $this->resolveLink(html_entity_decode($matches[2], ENT_QUOTES | ENT_HTML5));
return null === $url ? '' : ' href="' . htmlspecialchars($url) . '"';
},
$html
);
}
private function resolveLink(string $link): ?string
{
try {
$data = $this->linkService->resolve($link);
} catch (\Throwable $e) {
return null;
}
if (LinkService::TYPE_PAGE === ($data['type'] ?? null)) {
$pageUid = $this->urlResolver->parsePageReference('t3://page?uid=' . ($data['pageuid'] ?? ''));
$target = null === $pageUid ? null : $this->urlResolver->resolveLinkTarget($pageUid);
$url = null === $target ? null : $this->urlResolver->getPageUrl($target);
if (null !== $url && '' !== (string) ($data['fragment'] ?? '')) {
$url .= '#' . $data['fragment'];
}
return $url;
}
if (LinkService::TYPE_FILE === ($data['type'] ?? null) && ($data['file'] ?? null) instanceof File) {
return $this->absolute((string) $data['file']->getPublicUrl());
}
if (LinkService::TYPE_URL === ($data['type'] ?? null)) {
return (string) $data['url'];
}
return null;
}
/**
* File URLs come back relative to the document root; the consumer has no page to resolve
* them against for record text, so make them absolute against the main site.
*/
private function absolute(string $url): ?string
{
if ('' === $url) {
return null;
}
if (1 === preg_match('/^https?:\/\//', $url)) {
return $url;
}
$sites = $this->urlResolver->getIncludedSites();
if ([] === $sites) {
return null;
}
return rtrim((string) $sites[0]->getBase(), '/') . '/' . ltrim($url, '/');
}
}
@@ -0,0 +1,214 @@
<?php
namespace EP\EpProducts\ContentFeed;
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Utility\MathUtility;
/**
* Absolute public URLs for the content feed, generated through each site's router so that
* baseVariants apply (staging and DDEV get their own hosts) and route enhancers shape the path.
*/
class UrlResolver
{
private const DOKTYPE_DEFAULT = 1;
private const DOKTYPE_SHORTCUT = 4;
private const SHORTCUT_MODE_NONE = 0;
private const SHORTCUT_MODE_FIRST_SUBPAGE = 1;
private const SHORTCUT_MODE_PARENT_PAGE = 3;
private const MAX_SHORTCUT_DEPTH = 5;
/**
* @var SiteFinder
*/
private $siteFinder;
/**
* @var PageTree
*/
private $pageTree;
/**
* @var string[]
*/
private $includedSites;
/**
* @var array<string, int> news detail page uid by site identifier
*/
private $newsDetailPages;
/**
* @var array<int, Site|null>
*/
private $sitesByPage = [];
public function __construct(SiteFinder $siteFinder, PageTree $pageTree, ContentFeedConfiguration $configuration)
{
$this->siteFinder = $siteFinder;
$this->pageTree = $pageTree;
$this->includedSites = $configuration->getSites();
$this->newsDetailPages = $configuration->getNewsDetailPages();
}
/**
* @return Site[] included sites, in configuration order
*/
public function getIncludedSites(): array
{
$sites = [];
foreach ($this->includedSites as $identifier) {
try {
$sites[] = $this->siteFinder->getSiteByIdentifier($identifier);
} catch (SiteNotFoundException $e) {
// A misspelt identifier must not take the whole feed down; it just contributes nothing.
}
}
return $sites;
}
/**
* The page's site, or null when it belongs to no site or to one outside the feed.
*/
public function getIncludedSite(int $pageUid): ?Site
{
if (!array_key_exists($pageUid, $this->sitesByPage)) {
try {
$site = $this->siteFinder->getSiteByPageId($pageUid);
$this->sitesByPage[$pageUid] = in_array($site->getIdentifier(), $this->includedSites, true) ? $site : null;
} catch (SiteNotFoundException $e) {
$this->sitesByPage[$pageUid] = null;
}
}
return $this->sitesByPage[$pageUid];
}
public function getPageUrl(int $pageUid, int $languageId = 0, array $parameters = []): ?string
{
$site = $this->getIncludedSite($pageUid);
if (null === $site) {
return null;
}
try {
$language = $site->getLanguageById($languageId);
return (string) $site->getRouter()->generateUri($pageUid, ['_language' => $language] + $parameters);
} catch (\Throwable $e) {
// Unroutable pages (missing slug, disabled language) are left out rather than failing the feed.
return null;
}
}
/**
* Parses a typolink page reference as stored in `detail_page`: a plain uid or `t3://page?uid=N`.
*/
public function parsePageReference(string $reference): ?int
{
$reference = trim($reference);
if (MathUtility::canBeInterpretedAsInteger($reference)) {
return (int) $reference > 0 ? (int) $reference : null;
}
if (1 === preg_match('/^t3:\/\/page\?(?:.*&)?uid=(\d+)/', html_entity_decode($reference), $matches)) {
return (int) $matches[1];
}
return null;
}
/**
* Follows shortcut pages the way a typolink does, and returns the uid of the visible standard
* page a link to $pageUid ends up on - or null when the chain breaks or loops.
*/
public function resolveLinkTarget(int $pageUid): ?int
{
for ($depth = 0; $depth < self::MAX_SHORTCUT_DEPTH; $depth++) {
$page = $this->pageTree->getPage($pageUid);
if (null === $page || !$this->pageTree->isVisible($page)) {
return null;
}
if ((int) $page['doktype'] !== self::DOKTYPE_SHORTCUT) {
return (int) $page['doktype'] === self::DOKTYPE_DEFAULT ? $pageUid : null;
}
$next = $this->getShortcutTarget($page);
if (null === $next) {
return null;
}
$pageUid = $next;
}
return null;
}
/**
* @return array{url: ?string, site: ?string}
*/
public function getRecordLink(string $detailPage): array
{
$pageUid = $this->parsePageReference($detailPage);
$target = null === $pageUid ? null : $this->resolveLinkTarget($pageUid);
$site = null === $target ? null : $this->getIncludedSite($target);
$url = null === $site ? null : $this->getPageUrl($target);
return [
'url' => $url,
'site' => null === $url ? null : $site->getIdentifier(),
];
}
/**
* News has no detail_page of its own: the storage folder decides the site, and the site's
* configured detail page carries the article through the NewsDetailPlugin route enhancer.
*
* @return array{url: ?string, site: string}|null null when the article is stored outside the feed's sites
*/
public function getNewsLink(int $newsUid, int $storagePid): ?array
{
$site = $this->getIncludedSite($storagePid);
if (null === $site) {
return null;
}
$detailPage = $this->newsDetailPages[$site->getIdentifier()] ?? null;
$url = null === $detailPage ? null : $this->getPageUrl($detailPage, 0, [
'tx_news_pi1' => ['action' => 'detail', 'controller' => 'News', 'news' => $newsUid],
]);
return ['url' => $url, 'site' => $site->getIdentifier()];
}
private function getShortcutTarget(array $page): ?int
{
switch ((int) $page['shortcut_mode']) {
case self::SHORTCUT_MODE_NONE:
return (int) $page['shortcut'] > 0 ? (int) $page['shortcut'] : null;
case self::SHORTCUT_MODE_FIRST_SUBPAGE:
foreach ($this->pageTree->getChildren((int) $page['uid']) as $childUid) {
if ($this->pageTree->isVisible($this->pageTree->getPage($childUid))) {
return $childUid;
}
}
return null;
case self::SHORTCUT_MODE_PARENT_PAGE:
return (int) $page['pid'] > 0 ? (int) $page['pid'] : null;
default:
// Random subpage: there is no stable URL to give.
return null;
}
}
}
@@ -36,6 +36,7 @@ use EP\EpProducts\Service\ContingentDataService;
use EP\EpProducts\Service\DateService;
use EP\EpProducts\Service\FilterService;
use EP\EpProducts\Service\HotelDataService;
use EP\EpProducts\Service\PickupOverviewService;
use EP\EpProducts\Service\ProductDataService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
@@ -82,6 +83,11 @@ class ProductController extends ActionController
*/
private $infoboxRepository;
/**
* @var PickupOverviewService
*/
private $pickupOverviewService;
/**
* @param ProductRepository $productRepository
* @param ProductDataService $productDataService
@@ -91,6 +97,7 @@ class ProductController extends ActionController
* @param DateService $dateService
* @param FilterService $filterService
* @param InfoboxRepository $infoboxRepository
* @param PickupOverviewService $pickupOverviewService
*/
public function __construct(
ProductRepository $productRepository,
@@ -100,7 +107,8 @@ class ProductController extends ActionController
ContingentDataService $contingentDataService,
DateService $dateService,
FilterService $filterService,
InfoboxRepository $infoboxRepository
InfoboxRepository $infoboxRepository,
PickupOverviewService $pickupOverviewService
) {
$this->productRepository = $productRepository;
$this->productDataService = $productDataService;
@@ -110,6 +118,7 @@ class ProductController extends ActionController
$this->dateService = $dateService;
$this->filterService = $filterService;
$this->infoboxRepository = $infoboxRepository;
$this->pickupOverviewService = $pickupOverviewService;
}
/**
@@ -196,6 +205,7 @@ class ProductController extends ActionController
'referringUrl' => $backlinkUrl,
'backlinkLabel' => $backLinkLabel,
'nonBookableInfo' => $nonBookableInfo,
'pickupsOverview' => $this->pickupOverviewService->getOverview($product, $hotel),
]);
}
@@ -87,12 +87,16 @@ class SearchController extends ActionController
public function initializeSearchresultAction()
{
// Process encoded filtersettings from static search result
// Process encoded filtersettings from static search result.
// Explicit filter settings win: they carry the visitor's current selection,
// whereas a stale 'f' riding along on a link would silently replace it.
$encodedFilterSettings = GeneralUtility::_GET('f');
if ($encodedFilterSettings) {
if ($encodedFilterSettings && !$this->request->hasArgument('filterSettings')) {
$filterSettingsEncoder = new FilterSettingsEncoder();
$filterSettings = $filterSettingsEncoder->decode($encodedFilterSettings);
$this->request->setArgument('filterSettings', $filterSettings);
if (count($filterSettings) > 0) {
$this->request->setArgument('filterSettings', $filterSettings);
}
}
$forcedConceptUids = GeneralUtility::intExplode(',', $this->settings['forcedConceptUids'], true);
$this->processFilterSettingsArgument($forcedConceptUids);
@@ -56,7 +56,7 @@ class FacebookCatalogCsvFormatter
$product['images']['image'][0],
$product['link'],
$product['name'],
$minPrice . ' EUR',
sprintf('%.2f EUR', $minPrice),
'brand-epreisen'
];
}
@@ -48,7 +48,7 @@ class GoogleBusinessFeedCsvFormatter
$product['name'],
$product['link'],
$product['images']['image'][0],
$minPrice . '.00 EUR',
sprintf('%.2f EUR', $minPrice),
];
}
}
@@ -114,15 +114,20 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
*/
protected $skipassIncluded = false;
/**
* @var bool
*/
protected $groupTravel = false;
/**
* @var bool
*/
protected $busAvailable = false;
/**
* @var int
* @var float
*/
protected $busPrice = 0;
protected $busPrice = 0.0;
/**
* @var string
@@ -145,19 +150,19 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
protected $pickups = '';
/**
* @var int
* @var float
*/
protected $discount = 0;
protected $discount = 0.0;
/**
* @var int
* @var float
*/
protected $minPrice = 0;
protected $minPrice = 0.0;
/**
* @var int
* @var float
*/
protected $pseudoPrice = 0;
protected $pseudoPrice = 0.0;
/**
* @var int
@@ -421,6 +426,22 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
$this->skipassIncluded = $skipassIncluded;
}
/**
* @return bool
*/
public function getGroupTravel()
{
return $this->groupTravel;
}
/**
* @param bool $groupTravel
*/
public function setGroupTravel($groupTravel)
{
$this->groupTravel = $groupTravel;
}
/**
* @return bool
*/
@@ -438,7 +459,7 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
}
/**
* @return int
* @return float
*/
public function getBusPrice()
{
@@ -446,7 +467,7 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
}
/**
* @param int $busPrice
* @param float $busPrice
*/
public function setBusPrice($busPrice)
{
@@ -533,21 +554,21 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
}
/**
* @return int
* @return float
*/
public function getDiscount() {
return $this->discount;
}
/**
* @param int $discount
* @param float $discount
*/
public function setDiscount($discount) {
$this->discount = $discount;
}
/**
* @return int
* @return float
*/
public function getMinPrice()
{
@@ -555,7 +576,7 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
}
/**
* @param int $minPrice
* @param float $minPrice
*/
public function setMinPrice($minPrice)
{
@@ -563,7 +584,7 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
}
/**
* @return int
* @return float
*/
public function getPseudoPrice()
{
@@ -571,7 +592,7 @@ class Date extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
}
/**
* @param int $pseudoPrice
* @param float $pseudoPrice
*/
public function setPseudoPrice($pseudoPrice)
{
@@ -27,6 +27,7 @@ namespace EP\EpProducts\Domain\Model;
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use EP\EpProducts\Utility\HotelIconUtility;
use TYPO3\CMS\Extbase\Domain\Model\FileReference;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
@@ -1253,4 +1254,20 @@ class Hotel extends AbstractEntity implements TeaserInterface
{
$this->distanceLift = $distanceLift;
}
public function getIcons(): array
{
return HotelIconUtility::getIcons([
'beds_count' => $this->bedsCount,
'parking_count' => $this->parkingCount,
'altitude' => $this->altitude,
'distance_bus' => $this->distanceBus,
'distance_lift' => $this->distanceLift,
'shower' => $this->shower,
'partyroom' => $this->partyroom,
'gamesroom' => $this->gamesroom,
'sauna' => $this->sauna,
'wifi' => $this->wifi,
]);
}
}
@@ -30,12 +30,17 @@ namespace EP\EpProducts\Domain\Model;
class Room
{
const ROOM_TYPE_UNCLASSIFIED = 0;
const ROOM_TYPE_FOR_ONE = 1;
const ROOM_TYPE_FOR_TWO = 2;
const ROOM_TYPE_FOR_THREE = 3;
const ROOM_TYPE_FOR_FOUR = 4;
const ROOM_TYPE_WITH_OTHERS = 5;
const ROOM_TYPE_OTHER = 6;
const ROOM_TYPE_FOR_FIVE = 5;
const ROOM_TYPE_FOR_SIX = 6;
const ROOM_TYPE_FOR_SEVEN = 7;
const ROOM_TYPE_FOR_EIGHT = 8;
const ROOM_TYPE_FOR_NINE_PLUS = 9;
const ROOM_TYPE_WITH_OTHERS = 10;
const ROOM_STATUS_AVAILABLE = 1;
const ROOM_STATUS_ON_REQUEST = 2;
@@ -1,75 +0,0 @@
<?php
namespace EP\EpProducts\Domain\Model;
/***************************************************************
*
* Copyright notice
*
* (c) 2016 Björn Fromme <[email protected]>, dreipunktnull
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
class RoomMapping extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
/**
* @var string
*/
protected $code = '';
/**
* @var int
*/
protected $type = 0;
/**
* @return string
*/
public function getCode()
{
return $this->code;
}
/**
* @param string $code
*/
public function setCode($code)
{
$this->code = $code;
}
/**
* @return int
*/
public function getType()
{
return $this->type;
}
/**
* @param int $type
*/
public function setType($type)
{
$this->type = $type;
}
}
@@ -3,6 +3,7 @@
namespace EP\EpProducts\Domain\Repository;
use EP\EpProducts\Domain\Model\Product;
use TYPO3\CMS\Core\Database\Connection;
class DateRepository extends AbstractRepository
{
@@ -18,4 +19,27 @@ class DateRepository extends AbstractRepository
->execute()
;
}
/**
* @return string[] serialized pickups of each upcoming date, latest first
*/
public function findPickupsForProductAndHotel(int $productUid, int $hotelUid): array
{
$qb = $this->getDbConnection()->createQueryBuilder();
return $qb
->select('date.pickups')
->from('tx_epproducts_domain_model_date', 'date')
->where(
$qb->expr()->eq('date.product', $qb->createNamedParameter($productUid, Connection::PARAM_INT)),
$qb->expr()->eq('date.hotel', $qb->createNamedParameter($hotelUid, Connection::PARAM_INT)),
$qb->expr()->eq('date.group_travel', $qb->createNamedParameter(0, Connection::PARAM_INT)),
'date.date_start >= NOW()'
)
->orderBy('date.date_start', 'DESC')
->addOrderBy('date.uid', 'DESC')
->execute()
->fetchFirstColumn()
;
}
}
@@ -76,9 +76,11 @@ class ProductRepository extends AbstractRepository
'date.services_included as servicesIncluded', 'date.skipass_included as skiPassIncluded',
'date.bus_available as busAvailable', 'date.new as new',
'date.min_price as minPrice', 'date.nights as nights', 'date.available as available',
'date.pseudo_price as pseudoPrice', 'date.hide_booking_button as hideBookingButton',
'room.type as roomType'
'date.pseudo_price as pseudoPrice', 'date.hide_booking_button as hideBookingButton'
)
// The GROUP BY below collapses many room rows per group; an arbitrary
// room.type would hide most types from the filter facet.
->addSelectLiteral('GROUP_CONCAT(DISTINCT room.type) as roomTypes')
->from('tx_epproducts_domain_model_date', 'date')
->leftJoin('date', 'tx_epproducts_domain_model_concept', 'con', 'date.concept = con.uid')
->leftJoin('date', 'tx_epproducts_domain_model_room', 'room', 'room.date = date.uid')
@@ -208,6 +210,7 @@ class ProductRepository extends AbstractRepository
'date.uid as dateUid', 'date.date_start as dateStart', 'date.date_end as dateEnd',
'date.bus_pro_id as dateBusProId', 'date.hotel as hotelUid', 'date.hotel_bus_pro_id as hotelBusProId',
'date.bus_included as dateBusIncluded', 'date.skipass_included as dateSkiPassIncluded',
'date.group_travel as dateGroupTravel',
'date.season as season', 'date.product_detail_page as productDetailPage',
'room.uid as roomUid', 'room.bus_pro_id as roomBusProId', 'room.name as roomName',
'room.price as roomPrice', 'date.discount as roomDiscount', 'date.bus_price as busPrice',
@@ -271,6 +274,7 @@ class ProductRepository extends AbstractRepository
'date.discount as dateDiscount', 'date.bus_price as busPrice', 'date.nights as dateNights',
'date.bus_included as dateBusIncluded', 'date.services_included as dateServicesIncluded',
'date.services_general as dateServicesGeneral', 'date.skipass_included as dateSkiPassIncluded',
'date.group_travel as dateGroupTravel',
'date.bus_pro_id as dateBusProId', 'date.hotel_bus_pro_id as hotelBusProId',
'date.available as available', 'date.product_detail_page as productDetailPage',
)
@@ -1,31 +0,0 @@
<?php
namespace EP\EpProducts\Domain\Repository;
/***************************************************************
*
* Copyright notice
*
* (c) 2016 Björn Fromme <[email protected]>, dreipunktnull
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
class RoomMappingRepository extends AbstractRepository
{}
@@ -44,7 +44,7 @@ class Date
$date['@id'] = $array['dateBusProId'];
$date['from'] = $array['dateStart'];
$date['to'] = $array['dateEnd'];
$date['minprice'] = $array['dateMinPrice'];
$date['minprice'] = (float) $array['dateMinPrice'];
$date['nights'] = $array['dateNights'];
$date['skipassincluded'] = $array['dateSkiPassIncluded'];
$date['busincluded'] = $array['dateBusIncluded'];
@@ -40,8 +40,8 @@ class Room
$room['@pax'] = $array['roomPax'];
$room['@code'] = $array['roomCode'];
$room['name'] = $array['roomName'];
$room['price'] = $array['roomPrice'];
$room['busprice'] = $array['busPrice'];
$room['price'] = (float) $array['roomPrice'];
$room['busprice'] = (float) $array['busPrice'];
$room['nights'] = $array['roomNights'];
$room['available'] = $array['roomAvailable'];
@@ -0,0 +1,244 @@
<?php
namespace EP\EpProducts\EpTeam;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* The MyE&P Team application (Symfony). Separate from EP\EpProducts\MyEP\ApiClient on purpose:
* this is a different application on its own host, authenticated with a shared key in a header
* instead of the OAuth client-credentials flow MyE&P uses, so it shares neither the base URI nor
* the token handling.
*/
class ApiClient implements LoggerAwareInterface
{
use LoggerAwareTrait;
/**
* Applied when extension configuration does not override them. Seconds.
*/
private const DEFAULT_TIMEOUT = 5;
private const DEFAULT_MAX_DURATION = 15;
/**
* Status codes the endpoint answers a stored submission with. A conflict is included for the
* dedupe the team application may add later - it is not returned today - because a
* double-clicked submit button is not something to report.
*/
private const ACCEPTED_STATUS_CODES = [
Response::HTTP_OK,
Response::HTTP_CREATED,
Response::HTTP_ACCEPTED,
Response::HTTP_NO_CONTENT,
Response::HTTP_CONFLICT,
];
/**
* How much of a rejected response is carried into the exception message. A 400 names the
* offending field in its body, which is the only way to tell from a log why a submission
* was refused.
*/
private const ERROR_BODY_EXCERPT_LENGTH = 500;
/**
* Shared, like the MyE&P client: Symfony's CurlHttpClient keeps its connection pool and TLS
* session cache per instance. The API key is a constant, so unlike a bearer token it can be
* a client default header and the instance can live as long as the request.
*/
private static ?HttpClientInterface $httpClient = null;
private ?array $configuration = null;
/**
* Posts a submitted TYPO3 form to POST /api/application-forms.
*
* @throws ApiException
*/
public function submitApplicationForm(array $payload): void
{
$uri = 'api/application-forms';
// 'json' also sets the Content-Type the endpoint requires - without it the body is not
// read as JSON and the answer is a 400.
$response = $this->request('POST', $uri, [
'json' => $payload,
]);
$statusCode = $this->readStatusCode($response, 'POST', $uri);
if (false === in_array($statusCode, self::ACCEPTED_STATUS_CODES, true)) {
$message = sprintf(
'EP Team API returned unexpected status %d for POST %s: %s',
$statusCode,
$uri,
$this->readErrorBody($response)
);
$this->logWarning($message);
throw new ApiException($message, $statusCode);
}
$this->logAcceptedSubmission($response, $payload);
}
/**
* @throws ApiException
*/
private function request(string $method, string $uri, array $options): ResponseInterface
{
try {
return $this->getHttpClient()->request($method, $uri, $options);
} catch (TransportExceptionInterface $e) {
$message = sprintf('EP Team API transport error for %s %s: %s', $method, $uri, $e->getMessage());
$this->logError($message, ['exception' => $e]);
throw new ApiException($message, 0, $e);
}
}
/**
* Reading the status completes the transfer, so this is also what turns the lazy response
* returned by the client into a finished request.
*
* @throws ApiException
*/
private function readStatusCode(ResponseInterface $response, string $method, string $uri): int
{
try {
return $response->getStatusCode();
} catch (TransportExceptionInterface $e) {
$message = sprintf('EP Team API transport error while reading status for %s %s: %s', $method, $uri, $e->getMessage());
$this->logError($message, ['exception' => $e]);
throw new ApiException($message, 0, $e);
}
}
private function readErrorBody(ResponseInterface $response): string
{
try {
$body = trim($response->getContent(false));
} catch (TransportExceptionInterface $e) {
return '<no response body>';
}
if ('' === $body) {
return '<empty response body>';
}
if (mb_strlen($body) > self::ERROR_BODY_EXCERPT_LENGTH) {
$body = mb_substr($body, 0, self::ERROR_BODY_EXCERPT_LENGTH) . '…';
}
return $body;
}
/**
* The submission uuid the endpoint returns is what makes a support question ("did our
* application arrive?") answerable from the TYPO3 log alone. Reading the body also drains
* the response, which returns the connection to the pool instead of cancelling the transfer.
* Deliberately without any of the submitted values: these payloads are personal data.
*/
private function logAcceptedSubmission(ResponseInterface $response, array $payload): void
{
try {
$data = $response->toArray(false);
} catch (\Throwable $e) {
// A body that is absent (204) or not JSON costs nothing here - the submission is
// stored either way, which the asserted status has already established.
return;
}
if (null !== $this->logger) {
$this->logger->info('Application form submission accepted by the EP Team API.', [
'form' => $payload['form'] ?? null,
'pageUid' => $payload['pageUid'] ?? null,
'uuid' => $data['uuid'] ?? null,
]);
}
}
/**
* @throws ApiException
*/
private function getHttpClient(): HttpClientInterface
{
if (null !== static::$httpClient) {
return static::$httpClient;
}
$config = $this->getConfiguration();
$baseUrl = trim((string)($config['epTeamApiBaseUrl'] ?? ''));
$apiKey = trim((string)($config['epTeamApiKey'] ?? ''));
if ('' === $baseUrl) {
throw new ApiException('EP Team API base URL is not configured.');
}
if ('' === $apiKey) {
throw new ApiException('EP Team API key is not configured.');
}
if (0 !== strpos($baseUrl, 'https://')) {
// The application answers an http request with a 301 to the https URL, and this
// client does not follow redirects, so a plain http base URL fails every submission.
$this->logWarning(sprintf('EP Team API base URL is not https (%s); submissions will fail on the redirect.', $baseUrl));
}
$options = [
'headers' => [
'X-Api-Key' => $apiKey,
],
];
// Without these the client falls back to PHP's default_socket_timeout (commonly 60s),
// so a stalled API pins a PHP worker for a minute per request - and this call happens
// inside the visitor's form submission, with the visitor waiting for it. The defaults
// live in code rather than in ext_conf_template.txt: ExtensionConfiguration::get()
// returns the stored configuration verbatim and only syncs the template when an
// extension has no configuration at all, so a newly added template key is absent until
// someone saves extension configuration by hand. Falling back to 0 there would silently
// mean "no timeout" - the opposite of what this guard is for. An explicit 0 still
// disables.
$timeout = (int)($config['epTeamApiTimeout'] ?? self::DEFAULT_TIMEOUT);
if ($timeout > 0) {
$options['timeout'] = $timeout;
}
$maxDuration = (int)($config['epTeamApiMaxDuration'] ?? self::DEFAULT_MAX_DURATION);
if ($maxDuration > 0) {
$options['max_duration'] = $maxDuration;
}
return static::$httpClient = HttpClient::createForBaseUri(rtrim($baseUrl, '/') . '/', $options);
}
private function getConfiguration(): array
{
if (null === $this->configuration) {
$this->configuration = GeneralUtility::makeInstance(ExtensionConfiguration::class)
->get('ep_products');
}
return $this->configuration;
}
private function logError(string $message, array $context = []): void
{
if (null !== $this->logger) {
$this->logger->error($message, $context);
}
}
private function logWarning(string $message, array $context = []): void
{
if (null !== $this->logger) {
$this->logger->warning($message, $context);
}
}
}
@@ -0,0 +1,7 @@
<?php
namespace EP\EpProducts\EpTeam;
class ApiException extends \RuntimeException
{
}
@@ -0,0 +1,45 @@
<?php
namespace EP\EpProducts\Http;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
/**
* Checks the shared key of the CMS backchannel endpoints (content feed, CMS index).
*
* An empty or missing `cmsApiKey` denies every request. ExtensionConfiguration::get() returns the
* stored configuration verbatim, so a newly added key is absent until someone saves the extension
* configuration in the backend - defaulting to "allow" there would publish the whole catalogue.
*/
class ApiKeyAuthenticator
{
/**
* @var ExtensionConfiguration
*/
private $extensionConfiguration;
public function __construct(ExtensionConfiguration $extensionConfiguration)
{
$this->extensionConfiguration = $extensionConfiguration;
}
public function isAuthorized(ServerRequestInterface $request): bool
{
$configured = (string) ($this->extensionConfiguration->get('ep_products')['cmsApiKey'] ?? '');
if ('' === $configured) {
return false;
}
// Header first: query-string keys end up in access logs. `key` stays accepted for parity
// with the existing /api/hotel and /api/product calls.
$provided = $request->getHeaderLine('X-Api-Key');
if ('' === $provided) {
$provided = (string) ($request->getQueryParams()['key'] ?? '');
}
return hash_equals($configured, $provided);
}
}
@@ -2,7 +2,10 @@
namespace EP\EpProducts\Middleware;
use EP\EpProducts\ContentFeed\ContentFeedApi;
use EP\EpProducts\Http\ApiKeyAuthenticator;
use EP\EpProducts\Service\MyEpImageService;
use EP\EpProducts\Utility\HotelIconUtility;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
@@ -40,18 +43,32 @@ class ApiMiddleware implements MiddlewareInterface
*/
private $imageService;
/**
* @var ContentFeedApi
*/
private $contentFeedApi;
/**
* @var ApiKeyAuthenticator
*/
private $authenticator;
public function __construct(
MyEpImageService $hotelImageService,
MyEpImageService $productImageService,
MyEpImageService $regionImageService,
FileRepository $fileRepository,
ImageService $imageService
ImageService $imageService,
ContentFeedApi $contentFeedApi,
ApiKeyAuthenticator $authenticator
) {
$this->hotelImageService = $hotelImageService;
$this->productImageService = $productImageService;
$this->regionImageService = $regionImageService;
$this->fileRepository = $fileRepository;
$this->imageService = $imageService;
$this->contentFeedApi = $contentFeedApi;
$this->authenticator = $authenticator;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
@@ -66,17 +83,17 @@ class ApiMiddleware implements MiddlewareInterface
return $this->handleProductRequest($request);
}
if (0 === strpos($path, ContentFeedApi::PATH_PREFIX)) {
return $this->contentFeedApi->handle($request);
}
return $handler->handle($request);
}
private function handleHotelRequest(ServerRequestInterface $request): ResponseInterface
{
// This is currently fake, we only check for existence. Since we are communicating
// on the backchannel only it's not much of a problem.
$apiKey = $request->getQueryParams()['key'] ?? null;
if (null === $apiKey) {
return new JsonResponse(['message' => 'No api key provided'], 403);
if (!$this->authenticator->isAuthorized($request)) {
return new JsonResponse(['message' => 'Invalid or missing api key'], 403);
}
$hotelCode = $request->getQueryParams()['hotel'] ?? null;
@@ -96,12 +113,8 @@ class ApiMiddleware implements MiddlewareInterface
private function handleProductRequest(ServerRequestInterface $request): ResponseInterface
{
// This is currently fake, we only check for existence. Since we are communicating
// on the backchannel only it's not much of a problem.
$apiKey = $request->getQueryParams()['key'] ?? null;
if (null === $apiKey) {
return new JsonResponse(['message' => 'No api key provided'], 403);
if (!$this->authenticator->isAuthorized($request)) {
return new JsonResponse(['message' => 'Invalid or missing api key'], 403);
}
$productCode = $request->getQueryParams()['product'] ?? null;
@@ -217,70 +230,6 @@ class ApiMiddleware implements MiddlewareInterface
$images = $this->serializeImages($this->hotelImageService->getImages((int) $hotel['uid']));
// map fields to icon ids and labels
$icons = [];
if (($hotel['beds_count'] ?? 0) > 0) {
$icons[] = [
'icon' => 'bed',
'label' => sprintf('%d Betten', $hotel['beds_count']),
];
}
if (($hotel['parking_count'] ?? 0) > 0) {
$icons[] = [
'icon' => 'parking',
'label' => sprintf('%d Parkplätze', $hotel['parking_count']),
];
}
if ($hotel['altitude'] ?? null) {
$icons[] = [
'icon' => 'mountain',
'label' => $hotel['altitude'],
];
}
if ($hotel['distance_bus'] ?? null) {
$icons[] = [
'icon' => 'bus',
'label' => $hotel['distance_bus'],
];
}
if ($hotel['distance_lift'] ?? null) {
$icons[] = [
'icon' => 'lift',
'label' => $hotel['distance_lift'],
];
}
if ($hotel['shower'] ?? null) {
$icons[] = [
'icon' => 'shower',
'label' => $hotel['shower'],
];
}
if ($hotel['partyroom'] ?? false) {
$icons[] = [
'icon' => 'party',
'label' => 'Partyzimmer',
];
}
if ($hotel['gamesroom'] ?? false) {
$icons[] = [
'icon' => 'dice',
'label' => 'Spielezimmer',
];
}
if ($hotel['sauna'] ?? false) {
$icons[] = [
'icon' => 'sauna',
'label' => 'Sauna',
];
}
if ($hotel['wifi'] ?? false) {
$icons[] = [
'icon' => 'wifi',
'label' => 'WiFi',
];
}
return [
'name' => $hotel['name'],
'code' => $hotel['code'],
@@ -290,7 +239,7 @@ class ApiMiddleware implements MiddlewareInterface
'additional_information' => $hotel['additional_information'],
'address' => $hotel['address'],
'images' => $images,
'icons' => $icons,
'icons' => HotelIconUtility::getIcons($hotel),
'region' => $this->fetchRegionData((int) $hotel['region']),
];
}
@@ -0,0 +1,65 @@
<?php
namespace EP\EpProducts\Middleware;
use EP\EpProducts\ContentFeed\ContentFeedApi;
use EP\EpProducts\ContentFeed\ContentFeedConfiguration;
use EP\EpProducts\ContentFeed\ManifestBuilder;
use EP\EpProducts\Http\ApiKeyAuthenticator;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Routing\PageArguments;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Frontend\Controller\ErrorController;
/**
* Keeps the chatbot content-only page type (an unstyled copy of every page) off the public web:
* only requests carrying the CMS API key get it.
*
* Runs once the page type is known and before TSFE, so a page-cache hit cannot bypass it.
* staticfilecache never stores the type (`tx_staticfilecache.disableCache`); if it did, .htaccess
* would serve the file without this check ever running.
*/
class ContentPageTypeGuardMiddleware implements MiddlewareInterface
{
/**
* @var ApiKeyAuthenticator
*/
private $authenticator;
/**
* @var ContentFeedConfiguration
*/
private $configuration;
public function __construct(ApiKeyAuthenticator $authenticator, ContentFeedConfiguration $configuration)
{
$this->authenticator = $authenticator;
$this->configuration = $configuration;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$routing = $request->getAttribute('routing');
if (!$routing instanceof PageArguments
|| (string) ManifestBuilder::CONTENT_PAGE_TYPE !== $routing->getPageType()
) {
return $handler->handle($request);
}
if (!$this->authenticator->isAuthorized($request)) {
// 404, not 403: an unauthenticated caller should not learn the type exists.
return GeneralUtility::makeInstance(ErrorController::class)
->pageNotFoundAction($request, 'The requested page does not exist');
}
if (!$this->configuration->isEnabled()) {
return ContentFeedApi::disabledResponse();
}
return $handler->handle($request);
}
}
@@ -49,8 +49,22 @@ class ApiClient implements LoggerAwareInterface
*/
private const ACCESS_TOKEN_DEFAULT_TTL = 300;
/**
* Status codes that mean the token was rejected rather than the request being wrong.
*/
private const UNAUTHORIZED_STATUS_CODES = [Response::HTTP_UNAUTHORIZED, Response::HTTP_FORBIDDEN];
private static ?AccessToken $accessToken = null;
/**
* Shared on purpose. Symfony's CurlHttpClient keeps its connection pool and TLS session
* cache in a CurlClientState owned by the instance, so building a client per call throws
* both away and forces a fresh DNS lookup, TCP connect and TLS handshake every time -
* TravelinfoController alone makes two calls per page render. The bearer token is passed
* per request rather than as a client default so one instance can outlive one token.
*/
private static ?HttpClientInterface $httpClient = null;
private ?FrontendInterface $cache = null;
private ?array $configuration = null;
@@ -67,7 +81,8 @@ class ApiClient implements LoggerAwareInterface
}
try {
return new \DateTimeImmutable($data['timestamp']);
// The API reports Europe/Berlin local time without an offset.
return new \DateTimeImmutable($data['timestamp'], new \DateTimeZone('Europe/Berlin'));
} catch (\Throwable $e) {
$message = sprintf('Invalid timestamp returned by MyEP API for GET last-update: %s', $e->getMessage());
$this->logError($message, ['exception' => $e]);
@@ -75,6 +90,22 @@ class ApiClient implements LoggerAwareInterface
}
}
/**
* One page of the product export: one row per travel date × hotel in `data`,
* and `meta` describing the whole export.
*
* @throws ApiException
*/
public function getProductExport(int $page, int $perPage): array
{
return $this->requestJson('GET', 'exports/products', [
'query' => [
'page' => $page,
'perPage' => $perPage,
],
]);
}
/**
* @throws ApiException
*/
@@ -103,20 +134,7 @@ class ApiClient implements LoggerAwareInterface
// A conflict means the address is already registered, which is the normal answer to a
// resubmitted contact form and not worth reporting.
$this->assertStatusCode($response, [Response::HTTP_OK, Response::HTTP_CREATED, Response::HTTP_ACCEPTED, Response::HTTP_NO_CONTENT, Response::HTTP_CONFLICT], 'POST', 'contactform');
}
/**
* @throws ApiException
*/
public function submitApplication(array $applicationData): void
{
$response = $this->request('POST', 'applications', [
'json' => $applicationData,
]);
// A conflict means the submission is already known, which is the normal answer to a
// double-clicked submit button and not worth reporting.
$this->assertStatusCode($response, [Response::HTTP_OK, Response::HTTP_CREATED, Response::HTTP_ACCEPTED, Response::HTTP_NO_CONTENT, Response::HTTP_CONFLICT], 'POST', 'applications');
$this->drainResponse($response);
}
/**
@@ -199,6 +217,30 @@ class ApiClient implements LoggerAwareInterface
*/
private function request(string $method, string $uri, array $options = []): ResponseInterface
{
$response = $this->sendRequest($method, $uri, $options);
if (false === in_array($this->readStatusCode($response, $method, $uri), self::UNAUTHORIZED_STATUS_CODES, true)) {
return $response;
}
// The token outlives a single PHP request, so one the API has stopped accepting - after
// a MyEP restart or a revoked client - would keep failing every call for the rest of its
// cached lifetime unless it is actively discarded here.
$this->logWarning(sprintf('MyEP API rejected the cached access token for %s %s, re-authenticating once', $method, $uri));
$this->discardAccessToken();
return $this->sendRequest($method, $uri, $options);
}
/**
* @throws ApiException
*/
private function sendRequest(string $method, string $uri, array $options): ResponseInterface
{
// Resolved here rather than baked into the client's default options so that the shared
// client survives a token change, and so the retry above picks up the fresh token.
$options['auth_bearer'] = $this->getAccessToken($this->getConfiguration())->getToken();
try {
return $this->getHttpClient()->request($method, $uri, $options);
} catch (TransportExceptionInterface $e) {
@@ -215,13 +257,7 @@ class ApiClient implements LoggerAwareInterface
*/
private function assertStatusCode(ResponseInterface $response, array $expectedStatusCodes, string $method, string $uri): void
{
try {
$statusCode = $response->getStatusCode();
} catch (TransportExceptionInterface $e) {
$message = sprintf('MyEP API transport error while reading status for %s %s: %s', $method, $uri, $e->getMessage());
$this->logError($message, ['exception' => $e]);
throw new ApiException($message, 0, $e);
}
$statusCode = $this->readStatusCode($response, $method, $uri);
if (true === in_array($statusCode, $expectedStatusCodes, true)) {
return;
@@ -233,6 +269,39 @@ class ApiClient implements LoggerAwareInterface
throw new ApiException($message, $statusCode);
}
/**
* Reading the status completes the transfer, so this is also what turns the lazy response
* returned by the client into a finished request. Symfony keeps the status on the response,
* so calling this twice costs nothing.
*
* @throws ApiException
*/
private function readStatusCode(ResponseInterface $response, string $method, string $uri): int
{
try {
return $response->getStatusCode();
} catch (TransportExceptionInterface $e) {
$message = sprintf('MyEP API transport error while reading status for %s %s: %s', $method, $uri, $e->getMessage());
$this->logError($message, ['exception' => $e]);
throw new ApiException($message, 0, $e);
}
}
/**
* Reads and discards a body nobody else is going to look at. Destroying an unconsumed
* response cancels the transfer, which closes the connection instead of returning it to
* the pool, so the next call would have to handshake again.
*/
private function drainResponse(ResponseInterface $response): void
{
try {
$response->getContent(false);
} catch (TransportExceptionInterface $e) {
// The status has already been asserted, so a failure here costs nothing but the
// connection reuse this method exists for.
}
}
/**
* @throws ApiException
*/
@@ -253,13 +322,13 @@ class ApiClient implements LoggerAwareInterface
private function getHttpClient(): HttpClientInterface
{
if (null !== static::$httpClient) {
return static::$httpClient;
}
$config = $this->getConfiguration();
static::$accessToken = $this->getAccessToken($config);
$options = [
'auth_bearer' => static::$accessToken->getToken(),
];
$options = [];
// Without these the client falls back to PHP's default_socket_timeout (commonly 60s),
// so a stalled API pins a PHP worker for a minute per request. The defaults live in
@@ -277,7 +346,7 @@ class ApiClient implements LoggerAwareInterface
$options['max_duration'] = $maxDuration;
}
return HttpClient::createForBaseUri($config['myEpApiBaseUrl'], $options);
return static::$httpClient = HttpClient::createForBaseUri($config['myEpApiBaseUrl'], $options);
}
/**
@@ -312,7 +381,7 @@ class ApiClient implements LoggerAwareInterface
*/
private function getAccessToken(array $config): AccessToken
{
if (null !== static::$accessToken && false === static::$accessToken->hasExpired()) {
if (true === $this->isTokenUsable(static::$accessToken)) {
return static::$accessToken;
}
@@ -321,7 +390,7 @@ class ApiClient implements LoggerAwareInterface
$cachedToken = $this->getCache()->get(self::ACCESS_TOKEN_CACHE_IDENTIFIER);
if (is_array($cachedToken) && isset($cachedToken['access_token'])) {
$token = new AccessToken($cachedToken);
if (false === $token->hasExpired()) {
if (true === $this->isTokenUsable($token)) {
static::$accessToken = $token;
return static::$accessToken;
@@ -329,7 +398,7 @@ class ApiClient implements LoggerAwareInterface
}
try {
static::$accessToken = $this->getProvider($config)->getAccessToken('client_credentials');
static::$accessToken = $this->normalizeToken($this->getProvider($config)->getAccessToken('client_credentials'));
$this->cacheAccessToken(static::$accessToken);
} catch (IdentityProviderException $e) {
$message = sprintf('MyEP OAuth token request failed: %s', $e->getMessage());
@@ -348,16 +417,53 @@ class ApiClient implements LoggerAwareInterface
return static::$accessToken;
}
private function cacheAccessToken(AccessToken $token): void
/**
* AccessToken::hasExpired() throws for a token that reports no expiry, so it cannot be used
* as the check - a token without one is simply treated as unusable and replaced. The same
* margin as the cache lifetime is applied on read as well, so a token cannot lapse between
* this check and the API call that uses it, whichever node wrote the cache entry.
*/
private function isTokenUsable(?AccessToken $token): bool
{
if (null === $token) {
return false;
}
$expires = $token->getExpires();
if (null === $expires) {
$lifetime = self::ACCESS_TOKEN_DEFAULT_TTL;
} else {
$lifetime = $expires - time() - self::ACCESS_TOKEN_EXPIRY_MARGIN;
return false;
}
return $expires - self::ACCESS_TOKEN_EXPIRY_MARGIN > time();
}
/**
* A token that reports no expiry cannot be validated on read - isTokenUsable() rejects it
* and AccessToken::hasExpired() throws for it - so it is given the fallback lifetime here,
* once, and the rest of the class can treat every token the same way.
*/
private function normalizeToken(AccessToken $token): AccessToken
{
if (null !== $token->getExpires()) {
return $token;
}
return new AccessToken($token->jsonSerialize() + ['expires_in' => self::ACCESS_TOKEN_DEFAULT_TTL]);
}
private function discardAccessToken(): void
{
static::$accessToken = null;
$this->getCache()->remove(self::ACCESS_TOKEN_CACHE_IDENTIFIER);
}
private function cacheAccessToken(AccessToken $token): void
{
// normalizeToken() has already given a token without a reported expiry the fallback
// lifetime, so there is always a real expiry to subtract the margin from here.
$lifetime = $token->getExpires() - time() - self::ACCESS_TOKEN_EXPIRY_MARGIN;
if ($lifetime <= 0) {
return;
}
@@ -0,0 +1,233 @@
<?php
namespace EP\EpProducts\Service;
use EP\EpProducts\MyEP\ApiClient;
use EP\EpProducts\MyEP\ApiException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Reads the product export from GET /api/exports/products on MyE&P. The rows
* already have the shape {@see DateImportService::import()} consumes, so they
* are passed on unchanged.
*
* Change detection compares GET /api/last-update against the
* `meta.sourceGeneratedAt` of the last successfully imported export, kept in
* var/transient/ep_products_import/api-imported.info. Both carry the BusPro
* export's own timestamp.
*/
final class ApiImportSource implements ProductImportSource, SingletonInterface, LoggerAwareInterface
{
use LoggerAwareTrait;
/**
* The whole export is one page at current volumes; the walk does not rely on it.
*/
private const PER_PAGE = 500;
/**
* How often the walk restarts when MyE&P replaces its copy of the export
* mid-walk before giving up until the next run.
*/
private const MAX_WALKS = 3;
private const STAGING_SUBDIR = 'ep_products_import';
private const BASELINE_FILE = 'api-imported.info';
private const IMPORT_MARKER = 'fileadmin/products_import.info';
/**
* @var ApiClient|null
*/
private $apiClient;
public function __construct(?ApiClient $apiClient = null)
{
$this->apiClient = $apiClient;
}
/**
* The whole export is fetched before anything is returned, so a walk that
* has to restart never leaves a stitched dataset behind.
*
* @throws ApiException
*/
public function acquire(): ?ProductImport
{
if (!$this->isNewImportAvailable()) {
return null;
}
for ($walk = 1; $walk <= self::MAX_WALKS; $walk++) {
$export = $this->walkPages();
if ($export === false) {
continue;
}
if ($export === null) {
return null;
}
[$rows, $sourceGeneratedAt] = $export;
$baseline = $this->getImportedTimestamp();
if ($baseline !== null && $sourceGeneratedAt <= $baseline) {
return null;
}
return new ProductImport($rows, $sourceGeneratedAt);
}
throw new ApiException(sprintf(
'MyE&P replaced its product export during each of %d page walks, giving up until the next run',
self::MAX_WALKS
));
}
public function markImported(ProductImport $import): void
{
$sourceGeneratedAt = $import->getSourceGeneratedAt();
if ($sourceGeneratedAt !== null) {
$file = $this->baselinePath();
GeneralUtility::mkdir_deep(dirname($file));
GeneralUtility::writeFile($file, $sourceGeneratedAt->format(\DateTimeInterface::ATOM), false);
}
(new ImportTimestampService())->writeImportTimestamp(self::IMPORT_MARKER);
}
/**
* True when MyE&P reports an export newer than the last imported one, or
* nothing has been imported yet. A missing timestamp from MyE&P means
* "not importable now", never "import".
*
* @throws ApiException
*/
public function isNewImportAvailable(): bool
{
$lastUpdateAt = $this->getApiClient()->getLastUpdateAt();
if ($lastUpdateAt === null) {
return false;
}
$baseline = $this->getImportedTimestamp();
return $baseline === null || $lastUpdateAt > $baseline;
}
/**
* `meta.sourceGeneratedAt` of the last successfully imported export.
*/
public function getImportedTimestamp(): ?\DateTimeImmutable
{
$file = $this->baselinePath();
if (!is_file($file)) {
return null;
}
return $this->parseTimestamp(trim((string) file_get_contents($file)));
}
/**
* @return array{0: array[], 1: \DateTimeImmutable}|false|null the rows and
* the export's timestamp; null when the export is not importable now;
* false when the export changed mid-walk and the walk must restart
* @throws ApiException
*/
private function walkPages()
{
$rows = [];
$sourceGeneratedAt = null;
$page = 1;
do {
$body = $this->getApiClient()->getProductExport($page, self::PER_PAGE);
$meta = $body['meta'] ?? null;
if (!is_array($meta) || !isset($body['data']) || !is_array($body['data'])) {
throw new ApiException(sprintf('MyE&P product export page %d is malformed', $page));
}
$pageGeneratedAt = $this->parseTimestamp($meta['sourceGeneratedAt'] ?? null);
if ($page === 1) {
if ($pageGeneratedAt === null) {
$this->logWarning('MyE&P product export has no source timestamp; skipping product import');
return null;
}
$sourceGeneratedAt = $pageGeneratedAt;
} elseif ($pageGeneratedAt === null || $pageGeneratedAt != $sourceGeneratedAt) {
$this->logWarning('MyE&P product export changed during the page walk; restarting', [
'page' => $page,
'expected' => $sourceGeneratedAt->format(\DateTimeInterface::ATOM),
'actual' => $meta['sourceGeneratedAt'] ?? null,
]);
return false;
}
foreach ($body['data'] as $row) {
$rows[] = $row;
}
$totalPages = (int) ($meta['totalPages'] ?? 0);
$page++;
} while ($page <= $totalPages);
$total = (int) ($meta['total'] ?? -1);
if (count($rows) !== $total) {
throw new ApiException(sprintf(
'MyE&P product export is incomplete: %d rows received, %d announced',
count($rows),
$total
));
}
if ((int) ($meta['skipped'] ?? 0) > 0) {
$this->logWarning('MyE&P skipped travel dates with unparseable dates', ['skipped' => $meta['skipped']]);
}
if ((int) ($meta['pickupsWithoutMasterData'] ?? 0) > 0) {
$this->logWarning(
'MyE&P product export has pickups without master data',
['pickupsWithoutMasterData' => $meta['pickupsWithoutMasterData']]
);
}
return [$rows, $sourceGeneratedAt];
}
/**
* @param mixed $value
*/
private function parseTimestamp($value): ?\DateTimeImmutable
{
if (!is_string($value) || $value === '') {
return null;
}
try {
return new \DateTimeImmutable($value);
} catch (\Exception $e) {
return null;
}
}
private function getApiClient(): ApiClient
{
if ($this->apiClient === null) {
$this->apiClient = GeneralUtility::makeInstance(ApiClient::class);
}
return $this->apiClient;
}
private function baselinePath(): string
{
return Environment::getVarPath() . '/transient/' . self::STAGING_SUBDIR . '/' . self::BASELINE_FILE;
}
private function logWarning(string $message, array $context = []): void
{
if ($this->logger !== null) {
$this->logger->warning($message, $context);
}
}
}
@@ -50,6 +50,42 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
const STATUS_ON_REQUEST = 'Anfrage';
const STATUS_STOP = 'Buchungsstop';
/**
* BusPro ids of the selection groups whose selections make up the included
* services. Matched by id rather than by label, so a group renamed upstream
* does not silently drop out of services_included.
*/
const SELECTION_GROUP_SKIPASS = 7;
const SELECTION_GROUP_OTHER = 8;
const SELECTION_GROUP_BOARD = 71;
const SELECTION_GROUP_ACCOMMODATION = 85;
const SELECTION_GROUP_PROGRAMME = 86;
const SELECTION_GROUP_COURSES = 87;
const SELECTION_GROUP_EVENTS = 89;
const SELECTION_GROUP_TRANSPORTATION = 90;
/**
* Group 'Kunde' also carries trip types (Wochenreise, Midweekreise, ...), so
* group travel keys on the selection, not on the group's presence. Every
* date should carry either 'Gruppenkunde' or 'Endkunde'.
*/
const SELECTION_GROUP_CUSTOMER = 96;
const SELECTION_CUSTOMER_GROUP = 1418;
const SELECTION_CUSTOMER_END = 1419;
/**
* Fallback for dates the office has not tagged with either selection: these
* trip type markers in front of the travel code's trailing date mean
* end-customer travel.
*/
const END_CUSTOMER_CODE_PATTERN = '/(?:MP|WE|KT|PM|MW|FA)\d{6}$/';
/**
* 'Leistungen Personal' occurs in no export so far, so its id is unknown and
* it is still matched by label. Register its id once the warning fires.
*/
const SELECTION_GROUP_LABEL_PERSONNEL = 'Leistungen Personal';
/**
* @var ConfigurationManagerInterface
*/
@@ -60,21 +96,11 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
*/
protected $pid = 0;
/**
* @var array
*/
protected $roomMappings = [];
/**
* @var array
*/
protected $hotelMappings = [];
/**
* @var array
*/
protected $pickups = [];
/**
* @var Connection
*/
@@ -90,6 +116,11 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
*/
protected $importSourceFactory;
/**
* @var RoomTypeResolver
*/
protected $roomTypeResolver;
/**
* @var array
*/
@@ -101,15 +132,18 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
* @param ConfigurationManagerInterface $configurationManager
* @param CacheService $cacheService
* @param ProductImportSourceFactory $importSourceFactory
* @param RoomTypeResolver $roomTypeResolver
*/
public function __construct(
ConfigurationManagerInterface $configurationManager,
CacheService $cacheService,
ProductImportSourceFactory $importSourceFactory
ProductImportSourceFactory $importSourceFactory,
RoomTypeResolver $roomTypeResolver
) {
$this->configurationManager = $configurationManager;
$this->cacheService = $cacheService;
$this->importSourceFactory = $importSourceFactory;
$this->roomTypeResolver = $roomTypeResolver;
$settings = GeneralUtility::removeDotsFromTS(
$this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT)
@@ -123,19 +157,18 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
}
/**
* @param string $path
* @param iterable<array> $rows one row per travel date × hotel, in the shape
* of GET /api/exports/products on MyE&P
* @return int
* @throws \Doctrine\DBAL\DBALException
*/
public function import($path): int
public function import(iterable $rows): int
{
$this->db = $this->getDbConnection();
$this->getRoomMappings();
$this->getHotelMappings();
$this->importPickups($path);
$this->createTempTables();
$this->logger->info('starting product import');
$dateCount = $this->parseXmlFilesForProducts($path);
$dateCount = $this->importProducts($rows);
$this->clearTables();
$this->copyTables();
$this->clearTempTables();
@@ -149,50 +182,44 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
return $this->importSourceFactory->get()->isNewImportAvailable();
}
public function parseXmlFilesForProducts($path): int
/**
* Groups the rows by product and travel date, in the order they first
* appear, because a product code can map to more than one TYPO3 product and
* each of them imports all of the product's dates.
*
* @param iterable<array> $rows
* @return int
*/
protected function importProducts(iterable $rows): int
{
$dateCount = 0;
$folder = opendir($path);
while (($fileName = readdir($folder)) !== false) {
if (strpos($fileName, 'Ziel') === 0) {
$filePath = $path . '/' . $fileName;
$dateCount += $this->parseProductXmlFile($filePath);
$products = [];
foreach ($rows as $row) {
$code = $row['product']['code'];
if (!isset($products[$code])) {
$products[$code] = ['busProId' => (int) $row['product']['busProId'], 'dates' => []];
}
$products[$code]['dates'][(int) $row['date']['busProId']][] = $row;
}
$dateCount = 0;
foreach ($products as $code => $product) {
$dateCount += $this->importProduct((string) $code, $product['busProId'], $product['dates']);
}
return $dateCount;
}
/**
* @param string $file
* @return int
* Recreated on every run, so the temp tables always follow the schema of the
* live tables (a column type change would otherwise survive in them) and a
* crashed import cannot leave rows behind for the next one.
*/
public function parseProductXmlFile($file): int
{
if (!file_exists($file)) {
$this->logger->error('product xml not found', ['file' => $file]);
return 0;
}
libxml_use_internal_errors(true);
/** @var \SimpleXMLElement $xmlData */
if (!$xmlData = simplexml_load_string(file_get_contents($file))) {
libxml_clear_errors();
return 0;
}
if ($xmlData->reise[0] === null) {
return 0;
}
return $this->parseProduct($xmlData->reise[0]);
}
public function createTempTables(): void
{
$this->db->executeStatement('CREATE TABLE IF NOT EXISTS tx_epproducts_domain_model_date_temp LIKE tx_epproducts_domain_model_date');
$this->db->executeStatement('CREATE TABLE IF NOT EXISTS tx_epproducts_domain_model_room_temp LIKE tx_epproducts_domain_model_room');
$this->db->executeStatement('DROP TABLE IF EXISTS tx_epproducts_domain_model_date_temp');
$this->db->executeStatement('DROP TABLE IF EXISTS tx_epproducts_domain_model_room_temp');
$this->db->executeStatement('CREATE TABLE tx_epproducts_domain_model_date_temp LIKE tx_epproducts_domain_model_date');
$this->db->executeStatement('CREATE TABLE tx_epproducts_domain_model_room_temp LIKE tx_epproducts_domain_model_room');
}
public function clearTables(): void
@@ -214,13 +241,13 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
}
/**
* @param \SimpleXMLElement $xmlProduct
* @param string $code
* @param int $busProId
* @param array[][] $dates rows grouped by travel date
* @return int
*/
protected function parseProduct(\SimpleXMLElement $xmlProduct): int
protected function importProduct(string $code, int $busProId, array $dates): int
{
$code = (string) $xmlProduct->attributes()['code'];
$busProId = (int) $xmlProduct->attributes()['idbuspro'];
$dateCount = 0;
$sql = '
@@ -258,8 +285,8 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
$product['bus_pro_id'] = $busProId;
$product['product_fact'] = $this->getTopFactForRecord('tx_epproducts_product_fact_mm', $product['uid']);
$product['region_fact'] = $this->getTopFactForRecord('tx_epproducts_region_fact_mm', $product['region']);
foreach ($xmlProduct->termin as $xmlDate) {
$dateCount += $this->parseDates($xmlDate, $product);
foreach ($dates as $rows) {
$dateCount += $this->importDate($rows, $product);
}
}
@@ -267,25 +294,21 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
}
/**
* @param \SimpleXMLElement $xmlDate
* @param array[] $rows one per hotel of the travel date
* @param array $product
* @return int
*/
protected function parseDates(\SimpleXMLElement $xmlDate, array $product): int
protected function importDate(array $rows, array $product): int
{
$dateCount = 0;
// $earliestDate = new \DateTimeImmutable('next year');
foreach ($xmlDate->hotel as $xmlHotel) {
// don't import dates starting later than one year from now
// $dateStart = \DateTime::createFromFormat('d.m.Y', (string) $xmlDate->attributes()['termin']);
// if ($dateStart > $earliestDate) {
// continue;
// }
// Selection groups are date-level, so any hotel row tells.
$this->checkCustomerSelection(reset($rows));
$date = $this->createDateRecord($product, $xmlDate);
foreach ($rows as $row) {
$date = $this->createDateRecord($product, $row);
$hotelCode = (string) $xmlHotel->attributes()['code'];
$hotelCode = $row['hotel']['code'];
$key = $hotelCode . $date['date_start'];
// Import daytrip dates only once per hotel as room information is taken
@@ -294,7 +317,7 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
continue;
}
if ($this->parseHotel($xmlHotel, $date) !== false) {
if ($this->parseHotel($row, $date) !== false) {
$this->db->insert(
'tx_epproducts_domain_model_date_temp',
$date
@@ -320,17 +343,17 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
/**
* @param array $product
* @param \SimpleXMLElement $xmlDate
* @param array $row
* @return array
*/
protected function createDateRecord(array $product, \SimpleXMLElement $xmlDate): array
protected function createDateRecord(array $product, array $row): array
{
$dateStart = \DateTime::createFromFormat('d.m.Y', (string) $xmlDate->attributes()['termin']);
$dateEnd = \DateTime::createFromFormat('d.m.Y', (string) $xmlDate->attributes()['bis']);
$dateStart = \DateTime::createFromFormat('Y-m-d', $row['date']['from']);
$dateEnd = \DateTime::createFromFormat('Y-m-d', $row['date']['to']);
$nights = $dateStart->diff($dateEnd)->format('%d');
$busProId = (int) $xmlDate->attributes()['idbuspro'];
$code = (string) $xmlDate->attributes()['code'];
$busProId = (int) $row['date']['busProId'];
$code = (string) $row['date']['code'];
$date = [
'pid' => $this->pid,
@@ -373,15 +396,15 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
'important' => $product['important'],
];
$includedAccommodation = $this->parseSelectionGroup($xmlDate, 'Leistungen Übernachtung');
$includedSkiPass = $this->parseSelectionGroup($xmlDate, 'Leistungen Skipass');
$includedBoard = $this->parseSelectionGroup($xmlDate, 'Leistungen Verpflegung');
$includedTransportation = $this->parseSelectionGroup($xmlDate, 'Leistungen Transport');
$includedProgramme = $this->parseSelectionGroup($xmlDate, 'Leistungen Programm');
$includedPersonnel = $this->parseSelectionGroup($xmlDate, 'Leistungen Personal');
$includedEvents = $this->parseSelectionGroup($xmlDate, 'Leistungen Events');
$includedOther = $this->parseSelectionGroup($xmlDate, 'Leistungen Sonstige');
$includedCourses = $this->parseSelectionGroup($xmlDate, 'Leistungen Kurse');
$includedAccommodation = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_ACCOMMODATION);
$includedSkiPass = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_SKIPASS);
$includedBoard = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_BOARD);
$includedTransportation = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_TRANSPORTATION);
$includedProgramme = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_PROGRAMME);
$includedPersonnel = $this->parsePersonnelSelectionGroup($row['selectionGroups']);
$includedEvents = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_EVENTS);
$includedOther = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_OTHER);
$includedCourses = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_COURSES);
$includedServices = [
...$includedAccommodation,
@@ -406,7 +429,9 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
$skiPassIncluded = (int) (count($includedSkiPass) > 0);
$date['skipass_included'] = $skiPassIncluded;
$servicesTransportation = $this->parseService($xmlDate, 'lei_befoerderung');
$date['group_travel'] = (int) $this->isGroupTravel($row);
$servicesTransportation = $this->parseService($row['transportServices']);
$discount = $this->determineDiscount($servicesTransportation);
$date['discount'] = $discount;
@@ -428,11 +453,11 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
if ($discount) {
$servicesTransportationOptional[] = [
'label' => 'Rabatt bei Eigenanreise',
'price' => $discount,
'price' => number_format($discount, 2, ',', '.'),
];
}
$servicesGeneral = $this->parseService($xmlDate, 'lei_sonstiges');
$servicesGeneral = $this->parseService($row['dateServices']);
$combinedServices = [];
@@ -454,29 +479,22 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
$date['services_general'] = serialize($combinedServices);
$pickups = [];
foreach ($xmlDate->xpath('zustiege/zustieg') as $pickup) {
$attributes = $pickup->attributes();
if (null === $attributes) {
continue;
}
$busProId = (int) $attributes['idbuspro'];
foreach ($row['pickups'] as $pickup) {
$busProId = (int) $pickup['busProId'];
if ($busProId === 0) {
continue;
}
$timestamp = (string) $attributes['zeit'];
$parts = explode(' ', $timestamp);
if (2 === count($parts)) {
[$pickupDate, $timePart] = $parts;
$pickupTime = substr($timePart, 0, 5);
} else {
$pickupDate = $dateStart->format('d.m.Y');
$pickupTime = $parts[0];
$pickupDate = $dateStart->format('d.m.Y');
$pickupTime = '';
if ($pickup['datetime'] !== null) {
[$pickupDate, $pickupTime] = $this->parsePickupDateTime($pickup['datetime']);
}
$pickups[] = [
'bus_pro_id' => $busProId,
'city' => $this->pickups[$busProId]['city'],
'street' => $this->pickups[$busProId]['street'],
'price' => (float) str_replace(',', '.', (string) $attributes['preis']),
'city' => $pickup['city'],
'street' => $pickup['street'],
// A pickup without a stated price has always been shown as included.
'price' => $pickup['price'] === null ? 0.0 : (float) $pickup['price'],
'date' => $pickupDate,
'time' => $pickupTime,
];
@@ -493,21 +511,20 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
});
$date['pickups'] = serialize($pickups);
$guide = $this->parseGuide($xmlDate);
$date['guide'] = serialize($guide);
$date['guide'] = serialize($row['guide'] ?? []);
return $date;
}
/**
* @param \SimpleXMLElement $xmlHotel
* @param array $row
* @param array $date
* @return bool
*/
protected function parseHotel(\SimpleXMLElement $xmlHotel, array &$date): bool
protected function parseHotel(array $row, array &$date): bool
{
$code = (string) $xmlHotel->attributes()['code'];
$busProId = (string) $xmlHotel->attributes()['idbuspro'];
$code = $row['hotel']['code'];
$busProId = (int) $row['hotel']['busProId'];
if (!array_key_exists($code, $this->hotelMappings)) {
$this->logger->warning('hotel not found', ['code' => $code]);
@@ -520,7 +537,7 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
$services = [];
$generalServices = unserialize($date['services_general']);
$hotelServices = $this->parseService($xmlHotel, 'lei_sonstiges', true);
$hotelServices = $this->parseService($row['hotelServices'], true);
$this->addServices($generalServices, $services);
$this->addServices($hotelServices, $services);
foreach ($services as $key => $list) {
@@ -530,7 +547,7 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
$services[$key] = $list;
}
$this->parseRooms($xmlHotel, $hotel['uid'], $date, $services);
$this->parseRooms($row, $hotel['uid'], $date, $services);
$date['hotel'] = $hotel['uid'];
$date['hotel_code'] = $hotel['code'];
@@ -549,108 +566,91 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
return true;
}
protected function parseGuide(\SimpleXMLElement $xmlDate)
{
$transportationServicesBus = $xmlDate->xpath('lei_befoerderung/leistung[@unterart="BUS"]');
foreach ($transportationServicesBus as $service) {
if ('RUECK' === (string) $service->richtung) {
continue;
}
if (false === isset($service->zustiegsplanung->reiseleiter)) {
continue;
}
return [
'name' => (string) $service->zustiegsplanung->reiseleiter->name,
'phone' => (string) $service->zustiegsplanung->reiseleiter->telefon,
];
}
return [];
}
/**
* @param \SimpleXMLElement $xmlHotel
* @param array $row
* @param int $hotelUid
* @param array $date
* @param array $services
*/
protected function parseRooms(\SimpleXMLElement $xmlHotel, $hotelUid, array &$date, array $services): void
protected function parseRooms(array $row, $hotelUid, array &$date, array $services): void
{
$minPriceOverall = 0;
$minPriceAvailable = 0;
$minPriceOverall = 0.0;
$minPriceAvailable = 0.0;
$minPax = 0;
$availableTotal = 0;
$boardCode = '';
$count = 0;
foreach ($xmlHotel->xpath('zimmer/preis') as $roomXml) {
$code = trim((string) $roomXml->attributes()['zimmercode']);
if ($row['pseudoPrice'] !== null) {
$date['pseudo_price'] = (float) $row['pseudoPrice'];
}
if ($code === static::CODE_PSEUDOPRICE) {
$price = (int) $roomXml->attributes()['preis'];
$date['pseudo_price'] = $price;
continue;
}
foreach ($row['rooms'] as $roomRow) {
$code = $roomRow['code'];
$label = $roomRow['label'];
$roomMinPax = (int) $roomRow['minPax'];
$pax = (int) $roomRow['maxPax'];
$roomTypeKey = mb_strtolower($code);
if (array_key_exists($roomTypeKey, $this->roomMappings)) {
$roomType = $this->roomMappings[$roomTypeKey];
} else {
$this->logger->warning('room type not found', ['code' => $code]);
continue;
}
$available = (int) $roomXml->attributes()['verfuegbar'];
$price = (int) $roomXml->attributes()['preis'];
$available = (int) $roomRow['available'];
$price = (float) $roomRow['price'];
// Skip rooms with zero price _and_ zero availability.
if (!$available && !$price) {
continue;
}
$pax = (int) $roomXml->attributes()['MinPax'];
if (0 === $minPax || $pax < $minPax) {
$minPax = $pax;
$roomType = $this->roomTypeResolver->resolve($code, $label, $pax, $roomMinPax);
if ($pax < 1 && $roomMinPax < 1) {
$this->logger->warning('room without occupancy', ['code' => $code, 'zimmertext' => $label]);
}
if ($this->roomTypeResolver->needsReview($code, $label, $pax)) {
$this->logger->warning(
'single-occupancy room without single-use marker',
['code' => $code, 'zimmertext' => $label]
);
}
if (0 === $minPax || $roomMinPax < $minPax) {
$minPax = $roomMinPax;
}
$pax = (int) $roomXml->attributes()['MaxPax'];
$availableTotal += $available * $pax;
// Determine lowest price of available rooms
if ($code !== static::CODE_BABYROOM && $available > 0 && ($minPriceAvailable === 0 || $price < $minPriceAvailable)) {
if ($code !== static::CODE_BABYROOM && $available > 0 && ($minPriceAvailable === 0.0 || $price < $minPriceAvailable)) {
$minPriceAvailable = $price;
}
// Determine lowest overall price
if ($code !== static::CODE_BABYROOM && ($minPriceOverall === 0 || $price < $minPriceOverall)) {
if ($code !== static::CODE_BABYROOM && ($minPriceOverall === 0.0 || $price < $minPriceOverall)) {
$minPriceOverall = $price;
}
// Determine status
$statusXml = (string) $roomXml->attributes()['status'];
$sourceStatus = $roomRow['status'];
if (static::STATUS_STOP === $statusXml && $price) {
if (static::STATUS_STOP === $sourceStatus && $price) {
$status = Room::ROOM_STATUS_FULLY_BOOKED;
} elseif (static::STATUS_ON_REQUEST === $statusXml) {
} elseif (static::STATUS_ON_REQUEST === $sourceStatus) {
$status = Room::ROOM_STATUS_ON_REQUEST;
} else {
$status = Room::ROOM_STATUS_AVAILABLE;
}
$boardCode = (string) $roomXml->attributes()['vpcode'];
$boardCode = $roomRow['boardCode'];
$room = [
'pid' => $this->pid,
'date' => 0,
'hotel' => $hotelUid,
'bus_pro_id' => (int) $roomXml->attributes()['idbuspro_zimmer'],
'bus_pro_id' => (int) $roomRow['busProId'],
'code' => $code,
'type' => $roomType,
'name' => (string) $roomXml->attributes()['zimmertext'],
'name' => $label,
'pax' => $pax,
'nights' => (int) $roomXml->attributes()['naechte'],
'nights' => (int) $roomRow['nights'],
'price' => $price,
'available' => $available * $pax,
'status' => $status,
@@ -674,45 +674,43 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
/**
* @param array $services
* @return int
* @return float
*/
protected function determineDiscount(array $services): int
protected function determineDiscount(array $services): float
{
foreach ($services as $key => $section) {
foreach ($section as $service) {
if ($service['price'] < 0) {
return (int) $service['price'];
$price = $this->parseFormattedPrice($service['price']);
if ($price < 0) {
return $price;
}
}
}
return 0;
return 0.0;
}
/**
* @param \SimpleXMLElement $xmlData
* @param string $serviceLabel
* @param array[] $services a service list of a row
* @param bool $skipWithoutPrice
* @return array
*/
protected function parseService(\SimpleXMLElement $xmlData, string $serviceLabel, bool $skipWithoutPrice = false): array
protected function parseService(array $services, bool $skipWithoutPrice = false): array
{
$data = [];
$services = $xmlData->xpath($serviceLabel . '/leistung');
foreach ($services as $service) {
// Skip transportation service direction 'back'
if ($service->richtung && (string) $service->richtung === 'RUECK') {
if ($service['direction'] === 'RUECK') {
continue;
}
// Skip services with status 'Buchungsstop'
$status = (string) $service->status;
if ($status === 'Buchungsstop') {
if ($service['status'] === static::STATUS_STOP) {
continue;
}
// Skip services of subcategory 'EIN'
$type = (string) $service->attributes()['unterart'];
$type = $service['subType'];
if ($type === 'EIN') {
continue;
}
@@ -722,13 +720,14 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
$type = 'VER';
}
$price = (float) str_replace(',', '.', $service->preis);
// A service without a stated price has always been shown as included.
$price = $service['price'] === null ? 0.0 : (float) $service['price'];
if ($skipWithoutPrice && $price === 0.0) {
continue;
}
$label = (string) $service->text;
$label = $service['label'];
if ($type === 'BUS') {
$label = static::LABEL_BUS;
} elseif ($type === 'BAH') {
@@ -739,8 +738,8 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
$data[$type] = [];
}
$data[$type][(int)$service->attributes()['id']] = [
'idBusPro' => (int) $service->attributes()['idbuspro'],
$data[$type][(int) $service['busProId']] = [
'idBusPro' => (int) $service['busProId'],
'label' => $label,
'price' => number_format($price, 2, ',', '.'),
];
@@ -752,21 +751,17 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
}
/**
* @param \SimpleXMLElement $xmlDate
* @param string $label
* @param array[] $selectionGroups
* @param int $busProId
* @return array
*/
protected function parseSelectionGroup(\SimpleXMLElement $xmlDate, string $label): array
protected function parseSelectionGroup(array $selectionGroups, int $busProId): array
{
$data = [];
$selectionGroup = $xmlDate->xpath('selektiongruppe[@bezeichnung="' . $label . '"]/selektion');
foreach ($selectionGroup as $selection) {
$attributes = $selection->attributes();
if (null === $attributes) {
continue;
foreach ($selectionGroups as $group) {
if ((int) $group['busProId'] === $busProId) {
$this->addSelections($group['selections'], $data);
}
$id = (int) $attributes['idbuspro'];
$data[$id] = (string) $attributes['bezeichnung'];
}
ksort($data);
@@ -774,6 +769,83 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
return $data;
}
/**
* @param array[] $selectionGroups
* @return array
*/
protected function parsePersonnelSelectionGroup(array $selectionGroups): array
{
$data = [];
foreach ($selectionGroups as $group) {
if ($group['label'] !== static::SELECTION_GROUP_LABEL_PERSONNEL) {
continue;
}
$this->logger->warning(
'selection group matched by label, register its id',
['label' => $group['label'], 'idbuspro' => (int) $group['busProId']]
);
$this->addSelections($group['selections'], $data);
}
ksort($data);
return $data;
}
/**
* 'Gruppenkunde' and 'Endkunde' decide. A date carrying neither is judged by
* its travel code.
*
* @param array $row
* @return bool
*/
protected function isGroupTravel(array $row): bool
{
$customer = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_CUSTOMER);
$isGroup = isset($customer[static::SELECTION_CUSTOMER_GROUP]);
$isEnd = isset($customer[static::SELECTION_CUSTOMER_END]);
if ($isGroup || $isEnd) {
return $isGroup;
}
return !preg_match(static::END_CUSTOMER_CODE_PATTERN, (string) $row['date']['code']);
}
/**
* Reports dates whose customer selection is missing or contradictory, along
* with what they import as.
*
* @param array $row
*/
protected function checkCustomerSelection(array $row): void
{
$customer = $this->parseSelectionGroup($row['selectionGroups'], static::SELECTION_GROUP_CUSTOMER);
$isGroup = isset($customer[static::SELECTION_CUSTOMER_GROUP]);
$isEnd = isset($customer[static::SELECTION_CUSTOMER_END]);
if ($isGroup !== $isEnd) {
return;
}
$this->logger->warning(
$isGroup
? 'date has both Gruppenkunde and Endkunde selected, importing as group travel'
: 'date has neither Gruppenkunde nor Endkunde selected, falling back to travel code, importing as '
. ($this->isGroupTravel($row) ? 'group travel' : 'end-customer travel'),
['product' => $row['product']['code'], 'date' => $row['date']['code']]
);
}
/**
* @param array[] $selections
* @param array $data
*/
protected function addSelections(array $selections, array &$data): void
{
foreach ($selections as $selection) {
$data[(int) $selection['busProId']] = $selection['label'];
}
}
/**
* @param array $services
* @param array $date
@@ -785,20 +857,42 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
}
foreach ($services['BUS'] as $service) {
$price = $this->parseFormattedPrice($service['price']);
$date['bus_available'] = 1;
$date['bus_price'] = (int) $service['price'];
$date['bus_included'] = (int) ((int) $service['price'] === 0);
$date['bus_price'] = $price;
$date['bus_included'] = (int) ($price === 0.0);
}
}
protected function getRoomMappings(): void
/**
* A pickup time is the local date and time as BusPro states it
* ("2027-03-28T02:45:00"), taken over as is. An ISO-8601 time with an
* offset is still accepted and converted to Europe/Berlin, which cannot
* express a time inside the daylight saving gap.
*
* @param string $datetime
* @return string[] date as d.m.Y and time as H:i
*/
protected function parsePickupDateTime(string $datetime): array
{
$sql = 'SELECT code, type FROM tx_epproducts_domain_model_roommapping WHERE deleted = 0 AND hidden = 0';
$roomMappings = $this->db->fetchAllAssociative($sql);
foreach ($roomMappings as $mapping) {
$key = trim(mb_strtolower($mapping['code']));
$this->roomMappings[$key] = $mapping['type'];
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?$/', $datetime, $parts)) {
return [$parts[3] . '.' . $parts[2] . '.' . $parts[1], $parts[4] . ':' . $parts[5]];
}
$pickupDateTime = (new \DateTimeImmutable($datetime))->setTimezone(new \DateTimeZone('Europe/Berlin'));
return [$pickupDateTime->format('d.m.Y'), $pickupDateTime->format('H:i')];
}
/**
* Reads back a price parseService() formatted for display ("1.234,50").
*
* @param string $price
* @return float
*/
protected function parseFormattedPrice(string $price): float
{
return (float) str_replace(['.', ','], ['', '.'], $price);
}
protected function getHotelMappings(): void
@@ -814,7 +908,9 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
WHERE hotel.code != "" AND hotel.deleted = 0 AND hotel.hidden = 0
UNION SELECT matchcode.code code, matchcode.entity uid
FROM tx_epproducts_domain_model_matchcode matchcode
INNER JOIN tx_epproducts_domain_model_hotel matchcode_hotel ON matchcode.entity = matchcode_hotel.uid
WHERE matchcode.deleted = 0 AND matchcode.hidden = 0
AND matchcode_hotel.deleted = 0 AND matchcode_hotel.hidden = 0
ORDER BY code
) u
LEFT JOIN tx_epproducts_domain_model_hotel h ON u.uid = h.uid
@@ -871,27 +967,4 @@ class DateImportService implements SingletonInterface, LoggerAwareInterface
}
}
protected function importPickups(string $path): void
{
libxml_use_internal_errors (true);
$file = $path . '/zustiege.xml';
if (!is_file($file) || !$xmlData = simplexml_load_string((string) file_get_contents($file))) {
libxml_clear_errors();
$this->logger->warning('pickup xml missing or invalid', ['file' => $file]);
return;
}
foreach ($xmlData->zustieg as $entry) {
$attributes = $entry->attributes();
if (null === $attributes) {
continue;
}
$idBusPro = (int) $attributes['idbuspro'];
$this->pickups[$idBusPro] = [
'city' => (string) $entry->ort,
'street' => (string) $entry->strasse,
];
}
}
}
@@ -230,6 +230,7 @@ class DateService implements SingletonInterface
'summer' => $row['season'] === 's',
'busIncluded' => (bool) $row['dateBusIncluded'],
'skiPassIncluded' => (bool) $row['dateSkiPassIncluded'],
'groupTravel' => (bool) $row['dateGroupTravel'],
'roomUid' => $row['roomUid'],
'roomName' => $row['roomName'],
'available' => $row['roomAvailable'] && $row['roomPrice'],
@@ -320,6 +321,7 @@ class DateService implements SingletonInterface
'nights' => $row['dateNights'],
'busIncluded' => (bool) $row['dateBusIncluded'],
'skiPassIncluded' => (bool) $row['dateSkiPassIncluded'],
'groupTravel' => (bool) $row['dateGroupTravel'],
'servicesIncluded' => unserialize($row['dateServicesIncluded'], ['allowed_classes' => false]),
'servicesGeneral' => unserialize($row['dateServicesGeneral'], ['allowed_classes' => false]),
'season' => $row['season'],
@@ -3,6 +3,7 @@
namespace EP\EpProducts\Service;
use EP\EpProducts\Domain\Model\Dto\FilterOptions;
use EP\EpProducts\Domain\Model\Room;
use EP\EpProducts\Domain\Model\SearchResult;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
@@ -212,6 +213,12 @@ class FilterService implements SingletonInterface
}
}
foreach ($item['rooms'] as $roomType) {
// Type 0 is not a room (Baby) and must never become a filter option:
// it has no label, so it would render as an empty checkbox and leave
// a hole in the option list.
if ((int) $roomType === Room::ROOM_TYPE_UNCLASSIFIED) {
continue;
}
if (!\in_array($roomType, $roomTypes, false)) {
$roomTypes[] = $roomType;
}
@@ -76,11 +76,28 @@ class FilterSettingsEncoder
return implode('|', $encoded);
}
/**
* Decodes an encoded filter settings string.
*
* The format is strictly positional, so a string whose field count does not
* match the mapping cannot be interpreted: every field after a missing one
* would be read into the wrong setting. Such input is rejected outright
* rather than silently producing a shifted - and therefore wrong - result.
*
* @param string $data
* @return array the decoded settings, or an empty array if $data is malformed
*/
public function decode(string $data): array
{
$decoded = [];
$mapping = $this->getMapping();
$values = explode('|', $data);
foreach ($this->getMapping() as $index => $property)
if (count($values) !== count($mapping)) {
return [];
}
$decoded = [];
foreach ($mapping as $index => $property)
{
[$name, $type] = $property;
$value = $values[$index];
@@ -2,6 +2,7 @@
namespace EP\EpProducts\Service;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
@@ -17,16 +18,22 @@ final class LocalImportSource implements ProductImportSource, SingletonInterface
private const UPLOAD_MARKER = 'fileadmin/xmlexport/uebertragung.info';
private const IMPORT_MARKER = 'fileadmin/products_import.info';
public function acquire(): ?string
public function acquire(): ?ProductImport
{
if (!$this->isNewImportAvailable()) {
return null;
}
return GeneralUtility::getFileAbsFileName(self::XML_DIR);
$path = GeneralUtility::getFileAbsFileName(self::XML_DIR);
$reader = new XmlProductReader(
$path,
GeneralUtility::makeInstance(LogManager::class)->getLogger(XmlProductReader::class)
);
return new ProductImport($reader, $reader->getSourceGeneratedAt(), $path);
}
public function markImported(string $path): void
public function markImported(ProductImport $import): void
{
(new ImportTimestampService())->writeImportTimestamp(self::IMPORT_MARKER);
}
@@ -0,0 +1,82 @@
<?php
namespace EP\EpProducts\Service;
use EP\EpProducts\Domain\Model\Hotel;
use EP\EpProducts\Domain\Model\Product;
use EP\EpProducts\Domain\Repository\DateRepository;
/**
* Lists the pickup points of a product's latest upcoming end-customer date that
* has any, with that date's time and round-trip surcharge per pickup point.
* Group travel dates are left out: their pickups are arranged per group and
* are not offered publicly. Pickups, times and prices may differ on other
* dates; taking the latest one keeps the values unique and shows them for as
* long as the product is offered.
*
* The returned shape is meant to be served by MyE&P later on, so that only the
* data source has to change once the local date table goes away.
*/
class PickupOverviewService
{
/**
* @var DateRepository
*/
private $dateRepository;
public function __construct(DateRepository $dateRepository)
{
$this->dateRepository = $dateRepository;
}
/**
* @return array{pickups: array<int, array{busProId: int, city: string, street: string, price: float, time: string}>}
*/
public function getOverview(Product $product, ?Hotel $hotel): array
{
$overview = ['pickups' => []];
if ($hotel === null || $product->isDaytrip()) {
return $overview;
}
$dates = $this->dateRepository->findPickupsForProductAndHotel((int) $product->getUid(), (int) $hotel->getUid());
foreach ($dates as $serializedPickups) {
$pickups = $this->readPickups((string) $serializedPickups);
if ($pickups !== []) {
$overview['pickups'] = $pickups;
break;
}
}
return $overview;
}
/**
* Keeps the order of the import, which is the boarding order.
*/
private function readPickups(string $serializedPickups): array
{
$datePickups = @unserialize($serializedPickups, ['allowed_classes' => false]);
if (!is_array($datePickups)) {
return [];
}
$pickups = [];
foreach ($datePickups as $pickup) {
$busProId = (int) ($pickup['bus_pro_id'] ?? 0);
if ($busProId === 0 || isset($pickups[$busProId])) {
continue;
}
$pickups[$busProId] = [
'busProId' => $busProId,
'city' => (string) ($pickup['city'] ?? ''),
'street' => (string) ($pickup['street'] ?? ''),
// A pickup's price is one leg; the surcharge is split evenly between out- and inbound.
'price' => 2 * (float) ($pickup['price'] ?? 0.0),
'time' => (string) ($pickup['time'] ?? ''),
];
}
return array_values($pickups);
}
}
@@ -0,0 +1,56 @@
<?php
namespace EP\EpProducts\Service;
/**
* One acquired product export: the rows to hand to
* {@see DateImportService::import()}, the source's own timestamp, and whatever
* the source needs to find it again in {@see ProductImportSource::markImported()}.
*/
final class ProductImport
{
/**
* @var iterable<array>
*/
private $rows;
/**
* @var \DateTimeImmutable|null
*/
private $sourceGeneratedAt;
/**
* @var string|null
*/
private $location;
/**
* @param iterable<array> $rows
* @param \DateTimeImmutable|null $sourceGeneratedAt
* @param string|null $location local directory of an XML export, null otherwise
*/
public function __construct(iterable $rows, ?\DateTimeImmutable $sourceGeneratedAt, ?string $location = null)
{
$this->rows = $rows;
$this->sourceGeneratedAt = $sourceGeneratedAt;
$this->location = $location;
}
/**
* @return iterable<array>
*/
public function getRows(): iterable
{
return $this->rows;
}
public function getSourceGeneratedAt(): ?\DateTimeImmutable
{
return $this->sourceGeneratedAt;
}
public function getLocation(): ?string
{
return $this->location;
}
}
@@ -3,25 +3,26 @@
namespace EP\EpProducts\Service;
/**
* A source of the busProNet product export (Ziel_*.xml, zustiege.xml,
* uebertragung.info). Implementations either read a local drop directory or
* pull the files from a remote SFTP server; the caller does not care which.
* A source of the BusPro product export. Implementations read the XML export
* from a local drop directory or a remote SFTP server, or the JSON export from
* the MyE&P API; the caller does not care which.
*/
interface ProductImportSource
{
/**
* Returns a local directory ready to hand to {@see DateImportService::import()},
* Returns the export ready to hand to {@see DateImportService::import()},
* or null when there is nothing newer than the last successful import.
*
* @throws SftpImportException on an unrecoverable acquisition failure
* @throws SftpImportException on an unrecoverable SFTP acquisition failure
* @throws \EP\EpProducts\MyEP\ApiException on an unrecoverable API failure
*/
public function acquire(): ?string;
public function acquire(): ?ProductImport;
/**
* Called once {@see DateImportService::import()} of the acquired path has
* Called once {@see DateImportService::import()} of the acquired export has
* succeeded, so the source can advance its "last imported" bookkeeping.
*/
public function markImported(string $path): void;
public function markImported(ProductImport $import): void;
/**
* Best-effort, side-effect-free check for whether a newer export is available.
@@ -9,18 +9,24 @@ use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Picks the product import source based on the `productImportSource` extension
* configuration switch: `sftp` (default) pulls from the remote SFTP server,
* `local` reads the legacy fileadmin/xmlexport/ drop directory.
* `local` reads the legacy fileadmin/xmlexport/ drop directory, `api` reads the
* product export of the MyE&P API.
*/
final class ProductImportSourceFactory implements SingletonInterface
{
public const MODE_SFTP = 'sftp';
public const MODE_LOCAL = 'local';
public const MODE_API = 'api';
public function get(): ProductImportSource
{
if ($this->getMode() === self::MODE_LOCAL) {
$mode = $this->getMode();
if ($mode === self::MODE_LOCAL) {
return GeneralUtility::makeInstance(LocalImportSource::class);
}
if ($mode === self::MODE_API) {
return GeneralUtility::makeInstance(ApiImportSource::class);
}
return GeneralUtility::makeInstance(SftpImportSource::class);
}
@@ -30,6 +36,6 @@ final class ProductImportSourceFactory implements SingletonInterface
$config = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('ep_products');
$mode = strtolower(trim((string)(is_array($config) ? ($config['productImportSource'] ?? '') : '')));
return $mode === self::MODE_LOCAL ? self::MODE_LOCAL : self::MODE_SFTP;
return in_array($mode, [self::MODE_LOCAL, self::MODE_API], true) ? $mode : self::MODE_SFTP;
}
}
@@ -0,0 +1,129 @@
<?php
namespace EP\EpProducts\Service;
/***************************************************************
*
* Copyright notice
*
* (c) 2016 Björn Fromme <[email protected]>, dreipunktnull
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use EP\EpProducts\Domain\Model\Room;
/**
* Derives the room type from the data each <preis> element carries.
*
* Replaces the former tx_epproducts_domain_model_roommapping lookup: zimmercode is
* neither unique per room nor a function of room type, so a code-keyed table cannot
* classify this data. MaxPax is the advertised occupancy and is present on every row.
*/
class RoomTypeResolver
{
/**
* Phrases in zimmertext that mark a bed shared with other customers.
*
* @var array
*/
const LABEL_PATTERNS_WITH_OTHERS = [
'bett im',
'mit ander',
];
/**
* Phrases in zimmertext that mark a deliberate single use of a larger room.
*
* @var array
*/
const LABEL_PATTERNS_SINGLE_USE = [
'einzel',
'1 person',
];
/**
* @param string $code zimmercode
* @param string $label zimmertext
* @param int $maxPax MaxPax
* @param int $minPax MinPax
* @return int one of the Room::ROOM_TYPE_* constants
*/
public function resolve(string $code, string $label, int $maxPax, int $minPax): int
{
// Not a room: "Babypreis für 0-2 Jährige". Kept in the date record for its
// price and availability, but hidden from the filter.
if ($code === DateImportService::CODE_BABYROOM) {
return Room::ROOM_TYPE_UNCLASSIFIED;
}
if ($this->matchesAny($label, static::LABEL_PATTERNS_WITH_OTHERS)) {
return Room::ROOM_TYPE_WITH_OTHERS;
}
$pax = $maxPax > 0 ? $maxPax : $minPax;
if ($pax >= 1) {
// Type numbering is chosen so that type === pax for pax 1-8.
return $pax >= 9 ? Room::ROOM_TYPE_FOR_NINE_PLUS : $pax;
}
// No usable occupancy - should never happen on current data, the caller logs it.
return Room::ROOM_TYPE_WITH_OTHERS;
}
/**
* Tripwire for an under-matching label pattern: a row classified as a single room
* whose label carries no single-use marker is most likely a shared bed phrased in
* a way LABEL_PATTERNS_WITH_OTHERS does not yet cover.
*
* @param string $code zimmercode
* @param string $label zimmertext
* @param int $maxPax MaxPax
* @return bool
*/
public function needsReview(string $code, string $label, int $maxPax): bool
{
if ($this->resolve($code, $label, $maxPax, $maxPax) !== Room::ROOM_TYPE_FOR_ONE) {
return false;
}
if ($maxPax !== 1) {
return false;
}
return !$this->matchesAny($label, static::LABEL_PATTERNS_SINGLE_USE);
}
/**
* @param string $label
* @param array $patterns
* @return bool
*/
protected function matchesAny(string $label, array $patterns): bool
{
foreach ($patterns as $pattern) {
if (mb_strpos(mb_strtolower($label), mb_strtolower($pattern)) !== false) {
return true;
}
}
return false;
}
}
@@ -31,6 +31,7 @@ use EP\EpProducts\Domain\Model\SearchResult;
use EP\EpProducts\Domain\Repository\ProductRepository;
use Symfony\Component\OptionsResolver\OptionsResolver;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class SearchResultService implements SingletonInterface
{
@@ -216,8 +217,10 @@ class SearchResultService implements SingletonInterface
$item['filterMetadata']['boardTypes'][] = $boardType;
}
if (isset($row['roomType']) && !\in_array($row['roomType'], $item['rooms'], false)) {
$item['rooms'][] = $row['roomType'];
foreach (GeneralUtility::trimExplode(',', (string) ($row['roomTypes'] ?? ''), true) as $roomType) {
if (!\in_array($roomType, $item['rooms'], false)) {
$item['rooms'][] = $roomType;
}
}
if (!\in_array($row['nights'], $item['nights'], false)) {
@@ -12,8 +12,8 @@ use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Pulls the busProNet product export (Ziel_*.xml, zustiege.xml, uebertragung.info)
* from a remote SFTP server into a local staging directory so the existing
* {@see DateImportService::import()} can keep operating on a plain local folder.
* from a remote SFTP server into a local staging directory and reads it through
* an {@see XmlProductReader}.
*
* Change detection compares the remote uebertragung.info timestamp against the
* staged copy of the last successfully imported export
@@ -42,11 +42,19 @@ final class SftpImportSource implements ProductImportSource, SingletonInterface,
private $configuration;
/**
* {@see ProductImportSource::acquire()} — alias for {@see fetchIfNewer()}.
* {@see ProductImportSource::acquire()} — {@see fetchIfNewer()}, read through
* an {@see XmlProductReader}.
*/
public function acquire(): ?string
public function acquire(): ?ProductImport
{
return $this->fetchIfNewer();
$path = $this->fetchIfNewer();
if ($path === null) {
return null;
}
$reader = new XmlProductReader($path, $this->logger);
return new ProductImport($reader, $reader->getSourceGeneratedAt(), $path);
}
/**
@@ -54,9 +62,9 @@ final class SftpImportSource implements ProductImportSource, SingletonInterface,
* change-detection baseline (only reached after a successful import), then
* refresh the display-only marker for the BE module and system-info toolbar.
*/
public function markImported(string $path): void
public function markImported(ProductImport $import): void
{
$this->commit($path);
$this->commit((string)$import->getLocation());
(new ImportTimestampService())->writeImportTimestamp(self::IMPORT_MARKER);
}
@@ -0,0 +1,369 @@
<?php
namespace EP\EpProducts\Service;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Reads a BusPro XML export directory (Ziel_*.xml, zustiege.xml) and yields one
* row per travel date × hotel, in exactly the shape of the rows served by
* GET /api/exports/products on MyE&P, so {@see DateImportService::import()}
* does not care which of the two it is fed.
*
* Nothing is filtered or rewritten here: every display rule stays in
* DateImportService. Prices are parsed from the German format, and a price the
* source does not state is null. Like the API, service labels and pickup
* cities and streets are trimmed with inner whitespace collapsed; every other
* text is passed on verbatim.
*/
final class XmlProductReader implements \IteratorAggregate
{
private const PRODUCT_PREFIX = 'Ziel';
private const PICKUPS_FILE = 'zustiege.xml';
private const MARKER_FILE = 'uebertragung.info';
private const MARKER_TS_FORMAT = 'd.m.Y H:i:s';
private const CODE_PSEUDOPRICE = 'PDGS';
private const TIMEZONE = 'Europe/Berlin';
private const LOCAL_DATETIME_FORMAT = 'Y-m-d\TH:i:s';
/**
* @var string
*/
private $path;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var \DateTimeZone
*/
private $timezone;
/**
* Pickup times are clock readings, not instants. They are handled in UTC,
* which has no daylight saving gaps, so a time BusPro plans inside one
* (02:45 on the night clocks go forward) is kept as stated.
*
* @var \DateTimeZone
*/
private $wallClock;
/**
* @var array|null pickup master data by BusPro id
*/
private $pickups;
public function __construct(string $path, ?LoggerInterface $logger = null)
{
$this->path = rtrim($path, '/');
$this->logger = $logger ?? new NullLogger();
$this->timezone = new \DateTimeZone(self::TIMEZONE);
$this->wallClock = new \DateTimeZone('UTC');
}
public function getPath(): string
{
return $this->path;
}
/**
* The export's own timestamp from uebertragung.info, or null if unreadable.
*/
public function getSourceGeneratedAt(): ?\DateTimeImmutable
{
$file = $this->path . '/' . self::MARKER_FILE;
if (!is_file($file)) {
return null;
}
$line = trim((string) strtok((string) file_get_contents($file), "\r\n"));
$date = \DateTimeImmutable::createFromFormat(self::MARKER_TS_FORMAT, $line, $this->timezone);
return $date ?: null;
}
/**
* @return \Generator<array>
*/
public function getIterator(): \Generator
{
if ($this->pickups === null) {
$this->pickups = $this->readPickups();
}
$folder = opendir($this->path);
if ($folder === false) {
$this->logger->error('product xml directory not readable', ['path' => $this->path]);
return;
}
try {
while (($fileName = readdir($folder)) !== false) {
if (strpos($fileName, self::PRODUCT_PREFIX) === 0) {
yield from $this->readProductFile($this->path . '/' . $fileName);
}
}
} finally {
closedir($folder);
}
}
private function readProductFile(string $file): \Generator
{
libxml_use_internal_errors(true);
$xmlData = simplexml_load_string((string) file_get_contents($file));
if ($xmlData === false) {
libxml_clear_errors();
$this->logger->error('product xml invalid', ['file' => $file]);
return;
}
$xmlProduct = $xmlData->reise[0];
if ($xmlProduct === null) {
return;
}
$product = [
'code' => (string) $xmlProduct['code'],
'busProId' => (int) $xmlProduct['idbuspro'],
];
foreach ($xmlProduct->termin as $xmlDate) {
$from = $this->parseDate((string) $xmlDate['termin']);
$to = $this->parseDate((string) $xmlDate['bis']);
if ($from === null || $to === null) {
$this->logger->warning('travel date skipped, dates unparseable', [
'code' => (string) $xmlDate['code'],
'termin' => (string) $xmlDate['termin'],
'bis' => (string) $xmlDate['bis'],
]);
continue;
}
$date = [
'code' => (string) $xmlDate['code'],
'busProId' => (int) $xmlDate['idbuspro'],
'from' => $from->format('Y-m-d'),
'to' => $to->format('Y-m-d'),
'type' => (string) $xmlDate['reiseart'],
];
// Everything below is per travel date and shared by its hotels.
$selectionGroups = $this->readSelectionGroups($xmlDate);
$transportServices = $this->readServices($xmlDate, 'lei_befoerderung');
$dateServices = $this->readServices($xmlDate, 'lei_sonstiges');
$pickups = $this->readDatePickups($xmlDate, $from);
$guide = $this->readGuide($xmlDate);
foreach ($xmlDate->hotel as $xmlHotel) {
[$pseudoPrice, $rooms] = $this->readRooms($xmlHotel);
yield [
'product' => $product,
'date' => $date,
'hotel' => [
'code' => (string) $xmlHotel['code'],
'busProId' => (int) $xmlHotel['idbuspro'],
],
'pseudoPrice' => $pseudoPrice,
'selectionGroups' => $selectionGroups,
'transportServices' => $transportServices,
'dateServices' => $dateServices,
'hotelServices' => $this->readServices($xmlHotel, 'lei_sonstiges'),
'rooms' => $rooms,
'pickups' => $pickups,
'guide' => $guide,
];
}
}
}
private function readSelectionGroups(\SimpleXMLElement $xmlDate): array
{
$groups = [];
foreach ($xmlDate->selektiongruppe as $xmlGroup) {
$selections = [];
foreach ($xmlGroup->selektion as $xmlSelection) {
$selections[] = [
'busProId' => (int) $xmlSelection['idbuspro'],
'label' => (string) $xmlSelection['bezeichnung'],
];
}
$groups[] = [
'busProId' => (int) $xmlGroup['idbuspro'],
'label' => (string) $xmlGroup['bezeichnung'],
'selections' => $selections,
];
}
return $groups;
}
private function readServices(\SimpleXMLElement $xmlParent, string $list): array
{
$services = [];
foreach ($xmlParent->xpath($list . '/leistung') as $xmlService) {
$direction = trim((string) $xmlService->richtung);
$services[] = [
'busProId' => (int) $xmlService['idbuspro'],
'subType' => (string) $xmlService['unterart'],
'label' => $this->normalizeWhitespace((string) $xmlService->text),
'price' => $this->parsePrice((string) $xmlService->preis),
'status' => (string) $xmlService->status,
'direction' => $direction === '' ? null : $direction,
];
}
return $services;
}
/**
* @return array{0: ?float, 1: array}
*/
private function readRooms(\SimpleXMLElement $xmlHotel): array
{
$pseudoPrice = null;
$rooms = [];
foreach ($xmlHotel->xpath('zimmer/preis') as $xmlRoom) {
$code = trim((string) $xmlRoom['zimmercode']);
if ($code === self::CODE_PSEUDOPRICE) {
$pseudoPrice = $this->parsePrice((string) $xmlRoom['preis']);
continue;
}
$rooms[] = [
'busProId' => (int) $xmlRoom['idbuspro_zimmer'],
'code' => $code,
'label' => (string) $xmlRoom['zimmertext'],
'category' => (string) $xmlRoom['kat'],
'minPax' => $this->parseInt((string) $xmlRoom['MinPax']),
'maxPax' => $this->parseInt((string) $xmlRoom['MaxPax']),
'nights' => $this->parseInt((string) $xmlRoom['naechte']),
'price' => $this->parsePrice((string) $xmlRoom['preis']),
'available' => $this->parseInt((string) $xmlRoom['verfuegbar']),
'status' => (string) $xmlRoom['status'],
'boardCode' => (string) $xmlRoom['vpcode'],
'boardBusProId' => $this->parseInt((string) $xmlRoom['idbuspro_vp']),
];
}
return [$pseudoPrice, $rooms];
}
/**
* A bare HH:mm takes the travel date's start, and is rolled onto the next
* day when it would otherwise fall before the latest full date-time listed
* before it: a coach does not board backwards. The result is the local
* date and time as BusPro states it, without an offset.
*/
private function readDatePickups(\SimpleXMLElement $xmlDate, \DateTimeImmutable $from): array
{
$pickups = [];
$latest = null;
foreach ($xmlDate->xpath('zustiege/zustieg') as $xmlPickup) {
$busProId = (int) $xmlPickup['idbuspro'];
$time = trim((string) $xmlPickup['zeit']);
$datetime = null;
if ($time !== '' && strpos($time, ' ') !== false) {
$datetime = \DateTimeImmutable::createFromFormat('!d.m.Y H:i:s', $time, $this->wallClock) ?: null;
if ($datetime !== null && ($latest === null || $datetime > $latest)) {
$latest = $datetime;
}
} elseif ($time !== '') {
$datetime = \DateTimeImmutable::createFromFormat('!Y-m-d H:i', $from->format('Y-m-d') . ' ' . $time, $this->wallClock) ?: null;
if ($datetime !== null && $latest !== null && $datetime < $latest) {
$datetime = $datetime->modify('+1 day');
}
}
$masterData = $this->pickups[$busProId] ?? null;
$pickups[] = [
'busProId' => $busProId,
'code' => $masterData['code'] ?? null,
'city' => $masterData['city'] ?? null,
'street' => $masterData['street'] ?? null,
'price' => $this->parsePrice((string) $xmlPickup['preis']),
'datetime' => $datetime !== null ? $datetime->format(self::LOCAL_DATETIME_FORMAT) : null,
];
}
return $pickups;
}
private function readGuide(\SimpleXMLElement $xmlDate): ?array
{
foreach ($xmlDate->xpath('lei_befoerderung/leistung[@unterart="BUS"]') as $xmlService) {
if ((string) $xmlService->richtung === 'RUECK') {
continue;
}
if (!isset($xmlService->zustiegsplanung->reiseleiter)) {
continue;
}
return [
'name' => (string) $xmlService->zustiegsplanung->reiseleiter->name,
'phone' => (string) $xmlService->zustiegsplanung->reiseleiter->telefon,
];
}
return null;
}
/**
* @return array<int, array{code: string, city: string, street: string}>
*/
private function readPickups(): array
{
$file = $this->path . '/' . self::PICKUPS_FILE;
libxml_use_internal_errors(true);
if (!is_file($file) || !$xmlData = simplexml_load_string((string) file_get_contents($file))) {
libxml_clear_errors();
$this->logger->warning('pickup xml missing or invalid', ['file' => $file]);
return [];
}
$pickups = [];
foreach ($xmlData->zustieg as $xmlPickup) {
$pickups[(int) $xmlPickup['idbuspro']] = [
'code' => (string) $xmlPickup['code'],
'city' => $this->normalizeWhitespace((string) $xmlPickup->ort),
'street' => $this->normalizeWhitespace((string) $xmlPickup->strasse),
];
}
return $pickups;
}
private function normalizeWhitespace(string $value): string
{
return trim((string) preg_replace('/\s+/u', ' ', $value));
}
private function parseDate(string $value): ?\DateTimeImmutable
{
$date = \DateTimeImmutable::createFromFormat('!d.m.Y', trim($value), $this->timezone);
return $date ?: null;
}
/**
* German format with an optional thousands separator: "1.234,50" is 1234.5.
*/
private function parsePrice(string $value): ?float
{
$value = str_replace(['.', ','], ['', '.'], trim($value));
return is_numeric($value) ? (float) $value : null;
}
private function parseInt(string $value): ?int
{
$value = trim($value);
return is_numeric($value) ? (int) $value : null;
}
}
@@ -44,16 +44,16 @@ class ImportDatesTask extends AbstractTask
$cacheService = GeneralUtility::makeInstance(CacheService::class);
// Acquire the export only when it is newer than the one we last imported
// (SFTP mode: download to a staging dir; local mode: fileadmin/xmlexport).
// An acquisition failure (SFTP connect/auth/transfer) is left to propagate
// so the scheduler marks the task failed.
$path = $importSource->acquire();
// (SFTP mode: download to a staging dir; local mode: fileadmin/xmlexport;
// API mode: walk the MyE&P export pages). An acquisition failure is left
// to propagate so the scheduler marks the task failed.
$import = $importSource->acquire();
if ($path !== null) {
$importService->import($path);
if ($import !== null) {
$importService->import($import->getRows());
// Advance the "last imported" bookkeeping only after a successful
// import, so a crashed import retries on the next run.
$importSource->markImported($path);
$importSource->markImported($import);
}
$settings = $this->getSettings();
@@ -0,0 +1,83 @@
<?php
namespace EP\EpProducts\Utility;
/**
* Maps hotel fields to icon ids and labels. Shared by the MyEP API and the frontend
* detail pages, so both show the same selection. Icon ids correspond to the
* "icon-{id}" symbols in ep_theme's icons_sprite.svg (copied from MyEP).
*/
class HotelIconUtility
{
/**
* @param array $hotel Hotel values keyed by database column name
* @return array<int, array{icon: string, label: string}>
*/
public static function getIcons(array $hotel): array
{
$icons = [];
if (($hotel['beds_count'] ?? 0) > 0) {
$icons[] = [
'icon' => 'bed',
'label' => sprintf('%d Betten', $hotel['beds_count']),
];
}
if (($hotel['parking_count'] ?? 0) > 0) {
$icons[] = [
'icon' => 'parking',
'label' => sprintf('%d Parkplätze', $hotel['parking_count']),
];
}
if ($hotel['altitude'] ?? null) {
$icons[] = [
'icon' => 'mountain',
'label' => $hotel['altitude'],
];
}
if ($hotel['distance_bus'] ?? null) {
$icons[] = [
'icon' => 'bus',
'label' => $hotel['distance_bus'],
];
}
if ($hotel['distance_lift'] ?? null) {
$icons[] = [
'icon' => 'lift',
'label' => $hotel['distance_lift'],
];
}
if ($hotel['shower'] ?? null) {
$icons[] = [
'icon' => 'shower',
'label' => $hotel['shower'],
];
}
if ($hotel['partyroom'] ?? false) {
$icons[] = [
'icon' => 'party',
'label' => 'Partyzimmer',
];
}
if ($hotel['gamesroom'] ?? false) {
$icons[] = [
'icon' => 'dice',
'label' => 'Spielezimmer',
];
}
if ($hotel['sauna'] ?? false) {
$icons[] = [
'icon' => 'sauna',
'label' => 'Sauna',
];
}
if ($hotel['wifi'] ?? false) {
$icons[] = [
'icon' => 'wifi',
'label' => 'WiFi',
];
}
return $icons;
}
}
@@ -20,6 +20,15 @@ return [
'typo3/cms-frontend/site',
],
],
'ep/content-page-type-guard' => [
'target' => \EP\EpProducts\Middleware\ContentPageTypeGuardMiddleware::class,
'after' => [
'typo3/cms-frontend/page-resolver',
],
'before' => [
'typo3/cms-frontend/page-argument-validator',
],
],
'ep/staging-environment' => [
'target' => \EP\EpProducts\Middleware\StagingEnvironmentMiddleware::class,
'after' => [
@@ -403,6 +403,7 @@ return [
'label' => 'Produkte',
'config' => [
'type' => 'select',
'default' => 0,
'renderType' => 'selectMultipleSideBySide',
'foreign_table' => 'tx_epproducts_domain_model_product',
'size' => 10,
@@ -24,8 +24,8 @@ return [
],
'types' => [
'1' => ['showitem' => 'hidden, bus_pro_id, hotel_bus_pro_id, code, daytrip, date_start, date_end, nights, board,
board_code, board_bus_pro_id, bus_included, bus_available, skipass_included, services_included,
services_general, courses_included, guide, pickups, discount, min_price, pseudo_price, available, min_pax,
board_code, board_bus_pro_id, bus_included, bus_available, skipass_included, group_travel,
services_included, services_general, courses_included, guide, pickups, discount, min_price, pseudo_price, available, min_pax,
new'
],
],
@@ -322,6 +322,14 @@ return [
'default' => 0
]
],
'group_travel' => [
'exclude' => false,
'label' => 'Gruppenreise',
'config' => [
'type' => 'check',
'default' => 0
]
],
'bus_price' => [
'exclude' => false,
'label' => 'Bus Preis',
@@ -1,144 +0,0 @@
<?php
return [
'ctrl' => [
'title' => 'LLL:EXT:ep_products/Resources/Private/Language/locallang.xlf:tx_epproducts_domain_model_roommapping',
'label' => 'code',
'prependAtCopy' => '[COPY %s]',
'default_sortby' => 'ORDER BY code',
'tstamp' => 'tstamp',
'crdate' => 'crdate',
'cruser_id' => 'cruser_id',
'dividers2tabs' => true,
'versioningWS' => false,
'languageField' => 'sys_language_uid',
'transOrigPointerField' => 'l10n_parent',
'transOrigDiffSourceField' => 'l10n_diffsource',
'delete' => 'deleted',
'enablecolumns' => [
'disabled' => 'hidden',
'starttime' => 'starttime',
'endtime' => 'endtime',
],
'searchFields' => 'code',
'iconfile' => 'EXT:ep_theme/Resources/Public/images/icon_ce.svg',
],
'types' => [
'1' => ['showitem' => 'code, type'],
],
'palettes' => [
'1' => ['showitem' => ''],
],
'columns' => [
'sys_language_uid' => [
'exclude' => 0,
'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.language',
'config' => [
'type' => 'select',
'default' => 0,
'renderType' => 'selectSingle',
'foreign_table' => 'sys_language',
'foreign_table_where' => 'ORDER BY sys_language.title',
'items' => [
['LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.allLanguages', -1],
['LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.default_value', 0]
],
],
],
'l10n_parent' => [
'displayCond' => 'FIELD:sys_language_uid:>:0',
'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.l18n_parent',
'config' => [
'type' => 'select',
'default' => 0,
'renderType' => 'selectSingle',
'items' => [
['', 0],
],
'foreign_table' => 'tx_epproducts_domain_model_roommapping',
'foreign_table_where' => 'AND tx_epproducts_domain_model_roommapping.pid=###CURRENT_PID### AND tx_epproducts_domain_model_roommapping.sys_language_uid IN (-1,0)',
],
],
'l10n_diffsource' => [
'config' => [
'type' => 'passthrough',
],
],
't3ver_label' => [
'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.versionLabel',
'config' => [
'type' => 'input',
'size' => 30,
'max' => 255,
]
],
'hidden' => [
'exclude' => 0,
'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.hidden',
'config' => [
'type' => 'check',
],
],
'starttime' => [
'exclude' => 0,
'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.starttime',
'config' => [
'type' => 'input',
'size' => 13,
'eval' => 'datetime',
'checkbox' => 0,
'default' => 0,
'behaviour' => [
'allowLanguageSynchronization' => true,
],
'renderType' => 'inputDateTime',
],
],
'endtime' => [
'exclude' => 0,
'label' => 'LLL:EXT:core/Resources/Private/Language/locallang_general.xlf:LGL.endtime',
'config' => [
'type' => 'input',
'size' => 13,
'eval' => 'datetime',
'checkbox' => 0,
'default' => 0,
'behaviour' => [
'allowLanguageSynchronization' => true,
],
'renderType' => 'inputDateTime',
],
],
'code' => [
'exclude' => 0,
'label' => 'Code',
'config' => [
'type' => 'input',
'size' => 30,
'eval' => 'trim'
],
],
'type' => [
'exclude' => 0,
'label' => 'Typ',
'config' => [
'type' => 'select',
'renderType' => 'selectSingle',
'items' => [
['Einzelzimmer', \EP\EpProducts\Domain\Model\Room::ROOM_TYPE_FOR_ONE],
['Doppelzimmer und Apartm. f. 2 Pers.', \EP\EpProducts\Domain\Model\Room::ROOM_TYPE_FOR_TWO],
['Zimmer und Apartm. f. 3 Pers.', \EP\EpProducts\Domain\Model\Room::ROOM_TYPE_FOR_THREE],
['Zimmer und Apartm. f. 4 Pers.', \EP\EpProducts\Domain\Model\Room::ROOM_TYPE_FOR_FOUR],
['Zimmer und Apartm. mit Anderen', \EP\EpProducts\Domain\Model\Room::ROOM_TYPE_WITH_OTHERS],
['weitere Zimmer und Apartments', \EP\EpProducts\Domain\Model\Room::ROOM_TYPE_OTHER],
],
'size' => 1,
'minItems' => 1,
'maxItems' => 1
],
],
],
];
@@ -39,9 +39,6 @@
<trans-unit id="tx_epproducts_domain_model_teammember">
<source>Mitarbeiter/Teamer</source>
</trans-unit>
<trans-unit id="tx_epproducts_domain_model_roommapping">
<source>Zimmermapping</source>
</trans-unit>
<trans-unit id="tx_epproducts_domain_model_journey">
<source>Anreise</source>
</trans-unit>
@@ -40,7 +40,19 @@ bpnConnectApiTimeout = 5
# cat=MyEpAPI; type=int; label=Bpn Connect API max total request duration in seconds (0 = unlimited)
bpnConnectApiMaxDuration = 15
# cat=SftpImport; type=options[Remote SFTP server=sftp,Local directory (fileadmin/xmlexport)=local]; label=Product/date import source
# cat=EpTeamAPI; type=string; label=MyE&P Team base URL (https, e.g. https://team.ep-reisen.de) - receives application form submissions
epTeamApiBaseUrl =
# cat=EpTeamAPI; type=string; label=MyE&P Team application form API key (sent as X-Api-Key)
epTeamApiKey =
# cat=EpTeamAPI; type=int; label=MyE&P Team API inactivity timeout in seconds (0 = PHP default_socket_timeout)
epTeamApiTimeout = 5
# cat=EpTeamAPI; type=int; label=MyE&P Team API max total request duration in seconds (0 = unlimited)
epTeamApiMaxDuration = 15
# cat=SftpImport; type=options[Remote SFTP server=sftp,Local directory (fileadmin/xmlexport)=local,MyE&P API=api]; label=Product/date import source
productImportSource = sftp
# cat=SftpImport; type=string; label=SFTP host for product/date import
@@ -63,3 +75,21 @@ productImportSftpHostKey =
# cat=SftpImport; type=int+; label=SFTP connection timeout in seconds
productImportSftpTimeout = 15
# cat=ContentFeed; type=string; label=API key for the CMS backchannel endpoints used by MyE&P (/api/hotel, /api/product, /api/content/*); sent as X-Api-Key or ?key=. Empty denies every request.
cmsApiKey =
# cat=ContentFeed; type=boolean; label=Serve the chatbot content feed (off: all feed endpoints answer 503)
contentFeedEnabled = 1
# cat=ContentFeed; type=string; label=Site identifiers included in the chatbot content feed (comma-separated)
contentFeedSites = ep-reisen,ser,ski-boarderweek,ski-wochenenden,snowzone
# cat=ContentFeed; type=string; label=Language ids included in the chatbot content feed (comma-separated; the English pages are untranslated placeholders today)
contentFeedLanguages = 0
# cat=ContentFeed; type=string; label=Page uids whose subtrees stay out of the chatbot content feed (comma-separated; 634 = group booking links)
contentFeedExcludedPages = 634
# cat=ContentFeed; type=string; label=News detail page per site for the chatbot content feed (identifier:pageUid, comma-separated)
contentFeedNewsDetailPages = ep-reisen:1392
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more