Completed
Push — master ( 7cb17c...23be3f )
by Tim
12:20
created

RealUrl::aliasAlreadyExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * RealUrl.
5
 */
6
declare(strict_types=1);
7
8
namespace HDNET\Calendarize\Service\Url;
9
10
use DmitryDulepov\Realurl\Configuration\ConfigurationReader;
11
use DmitryDulepov\Realurl\Utility;
12
use HDNET\Calendarize\Service\IndexerService;
13
use HDNET\Calendarize\Utility\HelperUtility;
14
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
15
use TYPO3\CMS\Core\Utility\GeneralUtility;
16
use TYPO3\CMS\Core\Utility\VersionNumberUtility;
17
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
18
19
/**
20
 * RealUrl.
21
 */
22
class RealUrl extends AbstractUrl
23
{
24
    /**
25
     * Convert the given information.
26
     *
27
     * @param $param1
28
     * @param $param2
29
     *
30
     * @return string
31
     */
32
    public function convert($param1, $param2)
33
    {
34
        return $this->main($param1, $param2);
35
    }
36
37
    /**
38
     * Build the realurl alias.
39
     *
40
     * @param $params
41
     * @param $ref
42
     *
43
     * @return string
44
     */
45
    public function main($params, $ref)
0 ignored issues
show
Unused Code introduced by
The parameter $ref is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
46
    {
47
        if ($params['decodeAlias']) {
48
            return $this->alias2id($params['value']);
49
        }
50
        $this->cleanupOldLinks();
51
52
        return $this->id2alias($params['value']);
53
    }
54
55
    /**
56
     * Cleanup old URL segments.
57
     */
58
    protected function cleanupOldLinks()
59
    {
60
        $removeIds = [];
61
        $databaseConnection = HelperUtility::getDatabaseConnection();
62
        $selectInvalidItems = 'SELECT tx_realurl_uniqalias.uid 
63
FROM tx_realurl_uniqalias LEFT JOIN tx_calendarize_domain_model_index ON tx_realurl_uniqalias.value_id = tx_calendarize_domain_model_index.uid 
64
WHERE tx_calendarize_domain_model_index.uid IS NULL AND tx_realurl_uniqalias.tablename=\'tx_calendarize_domain_model_index\'';
65
        $res = $databaseConnection->admin_query($selectInvalidItems);
66
        while ($row = $databaseConnection->sql_fetch_assoc($res)) {
67
            $removeIds[] = (int) $row['uid'];
68
        }
69
        if (empty($removeIds)) {
70
            return;
71
        }
72
        $databaseConnection->exec_DELETEquery('tx_realurl_uniqalias', 'uid IN (' . \implode(',', $removeIds) . ')');
73
    }
74
75
    /**
76
     * Handle the alias to index ID convert.
77
     *
78
     * @param $value
79
     */
80
    protected function alias2id($value)
81
    {
82
        $databaseConnection = HelperUtility::getDatabaseConnection();
83
        $row = $databaseConnection->exec_SELECTgetSingleRow(
84
            'value_id',
85
            'tx_realurl_uniqalias',
86
            'tablename=' . $databaseConnection->fullQuoteStr(
87
                IndexerService::TABLE_NAME,
88
                IndexerService::TABLE_NAME
89
            ) . ' AND value_alias=' . $databaseConnection->fullQuoteStr(
90
                $value,
91
                IndexerService::TABLE_NAME
92
            )
93
        );
94
        if (isset($row['value_id'])) {
95
            return (int) $row['value_id'];
96
        }
97
98
        $matches = [];
99
        if (\preg_match('/^idx-([0-9]+)$/', $value, $matches)) {
100
            return $matches[1];
101
        }
102
    }
103
104
    /**
105
     * Handle the index ID to alias convert.
106
     *
107
     * @param $value
108
     *
109
     * @return string
110
     */
111
    protected function id2alias($value)
112
    {
113
        $databaseConnection = HelperUtility::getDatabaseConnection();
114
        $row = $databaseConnection->exec_SELECTgetSingleRow(
115
            'value_alias',
116
            'tx_realurl_uniqalias',
117
            'tablename=' . $databaseConnection->fullQuoteStr(
118
                IndexerService::TABLE_NAME,
119
                IndexerService::TABLE_NAME
120
            ) . ' AND value_id=' . (int) $value
121
        );
122
        if (isset($row['value_alias'])) {
123
            return $row['value_alias'];
124
        }
125
126
        $alias = $this->getIndexBase((int) $value);
127
        $alias = $this->cleanUrl($alias);
128
129
        $databaseConnection = HelperUtility::getDatabaseConnection();
130
        $entry = [
131
            'tablename' => IndexerService::TABLE_NAME,
132
            'field_alias' => 'title',
133
            'field_id' => 'uid',
134
            'value_alias' => $alias,
135
            'value_id' => $value,
136
        ];
137
        if ($this->isOldRealUrlVersion()) {
138
            $entry['tstamp'] = (new \DateTime())->getTimestamp();
139
        }
140
141
        $aliasBase = $alias;
142
        for ($i = 0; ; $i++) {
143
            $alias = $i > 0 ? $aliasBase . '-' . $i : $aliasBase;
144
            if (!$this->aliasAlreadyExists($alias)) {
145
                $entry['value_alias'] = $alias;
146
                break;
147
            }
148
        }
149
        $databaseConnection->exec_INSERTquery('tx_realurl_uniqalias', $entry);
150
151
        return $alias;
152
    }
153
154
    /**
155
     * Check if alias already exists
156
     *
157
     * @param string $alias
158
     * @return boolean
159
     */
160
    protected function aliasAlreadyExists($alias)
161
    {
162
        $databaseConnection = HelperUtility::getDatabaseConnection();
163
        $count = $databaseConnection->exec_SELECTcountRows('*', 'tx_realurl_uniqalias',
164
            'value_alias=' . $databaseConnection->fullQuoteStr($alias, 'tx_realurl_uniqalias'));
165
        return (bool)$count;
166
    }
167
168
    /**
169
     * Generate the realurl part.
170
     *
171
     * @param string $alias
172
     *
173
     * @return string
174
     */
175
    protected function cleanUrl($alias)
176
    {
177
        if ($this->isOldRealUrlVersion()) {
178
            /** @var \tx_realurl_advanced $realUrl */
179
            $realUrl = GeneralUtility::makeInstance('tx_realurl_advanced');
180
            $configuration = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT']['pagePath'];
181
            if (\is_array($configuration)) {
182
                ObjectAccess::setProperty($realUrl, 'conf', $configuration, true);
183
            }
184
            $processedTitle = $realUrl->encodeTitle($alias);
185
        } else {
186
            $configuration = GeneralUtility::makeInstance(ConfigurationReader::class, ConfigurationReader::MODE_ENCODE);
187
            // Init the internal utility by ObjectAccess because the property is
188
            // set by a protected method only. :( Perhaps this could be part of the construct (in realurl)
189
            $utility = GeneralUtility::makeInstance(Utility::class, $configuration);
190
            $processedTitle = $utility->convertToSafeString($alias);
191
        }
192
193
        return $processedTitle;
194
    }
195
196
    /**
197
     * Check if this is a old version of realurl < 2.0.0.
198
     *
199
     * @return bool
200
     */
201
    protected function isOldRealUrlVersion()
202
    {
203
        $extVersion = ExtensionManagementUtility::getExtensionVersion('realurl');
204
205
        return VersionNumberUtility::convertVersionNumberToInteger($extVersion) < 2000000;
206
    }
207
}
208