Passed
Push — master ( 0fabdc...37b7a8 )
by
unknown
17:17
created

RecordsXmlSitemapDataProvider::defineUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 15
nc 2
nop 1
dl 0
loc 24
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
namespace TYPO3\CMS\Seo\XmlSitemap;
19
20
use Psr\Http\Message\ServerRequestInterface;
21
use TYPO3\CMS\Core\Context\Context;
22
use TYPO3\CMS\Core\Context\WorkspaceAspect;
23
use TYPO3\CMS\Core\Database\ConnectionPool;
24
use TYPO3\CMS\Core\Database\Query\QueryHelper;
25
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
27
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
28
use TYPO3\CMS\Seo\XmlSitemap\Exception\MissingConfigurationException;
29
30
/**
31
 * XmlSiteDataProvider will provide information for the XML sitemap for a specific database table
32
 * @internal this class is not part of TYPO3's Core API.
33
 */
34
class RecordsXmlSitemapDataProvider extends AbstractXmlSitemapDataProvider
35
{
36
    /**
37
     * @param ServerRequestInterface $request
38
     * @param string $key
39
     * @param array $config
40
     * @param ContentObjectRenderer|null $cObj
41
     * @throws MissingConfigurationException
42
     */
43
    public function __construct(ServerRequestInterface $request, string $key, array $config = [], ContentObjectRenderer $cObj = null)
44
    {
45
        parent::__construct($request, $key, $config, $cObj);
46
47
        $this->generateItems();
48
    }
49
50
    /**
51
     * @throws MissingConfigurationException
52
     */
53
    public function generateItems(): void
54
    {
55
        $table = $this->config['table'];
56
57
        if (empty($table)) {
58
            throw new MissingConfigurationException(
59
                'No configuration found for sitemap ' . $this->getKey(),
60
                1535576053
61
            );
62
        }
63
64
        $pids = !empty($this->config['pid']) ? GeneralUtility::intExplode(',', $this->config['pid']) : [];
65
        $lastModifiedField = $this->config['lastModifiedField'] ?? 'tstamp';
66
        $sortField = $this->config['sortField'] ?? 'sorting';
67
68
        $changeFreqField = $this->config['changeFreqField'] ?? '';
69
        $priorityField = $this->config['priorityField'] ?? '';
70
71
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
72
            ->getQueryBuilderForTable($table);
73
74
        $constraints = [];
75
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['languageField'])) {
76
            $constraints[] = $queryBuilder->expr()->in(
77
                $GLOBALS['TCA'][$table]['ctrl']['languageField'],
78
                [
79
                    -1, // All languages
80
                    $this->getLanguageId()  // Current language
81
                ]
82
            );
83
        }
84
85
        if (!empty($pids)) {
86
            $recursiveLevel = isset($this->config['recursive']) ? (int)$this->config['recursive'] : 0;
87
            if ($recursiveLevel) {
88
                $newList = [];
89
                foreach ($pids as $pid) {
90
                    $list = $this->cObj->getTreeList($pid, $recursiveLevel);
91
                    if ($list) {
92
                        $newList = array_merge($newList, explode(',', $list));
93
                    }
94
                }
95
                $pids = array_merge($pids, $newList);
96
            }
97
98
            $constraints[] = $queryBuilder->expr()->in('pid', $pids);
99
        }
100
101
        if (!empty($this->config['additionalWhere'])) {
102
            $constraints[] = QueryHelper::stripLogicalOperatorPrefix($this->config['additionalWhere']);
103
        }
104
105
        $queryBuilder->getRestrictions()->add(
106
            GeneralUtility::makeInstance(WorkspaceRestriction::class, $this->getCurrentWorkspaceAspect()->getId())
107
        );
108
109
        $queryBuilder->select('*')
110
            ->from($table);
111
112
        if (!empty($constraints)) {
113
            $queryBuilder->where(
114
                ...$constraints
115
            );
116
        }
117
118
        $rows = $queryBuilder->orderBy($sortField)
119
            ->execute()
120
            ->fetchAll();
121
122
        foreach ($rows as $row) {
123
            $item = [
124
                'data' => $row,
125
                'lastMod' => (int)$row[$lastModifiedField]
126
            ];
127
            if (!empty($changeFreqField)) {
128
                $item['changefreq'] = $row[$changeFreqField];
129
            }
130
            $item['priority'] = !empty($priorityField) ? $row[$priorityField] : 0.5;
131
            $this->items[] = $item;
132
        }
133
    }
134
135
    /**
136
     * @param array $data
137
     * @return array
138
     */
139
    protected function defineUrl(array $data): array
140
    {
141
        $pageId = $this->config['url']['pageId'] ?? $GLOBALS['TSFE']->id;
142
        $additionalParams = [];
143
144
        $additionalParams = $this->getUrlFieldParameterMap($additionalParams, $data['data']);
145
        $additionalParams = $this->getUrlAdditionalParams($additionalParams);
146
147
        $additionalParamsString = http_build_query(
148
            $additionalParams,
149
            '',
150
            '&',
151
            PHP_QUERY_RFC3986
152
        );
153
154
        $typoLinkConfig = [
155
            'parameter' => $pageId,
156
            'additionalParams' => $additionalParamsString ? '&' . $additionalParamsString : '',
157
            'forceAbsoluteUrl' => 1,
158
        ];
159
160
        $data['loc'] = $this->cObj->typoLink_URL($typoLinkConfig);
161
162
        return $data;
163
    }
164
165
    /**
166
     * @param array $additionalParams
167
     * @param array $data
168
     * @return array
169
     */
170
    protected function getUrlFieldParameterMap(array $additionalParams, array $data): array
171
    {
172
        if (!empty($this->config['url']['fieldToParameterMap']) &&
173
            \is_array($this->config['url']['fieldToParameterMap'])) {
174
            foreach ($this->config['url']['fieldToParameterMap'] as $field => $urlPart) {
175
                $additionalParams[$urlPart] = $data[$field];
176
            }
177
        }
178
179
        return $additionalParams;
180
    }
181
182
    /**
183
     * @param array $additionalParams
184
     * @return array
185
     */
186
    protected function getUrlAdditionalParams(array $additionalParams): array
187
    {
188
        if (!empty($this->config['url']['additionalGetParameters']) &&
189
            is_array($this->config['url']['additionalGetParameters'])) {
190
            foreach ($this->config['url']['additionalGetParameters'] as $extension => $extensionConfig) {
191
                foreach ($extensionConfig as $key => $value) {
192
                    $additionalParams[$extension . '[' . $key . ']'] = $value;
193
                }
194
            }
195
        }
196
197
        return $additionalParams;
198
    }
199
200
    /**
201
     * @return int
202
     * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException
203
     */
204
    protected function getLanguageId(): int
205
    {
206
        $context = GeneralUtility::makeInstance(Context::class);
207
        return (int)$context->getPropertyFromAspect('language', 'id');
208
    }
209
210
    /**
211
     * @return WorkspaceAspect
212
     */
213
    protected function getCurrentWorkspaceAspect(): WorkspaceAspect
214
    {
215
        return GeneralUtility::makeInstance(Context::class)->getAspect('workspace');
216
    }
217
}
218