Completed
Push — master ( 8be416...b9cbba )
by Fabien
03:29
created
Classes/Persistence/Storage/VidiDbBackend.php 1 patch
Indentation   +1207 added lines, -1207 removed lines patch added patch discarded remove patch
@@ -38,1211 +38,1211 @@
 block discarded – undo
38 38
 class VidiDbBackend
39 39
 {
40 40
 
41
-    const OPERATOR_EQUAL_TO_NULL = 'operatorEqualToNull';
42
-    const OPERATOR_NOT_EQUAL_TO_NULL = 'operatorNotEqualToNull';
43
-
44
-    /**
45
-     * The TYPO3 database object
46
-     *
47
-     * @var \TYPO3\CMS\Core\Database\DatabaseConnection
48
-     */
49
-    protected $databaseHandle;
50
-
51
-    /**
52
-     * The TYPO3 page repository. Used for language and workspace overlay
53
-     *
54
-     * @var PageRepository
55
-     */
56
-    protected $pageRepository;
57
-
58
-    /**
59
-     * A first-level TypoScript configuration cache
60
-     *
61
-     * @var array
62
-     */
63
-    protected $pageTSConfigCache = array();
64
-
65
-    /**
66
-     * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
67
-     * @inject
68
-     */
69
-    protected $configurationManager;
70
-
71
-    /**
72
-     * @var \TYPO3\CMS\Extbase\Service\CacheService
73
-     * @inject
74
-     */
75
-    protected $cacheService;
76
-
77
-    /**
78
-     * @var \TYPO3\CMS\Core\Cache\CacheManager
79
-     * @inject
80
-     */
81
-    protected $cacheManager;
82
-
83
-    /**
84
-     * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
85
-     */
86
-    protected $tableColumnCache;
87
-
88
-    /**
89
-     * @var \TYPO3\CMS\Extbase\Service\EnvironmentService
90
-     * @inject
91
-     */
92
-    protected $environmentService;
93
-
94
-    /**
95
-     * @var \Fab\Vidi\Persistence\Query
96
-     */
97
-    protected $query;
98
-
99
-    /**
100
-     * Store some info related to table name and its aliases.
101
-     *
102
-     * @var array
103
-     */
104
-    protected $tableNameAliases = array(
105
-        'aliases' => array(),
106
-        'aliasIncrement' => array(),
107
-    );
108
-
109
-    /**
110
-     * Use to store the current foreign table name alias.
111
-     *
112
-     * @var string
113
-     */
114
-    protected $currentChildTableNameAlias = '';
115
-
116
-    /**
117
-     * The default object type being returned.
118
-     *
119
-     * @var string
120
-     */
121
-    protected $objectType = 'Fab\Vidi\Domain\Model\Content';
122
-
123
-    /**
124
-     * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
125
-     */
126
-    public function __construct(QueryInterface $query)
127
-    {
128
-        $this->query = $query;
129
-        $this->databaseHandle = $GLOBALS['TYPO3_DB'];
130
-    }
131
-
132
-    /**
133
-     * Lifecycle method
134
-     *
135
-     * @return void
136
-     */
137
-    public function initializeObject()
138
-    {
139
-        $this->tableColumnCache = $this->cacheManager->getCache('extbase_typo3dbbackend_tablecolumns');
140
-    }
141
-
142
-    /**
143
-     * @param array $identifier
144
-     * @return string
145
-     */
146
-    protected function parseIdentifier(array $identifier)
147
-    {
148
-        $fieldNames = array_keys($identifier);
149
-        $suffixedFieldNames = array();
150
-        foreach ($fieldNames as $fieldName) {
151
-            $suffixedFieldNames[] = $fieldName . '=?';
152
-        }
153
-        return implode(' AND ', $suffixedFieldNames);
154
-    }
155
-
156
-    /**
157
-     * Returns the result of the query
158
-     */
159
-    public function fetchResult()
160
-    {
161
-
162
-        $parameters = array();
163
-        $statementParts = $this->parseQuery($this->query, $parameters);
164
-        $statementParts = $this->processStatementStructureForRecursiveMMRelation($statementParts); // Mmm... check if that is the right way of doing that.
165
-
166
-        $sql = $this->buildQuery($statementParts);
167
-        $tableName = '';
168
-        if (is_array($statementParts) && !empty($statementParts['tables'][0])) {
169
-            $tableName = $statementParts['tables'][0];
170
-        }
171
-        $this->replacePlaceholders($sql, $parameters, $tableName);
172
-        #print $sql; exit(); // @debug
173
-
174
-        $result = $this->databaseHandle->sql_query($sql);
175
-        $this->checkSqlErrors($sql);
176
-        $rows = $this->getRowsFromResult($result);
177
-        $this->databaseHandle->sql_free_result($result);
178
-
179
-        return $rows;
180
-    }
181
-
182
-    /**
183
-     * Returns the number of tuples matching the query.
184
-     *
185
-     * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException
186
-     * @return int The number of matching tuples
187
-     */
188
-    public function countResult()
189
-    {
190
-
191
-        $parameters = array();
192
-        $statementParts = $this->parseQuery($this->query, $parameters);
193
-        $statementParts = $this->processStatementStructureForRecursiveMMRelation($statementParts); // Mmm... check if that is the right way of doing that.
194
-        // Reset $statementParts for valid table return
195
-        reset($statementParts);
196
-
197
-        // if limit is set, we need to count the rows "manually" as COUNT(*) ignores LIMIT constraints
198
-        if (!empty($statementParts['limit'])) {
199
-            $statement = $this->buildQuery($statementParts);
200
-            $this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
201
-            #print $statement; exit(); // @debug
202
-            $result = $this->databaseHandle->sql_query($statement);
203
-            $this->checkSqlErrors($statement);
204
-            $count = $this->databaseHandle->sql_num_rows($result);
205
-        } else {
206
-            $statementParts['fields'] = array('COUNT(*)');
207
-            // having orderings without grouping is not compatible with non-MySQL DBMS
208
-            $statementParts['orderings'] = array();
209
-            if (isset($statementParts['keywords']['distinct'])) {
210
-                unset($statementParts['keywords']['distinct']);
211
-                $distinctField = $this->query->getDistinct() ? $this->query->getDistinct() : 'uid';
212
-                $statementParts['fields'] = array('COUNT(DISTINCT ' . reset($statementParts['tables']) . '.' . $distinctField . ')');
213
-            }
214
-
215
-            $statement = $this->buildQuery($statementParts);
216
-            $this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
217
-
218
-            #print $statement; exit(); // @debug
219
-            $result = $this->databaseHandle->sql_query($statement);
220
-            $this->checkSqlErrors($statement);
221
-            $count = 0;
222
-            if ($result) {
223
-                $row = $this->databaseHandle->sql_fetch_assoc($result);
224
-                $count = current($row);
225
-            }
226
-        }
227
-        $this->databaseHandle->sql_free_result($result);
228
-        return (int)$count;
229
-    }
230
-
231
-    /**
232
-     * Parses the query and returns the SQL statement parts.
233
-     *
234
-     * @param QueryInterface $query The query
235
-     * @param array &$parameters
236
-     * @return array The SQL statement parts
237
-     */
238
-    public function parseQuery(QueryInterface $query, array &$parameters)
239
-    {
240
-        $statementParts = array();
241
-        $statementParts['keywords'] = array();
242
-        $statementParts['tables'] = array();
243
-        $statementParts['unions'] = array();
244
-        $statementParts['fields'] = array();
245
-        $statementParts['where'] = array();
246
-        $statementParts['additionalWhereClause'] = array();
247
-        $statementParts['orderings'] = array();
248
-        $statementParts['limit'] = array();
249
-        $source = $query->getSource();
250
-        $this->parseSource($source, $statementParts);
251
-        $this->parseConstraint($query->getConstraint(), $source, $statementParts, $parameters);
252
-        $this->parseOrderings($query->getOrderings(), $source, $statementParts);
253
-        $this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $statementParts);
254
-        $tableNames = array_unique(array_keys($statementParts['tables'] + $statementParts['unions']));
255
-        foreach ($tableNames as $tableNameOrAlias) {
256
-            if (is_string($tableNameOrAlias) && strlen($tableNameOrAlias) > 0) {
257
-                $this->addAdditionalWhereClause($query->getQuerySettings(), $tableNameOrAlias, $statementParts);
258
-            }
259
-        }
260
-
261
-        return $statementParts;
262
-    }
263
-
264
-    /**
265
-     * Fiddle with the statement structure to handle recursive MM relations.
266
-     * For the recursive MM query to work, we must invert some values.
267
-     * Let see if that is the best way of doing that...
268
-     *
269
-     * @param array $statementParts
270
-     * @return array
271
-     */
272
-    public function processStatementStructureForRecursiveMMRelation(array $statementParts)
273
-    {
274
-
275
-        if ($this->hasRecursiveMMRelation()) {
276
-            $tableName = $this->query->getType();
277
-
278
-            // In order the MM query to work for a recursive MM query, we must invert some values.
279
-            // tx_domain_model_foo0 (the alias) <--> tx_domain_model_foo (the origin table name)
280
-            $values = array();
281
-            foreach ($statementParts['fields'] as $key => $value) {
282
-                $values[$key] = str_replace($tableName, $tableName . '0', $value);
283
-            }
284
-            $statementParts['fields'] = $values;
285
-
286
-            // Same comment as above.
287
-            $values = array();
288
-            foreach ($statementParts['where'] as $key => $value) {
289
-                $values[$key] = str_replace($tableName . '0', $tableName, $value);
290
-            }
291
-            $statementParts['where'] = $values;
292
-
293
-            // We must be more restrictive by transforming the "left" union by "inner"
294
-            $values = array();
295
-            foreach ($statementParts['unions'] as $key => $value) {
296
-                $values[$key] = str_replace('LEFT JOIN', 'INNER JOIN', $value);
297
-            }
298
-            $statementParts['unions'] = $values;
299
-        }
300
-
301
-        return $statementParts;
302
-    }
303
-
304
-    /**
305
-     * Tell whether there is a recursive MM relation.
306
-     *
307
-     * @return bool
308
-     */
309
-    public function hasRecursiveMMRelation()
310
-    {
311
-        return isset($this->tableNameAliases['aliasIncrement'][$this->query->getType()]);
312
-
313
-    }
314
-
315
-    /**
316
-     * Returns the statement, ready to be executed.
317
-     *
318
-     * @param array $statementParts The SQL statement parts
319
-     * @return string The SQL statement
320
-     */
321
-    public function buildQuery(array $statementParts)
322
-    {
323
-
324
-        // Add more statement to the UNION part.
325
-        if (!empty($statementParts['unions'])) {
326
-            foreach ($statementParts['unions'] as $tableName => $unionPart) {
327
-                if (!empty($statementParts['additionalWhereClause'][$tableName])) {
328
-                    $statementParts['unions'][$tableName] .= ' AND ' . implode(' AND ', $statementParts['additionalWhereClause'][$tableName]);
329
-                }
330
-            }
331
-        }
332
-
333
-        $statement = 'SELECT ' . implode(' ', $statementParts['keywords']) . ' ' . implode(',', $statementParts['fields']) . ' FROM ' . implode(' ', $statementParts['tables']) . ' ' . implode(' ', $statementParts['unions']);
334
-        if (!empty($statementParts['where'])) {
335
-            $statement .= ' WHERE ' . implode('', $statementParts['where']);
336
-            if (!empty($statementParts['additionalWhereClause'][$this->query->getType()])) {
337
-                $statement .= ' AND ' . implode(' AND ', $statementParts['additionalWhereClause'][$this->query->getType()]);
338
-            }
339
-        } elseif (!empty($statementParts['additionalWhereClause'])) {
340
-            $statement .= ' WHERE ' . implode(' AND ', $statementParts['additionalWhereClause'][$this->query->getType()]);
341
-        }
342
-        if (!empty($statementParts['orderings'])) {
343
-            $statement .= ' ORDER BY ' . implode(', ', $statementParts['orderings']);
344
-        }
345
-        if (!empty($statementParts['limit'])) {
346
-            $statement .= ' LIMIT ' . $statementParts['limit'];
347
-        }
348
-
349
-        return $statement;
350
-    }
351
-
352
-    /**
353
-     * Transforms a Query Source into SQL and parameter arrays
354
-     *
355
-     * @param SourceInterface $source The source
356
-     * @param array &$sql
357
-     * @return void
358
-     */
359
-    protected function parseSource(SourceInterface $source, array &$sql)
360
-    {
361
-        if ($source instanceof SelectorInterface) {
362
-            $tableName = $source->getNodeTypeName();
363
-            $sql['fields'][$tableName] = $tableName . '.*';
364
-            $sql['tables'][$tableName] = $tableName;
365
-            if ($this->query->getDistinct()) {
366
-                $sql['fields'][$tableName] = $tableName . '.' . $this->query->getDistinct();
367
-                $sql['keywords']['distinct'] = 'DISTINCT';
368
-            }
369
-        } elseif ($source instanceof JoinInterface) {
370
-            $this->parseJoin($source, $sql);
371
-        }
372
-    }
373
-
374
-    /**
375
-     * Transforms a Join into SQL and parameter arrays
376
-     *
377
-     * @param JoinInterface $join The join
378
-     * @param array &$sql The query parts
379
-     * @return void
380
-     */
381
-    protected function parseJoin(JoinInterface $join, array &$sql)
382
-    {
383
-        $leftSource = $join->getLeft();
384
-        $leftTableName = $leftSource->getSelectorName();
385
-        // $sql['fields'][$leftTableName] = $leftTableName . '.*';
386
-        $rightSource = $join->getRight();
387
-        if ($rightSource instanceof JoinInterface) {
388
-            $rightTableName = $rightSource->getLeft()->getSelectorName();
389
-        } else {
390
-            $rightTableName = $rightSource->getSelectorName();
391
-            $sql['fields'][$leftTableName] = $rightTableName . '.*';
392
-        }
393
-        $sql['tables'][$leftTableName] = $leftTableName;
394
-        $sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
395
-        $joinCondition = $join->getJoinCondition();
396
-        if ($joinCondition instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\EquiJoinCondition) {
397
-            $column1Name = $joinCondition->getProperty1Name();
398
-            $column2Name = $joinCondition->getProperty2Name();
399
-            $sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
400
-        }
401
-        if ($rightSource instanceof JoinInterface) {
402
-            $this->parseJoin($rightSource, $sql);
403
-        }
404
-    }
405
-
406
-    /**
407
-     * Transforms a constraint into SQL and parameter arrays
408
-     *
409
-     * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint The constraint
410
-     * @param SourceInterface $source The source
411
-     * @param array &$sql The query parts
412
-     * @param array &$parameters The parameters that will replace the markers
413
-     * @return void
414
-     */
415
-    protected function parseConstraint(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint = NULL, SourceInterface $source, array &$sql, array &$parameters)
416
-    {
417
-        if ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface) {
418
-            $sql['where'][] = '(';
419
-            $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
420
-            $sql['where'][] = ' AND ';
421
-            $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
422
-            $sql['where'][] = ')';
423
-        } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface) {
424
-            $sql['where'][] = '(';
425
-            $this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
426
-            $sql['where'][] = ' OR ';
427
-            $this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
428
-            $sql['where'][] = ')';
429
-        } elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface) {
430
-            $sql['where'][] = 'NOT (';
431
-            $this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
432
-            $sql['where'][] = ')';
433
-        } elseif ($constraint instanceof ComparisonInterface) {
434
-            $this->parseComparison($constraint, $source, $sql, $parameters);
435
-        }
436
-    }
437
-
438
-    /**
439
-     * Parse a Comparison into SQL and parameter arrays.
440
-     *
441
-     * @param ComparisonInterface $comparison The comparison to parse
442
-     * @param SourceInterface $source The source
443
-     * @param array &$sql SQL query parts to add to
444
-     * @param array &$parameters Parameters to bind to the SQL
445
-     * @throws Exception\RepositoryException
446
-     * @return void
447
-     */
448
-    protected function parseComparison(ComparisonInterface $comparison, SourceInterface $source, array &$sql, array &$parameters)
449
-    {
450
-        $operand1 = $comparison->getOperand1();
451
-        $operator = $comparison->getOperator();
452
-        $operand2 = $comparison->getOperand2();
453
-        if ($operator === QueryInterface::OPERATOR_IN) {
454
-            $items = array();
455
-            $hasValue = FALSE;
456
-            foreach ($operand2 as $value) {
457
-                $value = $this->getPlainValue($value);
458
-                if ($value !== NULL) {
459
-                    $items[] = $value;
460
-                    $hasValue = TRUE;
461
-                }
462
-            }
463
-            if ($hasValue === FALSE) {
464
-                $sql['where'][] = '1<>1';
465
-            } else {
466
-                $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL);
467
-                $parameters[] = $items;
468
-            }
469
-        } elseif ($operator === QueryInterface::OPERATOR_CONTAINS) {
470
-            if ($operand2 === NULL) {
471
-                $sql['where'][] = '1<>1';
472
-            } else {
473
-                throw new \Exception('Not implemented! Contact extension author.', 1412931227);
474
-                # @todo re-implement me if necessary.
475
-                #$tableName = $this->query->getType();
476
-                #$propertyName = $operand1->getPropertyName();
477
-                #while (strpos($propertyName, '.') !== FALSE) {
478
-                #	$this->addUnionStatement($tableName, $propertyName, $sql);
479
-                #}
480
-                #$columnName = $propertyName;
481
-                #$columnMap = $propertyName;
482
-                #$typeOfRelation = $columnMap instanceof ColumnMap ? $columnMap->getTypeOfRelation() : NULL;
483
-                #if ($typeOfRelation === ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
484
-                #	$relationTableName = $columnMap->getRelationTableName();
485
-                #	$sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=?)';
486
-                #	$parameters[] = intval($this->getPlainValue($operand2));
487
-                #} elseif ($typeOfRelation === ColumnMap::RELATION_HAS_MANY) {
488
-                #	$parentKeyFieldName = $columnMap->getParentKeyFieldName();
489
-                #	if (isset($parentKeyFieldName)) {
490
-                #		$childTableName = $columnMap->getChildTableName();
491
-                #		$sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=?)';
492
-                #		$parameters[] = intval($this->getPlainValue($operand2));
493
-                #	} else {
494
-                #		$sql['where'][] = 'FIND_IN_SET(?,' . $tableName . '.' . $columnName . ')';
495
-                #		$parameters[] = intval($this->getPlainValue($operand2));
496
-                #	}
497
-                #} else {
498
-                #	throw new Exception\RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
499
-                #}
500
-            }
501
-        } else {
502
-            if ($operand2 === NULL) {
503
-                if ($operator === QueryInterface::OPERATOR_EQUAL_TO) {
504
-                    $operator = self::OPERATOR_EQUAL_TO_NULL;
505
-                } elseif ($operator === QueryInterface::OPERATOR_NOT_EQUAL_TO) {
506
-                    $operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
507
-                }
508
-            }
509
-            $this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
510
-            $parameters[] = $this->getPlainValue($operand2);
511
-        }
512
-    }
513
-
514
-    /**
515
-     * Returns a plain value, i.e. objects are flattened out if possible.
516
-     *
517
-     * @param mixed $input
518
-     * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
519
-     * @return mixed
520
-     */
521
-    protected function getPlainValue($input)
522
-    {
523
-        if (is_array($input)) {
524
-            throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
525
-        }
526
-        if ($input instanceof \DateTime) {
527
-            return $input->format('U');
528
-        } elseif (is_object($input)) {
529
-            if ($input instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
530
-                $realInput = $input->_loadRealInstance();
531
-            } else {
532
-                $realInput = $input;
533
-            }
534
-            if ($realInput instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
535
-                return $realInput->getUid();
536
-            } else {
537
-                throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An object of class "' . get_class($realInput) . '" could not be converted to a plain value.', 1274799934);
538
-            }
539
-        } elseif (is_bool($input)) {
540
-            return $input === TRUE ? 1 : 0;
541
-        } else {
542
-            return $input;
543
-        }
544
-    }
545
-
546
-    /**
547
-     * Parse a DynamicOperand into SQL and parameter arrays.
548
-     *
549
-     * @param DynamicOperandInterface $operand
550
-     * @param string $operator One of the JCR_OPERATOR_* constants
551
-     * @param SourceInterface $source The source
552
-     * @param array &$sql The query parts
553
-     * @param array &$parameters The parameters that will replace the markers
554
-     * @param string $valueFunction an optional SQL function to apply to the operand value
555
-     * @return void
556
-     */
557
-    protected function parseDynamicOperand(DynamicOperandInterface $operand, $operator, SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL)
558
-    {
559
-        if ($operand instanceof LowerCaseInterface) {
560
-            $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
561
-        } elseif ($operand instanceof UpperCaseInterface) {
562
-            $this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
563
-        } elseif ($operand instanceof PropertyValueInterface) {
564
-            $propertyName = $operand->getPropertyName();
565
-
566
-            // Reset value.
567
-            $this->currentChildTableNameAlias = '';
568
-
569
-            if ($source instanceof SelectorInterface) {
570
-                $tableName = $this->query->getType();
571
-                while (strpos($propertyName, '.') !== FALSE) {
572
-                    $this->addUnionStatement($tableName, $propertyName, $sql);
573
-                }
574
-            } elseif ($source instanceof JoinInterface) {
575
-                $tableName = $source->getJoinCondition()->getSelector1Name();
576
-            }
577
-
578
-            $columnName = $propertyName;
579
-            $operator = $this->resolveOperator($operator);
580
-            $constraintSQL = '';
581
-            if ($valueFunction === NULL) {
582
-                $constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
583
-            } else {
584
-                $constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ') ' . $operator . ' ?';
585
-            }
586
-
587
-            if (isset($tableName) && !empty($this->currentChildTableNameAlias)) {
588
-                $constraintSQL = $this->replaceTableNameByAlias($tableName, $this->currentChildTableNameAlias, $constraintSQL);
589
-            }
590
-            $sql['where'][] = $constraintSQL;
591
-        }
592
-    }
593
-
594
-    /**
595
-     * @param string &$tableName
596
-     * @param array &$propertyPath
597
-     * @param array &$sql
598
-     * @throws Exception
599
-     * @throws Exception\InvalidRelationConfigurationException
600
-     * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException
601
-     */
602
-    protected function addUnionStatement(&$tableName, &$propertyPath, array &$sql)
603
-    {
604
-
605
-        $table = Tca::table($tableName);
606
-
607
-        $explodedPropertyPath = explode('.', $propertyPath, 2);
608
-        $fieldName = $explodedPropertyPath[0];
609
-
610
-        // Field of type "group" are special because property path must contain the table name
611
-        // to determine the relation type. Example for sys_category, property path will look like "items.sys_file"
612
-        if ($table->field($fieldName)->isGroup()) {
613
-            $parts = explode('.', $propertyPath, 3);
614
-            $explodedPropertyPath[0] = $parts[0] . '.' . $parts[1];
615
-            $explodedPropertyPath[1] = $parts[2];
616
-            $fieldName = $explodedPropertyPath[0];
617
-        }
618
-
619
-        $parentKeyFieldName = $table->field($fieldName)->getForeignField();
620
-        $childTableName = $table->field($fieldName)->getForeignTable();
621
-
622
-        if ($childTableName === NULL) {
623
-            throw new Exception\InvalidRelationConfigurationException('The relation information for property "' . $fieldName . '" of class "' . $tableName . '" is missing.', 1353170925);
624
-        }
625
-
626
-        if ($table->field($fieldName)->hasOne()) { // includes relation "one-to-one" and "many-to-one"
627
-            // sometimes the opposite relation is not defined. We don't want to force this config for backward compatibility reasons.
628
-            // $parentKeyFieldName === NULL does the trick somehow. Before condition was if (isset($parentKeyFieldName))
629
-            if ($table->field($fieldName)->hasRelationManyToOne() || $parentKeyFieldName === NULL) {
630
-                $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $fieldName . '=' . $childTableName . '.uid';
631
-            } else {
632
-                $sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
633
-            }
634
-        } elseif ($table->field($fieldName)->hasRelationManyToMany()) {
635
-            $relationTableName = $table->field($fieldName)->getManyToManyTable();
636
-
637
-            $parentKeyFieldName = $table->field($fieldName)->isOppositeRelation() ? 'uid_foreign' : 'uid_local';
638
-            $childKeyFieldName = !$table->field($fieldName)->isOppositeRelation() ? 'uid_foreign' : 'uid_local';
639
-
640
-            // MM table e.g sys_category_record_mm
641
-            $relationTableNameAlias = $this->generateAlias($relationTableName);
642
-            $join = sprintf(
643
-                'LEFT JOIN %s AS %s ON %s.uid=%s.%s', $relationTableName,
644
-                $relationTableNameAlias,
645
-                $tableName,
646
-                $relationTableNameAlias,
647
-                $parentKeyFieldName
648
-            );
649
-            $sql['unions'][$relationTableNameAlias] = $join;
650
-
651
-            // Foreign table e.g sys_category
652
-            $childTableNameAlias = $this->generateAlias($childTableName);
653
-            $this->currentChildTableNameAlias = $childTableNameAlias;
654
-            $join = sprintf(
655
-                'LEFT JOIN %s AS %s ON %s.%s=%s.uid',
656
-                $childTableName,
657
-                $childTableNameAlias,
658
-                $relationTableNameAlias,
659
-                $childKeyFieldName,
660
-                $childTableNameAlias
661
-            );
662
-            $sql['unions'][$childTableNameAlias] = $join;
663
-
664
-            // Find a possible table name for a MM condition.
665
-            $tableNameCondition = $table->field($fieldName)->getAdditionalTableNameCondition();
666
-            if ($tableNameCondition) {
667
-
668
-                // If we can find a source file name,  we can then retrieve more MM conditions from the TCA such as a field name.
669
-                $sourceFileName = $this->query->getSourceFieldName();
670
-                if (empty($sourceFileName)) {
671
-                    $additionalMMConditions = array(
672
-                        'tablenames' => $tableNameCondition,
673
-                    );
674
-                } else {
675
-                    $additionalMMConditions = Tca::table($tableNameCondition)->field($sourceFileName)->getAdditionalMMCondition();
676
-                }
677
-
678
-                foreach ($additionalMMConditions as $additionalFieldName => $additionalMMCondition) {
679
-                    $additionalJoin = sprintf(' AND %s.%s = "%s"', $relationTableNameAlias, $additionalFieldName, $additionalMMCondition);
680
-                    $sql['unions'][$relationTableNameAlias] .= $additionalJoin;
681
-
682
-                    $additionalJoin = sprintf(' AND %s.%s = "%s"', $relationTableNameAlias, $additionalFieldName, $additionalMMCondition);
683
-                    $sql['unions'][$childTableNameAlias] .= $additionalJoin;
684
-                }
685
-
686
-            }
687
-
688
-
689
-        } elseif ($table->field($fieldName)->hasMany()) { // includes relations "many-to-one" and "csv" relations
690
-            $childTableNameAlias = $this->generateAlias($childTableName);
691
-            $this->currentChildTableNameAlias = $childTableNameAlias;
692
-
693
-            if (isset($parentKeyFieldName)) {
694
-                $join = sprintf(
695
-                    'LEFT JOIN %s AS %s ON %s.uid=%s.%s',
696
-                    $childTableName,
697
-                    $childTableNameAlias,
698
-                    $tableName,
699
-                    $childTableNameAlias,
700
-                    $parentKeyFieldName
701
-                );
702
-                $sql['unions'][$childTableNameAlias] = $join;
703
-            } else {
704
-                $join = sprintf(
705
-                    'LEFT JOIN %s AS %s ON (FIND_IN_SET(%s.uid, %s.%s))',
706
-                    $childTableName,
707
-                    $childTableNameAlias,
708
-                    $childTableNameAlias,
709
-                    $tableName,
710
-                    $fieldName
711
-                );
712
-                $sql['unions'][$childTableNameAlias] = $join;
713
-            }
714
-        } else {
715
-            throw new Exception('Could not determine type of relation.', 1252502725);
716
-        }
717
-
718
-        // TODO check if there is another solution for this
719
-        $sql['keywords']['distinct'] = 'DISTINCT';
720
-        $propertyPath = $explodedPropertyPath[1];
721
-        $tableName = $childTableName;
722
-    }
723
-
724
-    /**
725
-     * Returns the SQL operator for the given JCR operator type.
726
-     *
727
-     * @param string $operator One of the JCR_OPERATOR_* constants
728
-     * @throws Exception
729
-     * @return string an SQL operator
730
-     */
731
-    protected function resolveOperator($operator)
732
-    {
733
-        switch ($operator) {
734
-            case self::OPERATOR_EQUAL_TO_NULL:
735
-                $operator = 'IS';
736
-                break;
737
-            case self::OPERATOR_NOT_EQUAL_TO_NULL:
738
-                $operator = 'IS NOT';
739
-                break;
740
-            case QueryInterface::OPERATOR_IN:
741
-                $operator = 'IN';
742
-                break;
743
-            case QueryInterface::OPERATOR_EQUAL_TO:
744
-                $operator = '=';
745
-                break;
746
-            case QueryInterface::OPERATOR_NOT_EQUAL_TO:
747
-                $operator = '!=';
748
-                break;
749
-            case QueryInterface::OPERATOR_LESS_THAN:
750
-                $operator = '<';
751
-                break;
752
-            case QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
753
-                $operator = '<=';
754
-                break;
755
-            case QueryInterface::OPERATOR_GREATER_THAN:
756
-                $operator = '>';
757
-                break;
758
-            case QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
759
-                $operator = '>=';
760
-                break;
761
-            case QueryInterface::OPERATOR_LIKE:
762
-                $operator = 'LIKE';
763
-                break;
764
-            default:
765
-                throw new Exception('Unsupported operator encountered.', 1242816073);
766
-        }
767
-        return $operator;
768
-    }
769
-
770
-    /**
771
-     * Replace query placeholders in a query part by the given
772
-     * parameters.
773
-     *
774
-     * @param string &$sqlString The query part with placeholders
775
-     * @param array $parameters The parameters
776
-     * @param string $tableName
777
-     *
778
-     * @throws Exception
779
-     */
780
-    protected function replacePlaceholders(&$sqlString, array $parameters, $tableName = 'foo')
781
-    {
782
-        // TODO profile this method again
783
-        if (substr_count($sqlString, '?') !== count($parameters)) {
784
-            throw new Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
785
-        }
786
-        $offset = 0;
787
-        foreach ($parameters as $parameter) {
788
-            $markPosition = strpos($sqlString, '?', $offset);
789
-            if ($markPosition !== FALSE) {
790
-                if ($parameter === NULL) {
791
-                    $parameter = 'NULL';
792
-                } elseif (is_array($parameter) || $parameter instanceof \ArrayAccess || $parameter instanceof \Traversable) {
793
-                    $items = array();
794
-                    foreach ($parameter as $item) {
795
-                        $items[] = $this->databaseHandle->fullQuoteStr($item, $tableName);
796
-                    }
797
-                    $parameter = '(' . implode(',', $items) . ')';
798
-                } else {
799
-                    $parameter = $this->databaseHandle->fullQuoteStr($parameter, $tableName);
800
-                }
801
-                $sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, ($markPosition + 1));
802
-            }
803
-            $offset = $markPosition + strlen($parameter);
804
-        }
805
-    }
806
-
807
-    /**
808
-     * Adds additional WHERE statements according to the query settings.
809
-     *
810
-     * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
811
-     * @param string $tableNameOrAlias The table name to add the additional where clause for
812
-     * @param array &$statementParts
813
-     * @return void
814
-     */
815
-    protected function addAdditionalWhereClause(QuerySettingsInterface $querySettings, $tableNameOrAlias, &$statementParts)
816
-    {
817
-        $this->addVisibilityConstraintStatement($querySettings, $tableNameOrAlias, $statementParts);
818
-        if ($querySettings->getRespectSysLanguage()) {
819
-            $this->addSysLanguageStatement($tableNameOrAlias, $statementParts, $querySettings);
820
-        }
821
-        if ($querySettings->getRespectStoragePage()) {
822
-            $this->addPageIdStatement($tableNameOrAlias, $statementParts, $querySettings->getStoragePageIds());
823
-        }
824
-    }
825
-
826
-    /**
827
-     * Adds enableFields and deletedClause to the query if necessary
828
-     *
829
-     * @param QuerySettingsInterface $querySettings
830
-     * @param string $tableNameOrAlias The database table name
831
-     * @param array &$statementParts The query parts
832
-     * @return void
833
-     */
834
-    protected function addVisibilityConstraintStatement(QuerySettingsInterface $querySettings, $tableNameOrAlias, array &$statementParts)
835
-    {
836
-        $statement = '';
837
-        $tableName = $this->resolveTableNameAlias($tableNameOrAlias);
838
-        if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
839
-            $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
840
-            $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
841
-            $includeDeleted = $querySettings->getIncludeDeleted();
842
-            if ($this->environmentService->isEnvironmentInFrontendMode()) {
843
-                $statement .= $this->getFrontendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
844
-            } else {
845
-                // TYPO3_MODE === 'BE'
846
-                $statement .= $this->getBackendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $includeDeleted);
847
-            }
848
-
849
-            // Remove the prefixing "AND" if any.
850
-            if (!empty($statement)) {
851
-                $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
852
-                $statementParts['additionalWhereClause'][$tableNameOrAlias][] = $statement;
853
-            }
854
-        }
855
-    }
856
-
857
-    /**
858
-     * Returns constraint statement for frontend context
859
-     *
860
-     * @param string $tableNameOrAlias
861
-     * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
862
-     * @param array $enableFieldsToBeIgnored If $ignoreEnableFields is true, this array specifies enable fields to be ignored. If it is NULL or an empty array (default) all enable fields are ignored.
863
-     * @param boolean $includeDeleted A flag indicating whether deleted records should be included
864
-     * @return string
865
-     * @throws Exception\InconsistentQuerySettingsException
866
-     */
867
-    protected function getFrontendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $enableFieldsToBeIgnored = array(), $includeDeleted)
868
-    {
869
-        $statement = '';
870
-        $tableName = $this->resolveTableNameAlias($tableNameOrAlias);
871
-        if ($ignoreEnableFields && !$includeDeleted) {
872
-            if (count($enableFieldsToBeIgnored)) {
873
-                // array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
874
-                $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
875
-            } else {
876
-                $statement .= $this->getPageRepository()->deleteClause($tableName);
877
-            }
878
-        } elseif (!$ignoreEnableFields && !$includeDeleted) {
879
-            $statement .= $this->getPageRepository()->enableFields($tableName);
880
-        } elseif (!$ignoreEnableFields && $includeDeleted) {
881
-            throw new Exception\InconsistentQuerySettingsException('Query setting "ignoreEnableFields=FALSE" can not be used together with "includeDeleted=TRUE" in frontend context.', 1327678173);
882
-        }
883
-        return $this->replaceTableNameByAlias($tableName, $tableNameOrAlias, $statement);
884
-    }
885
-
886
-    /**
887
-     * Returns constraint statement for backend context
888
-     *
889
-     * @param string $tableNameOrAlias
890
-     * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
891
-     * @param boolean $includeDeleted A flag indicating whether deleted records should be included
892
-     * @return string
893
-     */
894
-    protected function getBackendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $includeDeleted)
895
-    {
896
-        $tableName = $this->resolveTableNameAlias($tableNameOrAlias);
897
-        $statement = '';
898
-        if (!$ignoreEnableFields) {
899
-            $statement .= BackendUtility::BEenableFields($tableName);
900
-        }
901
-
902
-        // If the table is found to have "workspace" support, add the corresponding fields in the statement.
903
-        if (Tca::table($tableName)->hasWorkspaceSupport()) {
904
-            if ($this->getBackendUser()->workspace === 0) {
905
-                $statement .= ' AND ' . $tableName . '.t3ver_state<=' . new VersionState(VersionState::DEFAULT_STATE);
906
-            } else {
907
-                // Show only records of live and of the current workspace
908
-                // In case we are in a Versioning preview
909
-                $statement .= ' AND (' .
910
-                    $tableName . '.t3ver_wsid=0 OR ' .
911
-                    $tableName . '.t3ver_wsid=' . (int)$this->getBackendUser()->workspace .
912
-                    ')';
913
-            }
914
-
915
-            // Check if this segment make sense here or whether it should be in the "if" part when we have workspace = 0
916
-            $statement .= ' AND ' . $tableName . '.pid<>-1';
917
-        }
918
-
919
-        if (!$includeDeleted) {
920
-            $statement .= BackendUtility::deleteClause($tableName);
921
-        }
922
-
923
-        return $this->replaceTableNameByAlias($tableName, $tableNameOrAlias, $statement);
924
-    }
925
-
926
-    /**
927
-     * Builds the language field statement
928
-     *
929
-     * @param string $tableNameOrAlias The database table name
930
-     * @param array &$statementParts The query parts
931
-     * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
932
-     * @throws Exception
933
-     * @return void
934
-     */
935
-    protected function addSysLanguageStatement($tableNameOrAlias, array &$statementParts, $querySettings)
936
-    {
937
-
938
-        $tableName = $this->resolveTableNameAlias($tableNameOrAlias);
939
-        if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
940
-            if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
941
-                // Select all entries for the current language
942
-                $additionalWhereClause = $tableNameOrAlias . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (' . intval($querySettings->getLanguageUid()) . ',-1)';
943
-                // If any language is set -> get those entries which are not translated yet
944
-                // They will be removed by t3lib_page::getRecordOverlay if not matching overlay mode
945
-                if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
946
-                    && $querySettings->getLanguageUid() > 0
947
-                ) {
948
-                    $additionalWhereClause .= ' OR (' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0' .
949
-                        ' AND ' . $tableName . '.uid NOT IN (SELECT ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] .
950
-                        ' FROM ' . $tableName .
951
-                        ' WHERE ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] . '>0' .
952
-                        ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '>0';
953
-
954
-                    // Add delete clause to ensure all entries are loaded
955
-                    if (isset($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
956
-                        $additionalWhereClause .= ' AND ' . $tableNameOrAlias . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
957
-                    }
958
-                    $additionalWhereClause .= '))';
959
-                    throw new Exception('Not tested code! It will fail', 1412928284);
960
-                }
961
-                $statementParts['additionalWhereClause'][$tableNameOrAlias][] = '(' . $additionalWhereClause . ')';
962
-            }
963
-        }
964
-    }
965
-
966
-    /**
967
-     * Builds the page ID checking statement
968
-     *
969
-     * @param string $tableNameOrAlias The database table name
970
-     * @param array &$statementParts The query parts
971
-     * @param array $storagePageIds list of storage page ids
972
-     * @throws Exception\InconsistentQuerySettingsException
973
-     * @return void
974
-     */
975
-    protected function addPageIdStatement($tableNameOrAlias, array &$statementParts, array $storagePageIds)
976
-    {
977
-
978
-        $tableName = $this->resolveTableNameAlias($tableNameOrAlias);
979
-        $tableColumns = $this->tableColumnCache->get($tableName);
980
-        if ($tableColumns === FALSE) {
981
-            $tableColumns = $this->databaseHandle->admin_get_fields($tableName);
982
-            $this->tableColumnCache->set($tableName, $tableColumns);
983
-        }
984
-        if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $tableColumns)) {
985
-            $rootLevel = (int)$GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'];
986
-            if ($rootLevel) {
987
-                if ($rootLevel === 1) {
988
-                    $statementParts['additionalWhereClause'][$tableNameOrAlias][] = $tableNameOrAlias . '.pid = 0';
989
-                }
990
-            } else {
991
-                if (empty($storagePageIds)) {
992
-                    throw new Exception\InconsistentQuerySettingsException('Missing storage page ids.', 1365779762);
993
-                }
994
-                $statementParts['additionalWhereClause'][$tableNameOrAlias][] = $tableNameOrAlias . '.pid IN (' . implode(', ', $storagePageIds) . ')';
995
-            }
996
-        }
997
-    }
998
-
999
-    /**
1000
-     * Transforms orderings into SQL.
1001
-     *
1002
-     * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
1003
-     * @param SourceInterface $source The source
1004
-     * @param array &$sql The query parts
1005
-     * @throws Exception\UnsupportedOrderException
1006
-     * @return void
1007
-     */
1008
-    protected function parseOrderings(array $orderings, SourceInterface $source, array &$sql)
1009
-    {
1010
-        foreach ($orderings as $fieldNameAndPath => $order) {
1011
-            switch ($order) {
1012
-                case QueryInterface::ORDER_ASCENDING:
1013
-                    $order = 'ASC';
1014
-                    break;
1015
-                case QueryInterface::ORDER_DESCENDING:
1016
-                    $order = 'DESC';
1017
-                    break;
1018
-                default:
1019
-                    throw new Exception\UnsupportedOrderException('Unsupported order encountered.', 1456845126);
1020
-            }
1021
-
1022
-            $tableName = $this->getFieldPathResolver()->getDataType($fieldNameAndPath, $this->query->getType());
1023
-            $fieldName = $this->getFieldPathResolver()->stripFieldPath($fieldNameAndPath, $tableName);
1024
-            $sql['orderings'][] = sprintf('%s.%s %s', $tableName, $fieldName, $order);
1025
-        }
1026
-    }
1027
-
1028
-    /**
1029
-     * Transforms limit and offset into SQL
1030
-     *
1031
-     * @param int $limit
1032
-     * @param int $offset
1033
-     * @param array &$sql
1034
-     * @return void
1035
-     */
1036
-    protected function parseLimitAndOffset($limit, $offset, array &$sql)
1037
-    {
1038
-        if ($limit !== NULL && $offset !== NULL) {
1039
-            $sql['limit'] = intval($offset) . ', ' . intval($limit);
1040
-        } elseif ($limit !== NULL) {
1041
-            $sql['limit'] = intval($limit);
1042
-        }
1043
-    }
1044
-
1045
-    /**
1046
-     * Transforms a Resource from a database query to an array of rows.
1047
-     *
1048
-     * @param resource $result The result
1049
-     * @return array The result as an array of rows (tuples)
1050
-     */
1051
-    protected function getRowsFromResult($result)
1052
-    {
1053
-        $rows = array();
1054
-        while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
1055
-            if (is_array($row)) {
1056
-
1057
-                // Get language uid from querySettings.
1058
-                // Ensure the backend handling is not broken (fallback to Get parameter 'L' if needed)
1059
-                $overlaidRow = $this->doLanguageAndWorkspaceOverlay($this->query->getSource(), $row, $this->query->getQuerySettings());
1060
-                $contentObject = GeneralUtility::makeInstance($this->objectType, $this->query->getType(), $overlaidRow);
1061
-                $rows[] = $contentObject;
1062
-            }
1063
-        }
1064
-
1065
-        return $rows;
1066
-    }
1067
-
1068
-    /**
1069
-     * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
1070
-     * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
1071
-     *
1072
-     * @param SourceInterface $source The source (selector od join)
1073
-     * @param array $row
1074
-     * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
1075
-     * @return array
1076
-     */
1077
-    protected function doLanguageAndWorkspaceOverlay(SourceInterface $source, array $row, $querySettings)
1078
-    {
1079
-
1080
-        /** @var SelectorInterface $source */
1081
-        $tableName = $source->getSelectorName();
1082
-
1083
-        $pageRepository = $this->getPageRepository();
1084
-        if (is_object($GLOBALS['TSFE'])) {
1085
-            $languageMode = $GLOBALS['TSFE']->sys_language_mode;
1086
-            if ($this->isBackendUserLogged() && $this->getBackendUser()->workspace !== 0) {
1087
-                $pageRepository->versioningWorkspaceId = $this->getBackendUser()->workspace;
1088
-            }
1089
-        } else {
1090
-            $languageMode = '';
1091
-            $workspaceUid = $this->getBackendUser()->workspace;
1092
-            $pageRepository->versioningWorkspaceId = $workspaceUid;
1093
-            if ($this->getBackendUser()->workspace !== 0) {
1094
-                $pageRepository->versioningPreview = 1;
1095
-            }
1096
-        }
1097
-
1098
-        // If current row is a translation select its parent
1099
-        if (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1100
-            && isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1101
-        ) {
1102
-            if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
1103
-                && $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
1104
-            ) {
1105
-                $row = $this->databaseHandle->exec_SELECTgetSingleRow(
1106
-                    $tableName . '.*',
1107
-                    $tableName,
1108
-                    $tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
1109
-                    ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
1110
-                );
1111
-            }
1112
-        }
1113
-
1114
-        // Retrieve the original uid
1115
-        // @todo It looks for me this code will never be used! "_ORIG_uid" is something from extbase. Adjust me or remove me in 0.4 + 2 version!
1116
-        $pageRepository->versionOL($tableName, $row, TRUE);
1117
-        if ($pageRepository->versioningPreview && isset($row['_ORIG_uid'])) {
1118
-            $row['uid'] = $row['_ORIG_uid'];
1119
-        }
1120
-
1121
-        // Special case for table "pages"
1122
-        if ($tableName == 'pages') {
1123
-            $row = $pageRepository->getPageOverlay($row, $querySettings->getLanguageUid());
1124
-        } elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1125
-            && $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
1126
-        ) {
1127
-            if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
1128
-                $overlayMode = $languageMode === 'strict' ? 'hideNonTranslated' : '';
1129
-                $row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getLanguageUid(), $overlayMode);
1130
-            }
1131
-        }
1132
-
1133
-        return $row;
1134
-    }
1135
-
1136
-    /**
1137
-     * Return a resolved table name given a possible table name alias.
1138
-     *
1139
-     * @param string $tableNameOrAlias
1140
-     * @return string
1141
-     */
1142
-    protected function resolveTableNameAlias($tableNameOrAlias)
1143
-    {
1144
-        $resolvedTableName = $tableNameOrAlias;
1145
-        if (!empty($this->tableNameAliases['aliases'][$tableNameOrAlias])) {
1146
-            $resolvedTableName = $this->tableNameAliases['aliases'][$tableNameOrAlias];
1147
-        }
1148
-        return $resolvedTableName;
1149
-    }
1150
-
1151
-    /**
1152
-     * Generate a unique table name alias for the given table name.
1153
-     *
1154
-     * @param string $tableName
1155
-     * @return string
1156
-     */
1157
-    protected function generateAlias($tableName)
1158
-    {
1159
-
1160
-        if (!isset($this->tableNameAliases['aliasIncrement'][$tableName])) {
1161
-            $this->tableNameAliases['aliasIncrement'][$tableName] = 0;
1162
-        }
1163
-
1164
-        $numberOfAliases = $this->tableNameAliases['aliasIncrement'][$tableName];
1165
-        $tableNameAlias = $tableName . $numberOfAliases;
1166
-
1167
-        $this->tableNameAliases['aliasIncrement'][$tableName]++;
1168
-        $this->tableNameAliases['aliases'][$tableNameAlias] = $tableName;
1169
-
1170
-        return $tableNameAlias;
1171
-    }
1172
-
1173
-    /**
1174
-     * Replace the table names by its table name alias within the given statement.
1175
-     *
1176
-     * @param string $tableName
1177
-     * @param string $tableNameAlias
1178
-     * @param string $statement
1179
-     * @return string
1180
-     */
1181
-    protected function replaceTableNameByAlias($tableName, $tableNameAlias, $statement)
1182
-    {
1183
-        if ($statement && $tableName !== $tableNameAlias) {
1184
-            $statement = str_replace($tableName, $tableNameAlias, $statement);
1185
-        }
1186
-        return $statement;
1187
-    }
1188
-
1189
-    /**
1190
-     * Returns an instance of the current Backend User.
1191
-     *
1192
-     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1193
-     */
1194
-    protected function getBackendUser()
1195
-    {
1196
-        return $GLOBALS['BE_USER'];
1197
-    }
1198
-
1199
-    /**
1200
-     * Tell whether a Backend User is logged in.
1201
-     *
1202
-     * @return bool
1203
-     */
1204
-    protected function isBackendUserLogged()
1205
-    {
1206
-        return is_object($GLOBALS['BE_USER']);
1207
-    }
1208
-
1209
-    /**
1210
-     * @return PageRepository
1211
-     */
1212
-    protected function getPageRepository()
1213
-    {
1214
-        if (!$this->pageRepository instanceof PageRepository) {
1215
-            if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
1216
-                $this->pageRepository = $GLOBALS['TSFE']->sys_page;
1217
-            } else {
1218
-                $this->pageRepository = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
1219
-            }
1220
-        }
1221
-
1222
-        return $this->pageRepository;
1223
-    }
1224
-
1225
-    /**
1226
-     * @return \Fab\Vidi\Resolver\FieldPathResolver
1227
-     */
1228
-    protected function getFieldPathResolver()
1229
-    {
1230
-        return GeneralUtility::makeInstance('Fab\Vidi\Resolver\FieldPathResolver');
1231
-    }
1232
-
1233
-    /**
1234
-     * Checks if there are SQL errors in the last query, and if yes, throw an exception.
1235
-     *
1236
-     * @return void
1237
-     * @param string $sql The SQL statement
1238
-     * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException
1239
-     */
1240
-    protected function checkSqlErrors($sql = '')
1241
-    {
1242
-        $error = $this->databaseHandle->sql_error();
1243
-        if ($error !== '') {
1244
-            $error .= $sql ? ': ' . $sql : '';
1245
-            throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException($error, 1247602160);
1246
-        }
1247
-    }
41
+	const OPERATOR_EQUAL_TO_NULL = 'operatorEqualToNull';
42
+	const OPERATOR_NOT_EQUAL_TO_NULL = 'operatorNotEqualToNull';
43
+
44
+	/**
45
+	 * The TYPO3 database object
46
+	 *
47
+	 * @var \TYPO3\CMS\Core\Database\DatabaseConnection
48
+	 */
49
+	protected $databaseHandle;
50
+
51
+	/**
52
+	 * The TYPO3 page repository. Used for language and workspace overlay
53
+	 *
54
+	 * @var PageRepository
55
+	 */
56
+	protected $pageRepository;
57
+
58
+	/**
59
+	 * A first-level TypoScript configuration cache
60
+	 *
61
+	 * @var array
62
+	 */
63
+	protected $pageTSConfigCache = array();
64
+
65
+	/**
66
+	 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
67
+	 * @inject
68
+	 */
69
+	protected $configurationManager;
70
+
71
+	/**
72
+	 * @var \TYPO3\CMS\Extbase\Service\CacheService
73
+	 * @inject
74
+	 */
75
+	protected $cacheService;
76
+
77
+	/**
78
+	 * @var \TYPO3\CMS\Core\Cache\CacheManager
79
+	 * @inject
80
+	 */
81
+	protected $cacheManager;
82
+
83
+	/**
84
+	 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
85
+	 */
86
+	protected $tableColumnCache;
87
+
88
+	/**
89
+	 * @var \TYPO3\CMS\Extbase\Service\EnvironmentService
90
+	 * @inject
91
+	 */
92
+	protected $environmentService;
93
+
94
+	/**
95
+	 * @var \Fab\Vidi\Persistence\Query
96
+	 */
97
+	protected $query;
98
+
99
+	/**
100
+	 * Store some info related to table name and its aliases.
101
+	 *
102
+	 * @var array
103
+	 */
104
+	protected $tableNameAliases = array(
105
+		'aliases' => array(),
106
+		'aliasIncrement' => array(),
107
+	);
108
+
109
+	/**
110
+	 * Use to store the current foreign table name alias.
111
+	 *
112
+	 * @var string
113
+	 */
114
+	protected $currentChildTableNameAlias = '';
115
+
116
+	/**
117
+	 * The default object type being returned.
118
+	 *
119
+	 * @var string
120
+	 */
121
+	protected $objectType = 'Fab\Vidi\Domain\Model\Content';
122
+
123
+	/**
124
+	 * Constructor. takes the database handle from $GLOBALS['TYPO3_DB']
125
+	 */
126
+	public function __construct(QueryInterface $query)
127
+	{
128
+		$this->query = $query;
129
+		$this->databaseHandle = $GLOBALS['TYPO3_DB'];
130
+	}
131
+
132
+	/**
133
+	 * Lifecycle method
134
+	 *
135
+	 * @return void
136
+	 */
137
+	public function initializeObject()
138
+	{
139
+		$this->tableColumnCache = $this->cacheManager->getCache('extbase_typo3dbbackend_tablecolumns');
140
+	}
141
+
142
+	/**
143
+	 * @param array $identifier
144
+	 * @return string
145
+	 */
146
+	protected function parseIdentifier(array $identifier)
147
+	{
148
+		$fieldNames = array_keys($identifier);
149
+		$suffixedFieldNames = array();
150
+		foreach ($fieldNames as $fieldName) {
151
+			$suffixedFieldNames[] = $fieldName . '=?';
152
+		}
153
+		return implode(' AND ', $suffixedFieldNames);
154
+	}
155
+
156
+	/**
157
+	 * Returns the result of the query
158
+	 */
159
+	public function fetchResult()
160
+	{
161
+
162
+		$parameters = array();
163
+		$statementParts = $this->parseQuery($this->query, $parameters);
164
+		$statementParts = $this->processStatementStructureForRecursiveMMRelation($statementParts); // Mmm... check if that is the right way of doing that.
165
+
166
+		$sql = $this->buildQuery($statementParts);
167
+		$tableName = '';
168
+		if (is_array($statementParts) && !empty($statementParts['tables'][0])) {
169
+			$tableName = $statementParts['tables'][0];
170
+		}
171
+		$this->replacePlaceholders($sql, $parameters, $tableName);
172
+		#print $sql; exit(); // @debug
173
+
174
+		$result = $this->databaseHandle->sql_query($sql);
175
+		$this->checkSqlErrors($sql);
176
+		$rows = $this->getRowsFromResult($result);
177
+		$this->databaseHandle->sql_free_result($result);
178
+
179
+		return $rows;
180
+	}
181
+
182
+	/**
183
+	 * Returns the number of tuples matching the query.
184
+	 *
185
+	 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException
186
+	 * @return int The number of matching tuples
187
+	 */
188
+	public function countResult()
189
+	{
190
+
191
+		$parameters = array();
192
+		$statementParts = $this->parseQuery($this->query, $parameters);
193
+		$statementParts = $this->processStatementStructureForRecursiveMMRelation($statementParts); // Mmm... check if that is the right way of doing that.
194
+		// Reset $statementParts for valid table return
195
+		reset($statementParts);
196
+
197
+		// if limit is set, we need to count the rows "manually" as COUNT(*) ignores LIMIT constraints
198
+		if (!empty($statementParts['limit'])) {
199
+			$statement = $this->buildQuery($statementParts);
200
+			$this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
201
+			#print $statement; exit(); // @debug
202
+			$result = $this->databaseHandle->sql_query($statement);
203
+			$this->checkSqlErrors($statement);
204
+			$count = $this->databaseHandle->sql_num_rows($result);
205
+		} else {
206
+			$statementParts['fields'] = array('COUNT(*)');
207
+			// having orderings without grouping is not compatible with non-MySQL DBMS
208
+			$statementParts['orderings'] = array();
209
+			if (isset($statementParts['keywords']['distinct'])) {
210
+				unset($statementParts['keywords']['distinct']);
211
+				$distinctField = $this->query->getDistinct() ? $this->query->getDistinct() : 'uid';
212
+				$statementParts['fields'] = array('COUNT(DISTINCT ' . reset($statementParts['tables']) . '.' . $distinctField . ')');
213
+			}
214
+
215
+			$statement = $this->buildQuery($statementParts);
216
+			$this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
217
+
218
+			#print $statement; exit(); // @debug
219
+			$result = $this->databaseHandle->sql_query($statement);
220
+			$this->checkSqlErrors($statement);
221
+			$count = 0;
222
+			if ($result) {
223
+				$row = $this->databaseHandle->sql_fetch_assoc($result);
224
+				$count = current($row);
225
+			}
226
+		}
227
+		$this->databaseHandle->sql_free_result($result);
228
+		return (int)$count;
229
+	}
230
+
231
+	/**
232
+	 * Parses the query and returns the SQL statement parts.
233
+	 *
234
+	 * @param QueryInterface $query The query
235
+	 * @param array &$parameters
236
+	 * @return array The SQL statement parts
237
+	 */
238
+	public function parseQuery(QueryInterface $query, array &$parameters)
239
+	{
240
+		$statementParts = array();
241
+		$statementParts['keywords'] = array();
242
+		$statementParts['tables'] = array();
243
+		$statementParts['unions'] = array();
244
+		$statementParts['fields'] = array();
245
+		$statementParts['where'] = array();
246
+		$statementParts['additionalWhereClause'] = array();
247
+		$statementParts['orderings'] = array();
248
+		$statementParts['limit'] = array();
249
+		$source = $query->getSource();
250
+		$this->parseSource($source, $statementParts);
251
+		$this->parseConstraint($query->getConstraint(), $source, $statementParts, $parameters);
252
+		$this->parseOrderings($query->getOrderings(), $source, $statementParts);
253
+		$this->parseLimitAndOffset($query->getLimit(), $query->getOffset(), $statementParts);
254
+		$tableNames = array_unique(array_keys($statementParts['tables'] + $statementParts['unions']));
255
+		foreach ($tableNames as $tableNameOrAlias) {
256
+			if (is_string($tableNameOrAlias) && strlen($tableNameOrAlias) > 0) {
257
+				$this->addAdditionalWhereClause($query->getQuerySettings(), $tableNameOrAlias, $statementParts);
258
+			}
259
+		}
260
+
261
+		return $statementParts;
262
+	}
263
+
264
+	/**
265
+	 * Fiddle with the statement structure to handle recursive MM relations.
266
+	 * For the recursive MM query to work, we must invert some values.
267
+	 * Let see if that is the best way of doing that...
268
+	 *
269
+	 * @param array $statementParts
270
+	 * @return array
271
+	 */
272
+	public function processStatementStructureForRecursiveMMRelation(array $statementParts)
273
+	{
274
+
275
+		if ($this->hasRecursiveMMRelation()) {
276
+			$tableName = $this->query->getType();
277
+
278
+			// In order the MM query to work for a recursive MM query, we must invert some values.
279
+			// tx_domain_model_foo0 (the alias) <--> tx_domain_model_foo (the origin table name)
280
+			$values = array();
281
+			foreach ($statementParts['fields'] as $key => $value) {
282
+				$values[$key] = str_replace($tableName, $tableName . '0', $value);
283
+			}
284
+			$statementParts['fields'] = $values;
285
+
286
+			// Same comment as above.
287
+			$values = array();
288
+			foreach ($statementParts['where'] as $key => $value) {
289
+				$values[$key] = str_replace($tableName . '0', $tableName, $value);
290
+			}
291
+			$statementParts['where'] = $values;
292
+
293
+			// We must be more restrictive by transforming the "left" union by "inner"
294
+			$values = array();
295
+			foreach ($statementParts['unions'] as $key => $value) {
296
+				$values[$key] = str_replace('LEFT JOIN', 'INNER JOIN', $value);
297
+			}
298
+			$statementParts['unions'] = $values;
299
+		}
300
+
301
+		return $statementParts;
302
+	}
303
+
304
+	/**
305
+	 * Tell whether there is a recursive MM relation.
306
+	 *
307
+	 * @return bool
308
+	 */
309
+	public function hasRecursiveMMRelation()
310
+	{
311
+		return isset($this->tableNameAliases['aliasIncrement'][$this->query->getType()]);
312
+
313
+	}
314
+
315
+	/**
316
+	 * Returns the statement, ready to be executed.
317
+	 *
318
+	 * @param array $statementParts The SQL statement parts
319
+	 * @return string The SQL statement
320
+	 */
321
+	public function buildQuery(array $statementParts)
322
+	{
323
+
324
+		// Add more statement to the UNION part.
325
+		if (!empty($statementParts['unions'])) {
326
+			foreach ($statementParts['unions'] as $tableName => $unionPart) {
327
+				if (!empty($statementParts['additionalWhereClause'][$tableName])) {
328
+					$statementParts['unions'][$tableName] .= ' AND ' . implode(' AND ', $statementParts['additionalWhereClause'][$tableName]);
329
+				}
330
+			}
331
+		}
332
+
333
+		$statement = 'SELECT ' . implode(' ', $statementParts['keywords']) . ' ' . implode(',', $statementParts['fields']) . ' FROM ' . implode(' ', $statementParts['tables']) . ' ' . implode(' ', $statementParts['unions']);
334
+		if (!empty($statementParts['where'])) {
335
+			$statement .= ' WHERE ' . implode('', $statementParts['where']);
336
+			if (!empty($statementParts['additionalWhereClause'][$this->query->getType()])) {
337
+				$statement .= ' AND ' . implode(' AND ', $statementParts['additionalWhereClause'][$this->query->getType()]);
338
+			}
339
+		} elseif (!empty($statementParts['additionalWhereClause'])) {
340
+			$statement .= ' WHERE ' . implode(' AND ', $statementParts['additionalWhereClause'][$this->query->getType()]);
341
+		}
342
+		if (!empty($statementParts['orderings'])) {
343
+			$statement .= ' ORDER BY ' . implode(', ', $statementParts['orderings']);
344
+		}
345
+		if (!empty($statementParts['limit'])) {
346
+			$statement .= ' LIMIT ' . $statementParts['limit'];
347
+		}
348
+
349
+		return $statement;
350
+	}
351
+
352
+	/**
353
+	 * Transforms a Query Source into SQL and parameter arrays
354
+	 *
355
+	 * @param SourceInterface $source The source
356
+	 * @param array &$sql
357
+	 * @return void
358
+	 */
359
+	protected function parseSource(SourceInterface $source, array &$sql)
360
+	{
361
+		if ($source instanceof SelectorInterface) {
362
+			$tableName = $source->getNodeTypeName();
363
+			$sql['fields'][$tableName] = $tableName . '.*';
364
+			$sql['tables'][$tableName] = $tableName;
365
+			if ($this->query->getDistinct()) {
366
+				$sql['fields'][$tableName] = $tableName . '.' . $this->query->getDistinct();
367
+				$sql['keywords']['distinct'] = 'DISTINCT';
368
+			}
369
+		} elseif ($source instanceof JoinInterface) {
370
+			$this->parseJoin($source, $sql);
371
+		}
372
+	}
373
+
374
+	/**
375
+	 * Transforms a Join into SQL and parameter arrays
376
+	 *
377
+	 * @param JoinInterface $join The join
378
+	 * @param array &$sql The query parts
379
+	 * @return void
380
+	 */
381
+	protected function parseJoin(JoinInterface $join, array &$sql)
382
+	{
383
+		$leftSource = $join->getLeft();
384
+		$leftTableName = $leftSource->getSelectorName();
385
+		// $sql['fields'][$leftTableName] = $leftTableName . '.*';
386
+		$rightSource = $join->getRight();
387
+		if ($rightSource instanceof JoinInterface) {
388
+			$rightTableName = $rightSource->getLeft()->getSelectorName();
389
+		} else {
390
+			$rightTableName = $rightSource->getSelectorName();
391
+			$sql['fields'][$leftTableName] = $rightTableName . '.*';
392
+		}
393
+		$sql['tables'][$leftTableName] = $leftTableName;
394
+		$sql['unions'][$rightTableName] = 'LEFT JOIN ' . $rightTableName;
395
+		$joinCondition = $join->getJoinCondition();
396
+		if ($joinCondition instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\EquiJoinCondition) {
397
+			$column1Name = $joinCondition->getProperty1Name();
398
+			$column2Name = $joinCondition->getProperty2Name();
399
+			$sql['unions'][$rightTableName] .= ' ON ' . $joinCondition->getSelector1Name() . '.' . $column1Name . ' = ' . $joinCondition->getSelector2Name() . '.' . $column2Name;
400
+		}
401
+		if ($rightSource instanceof JoinInterface) {
402
+			$this->parseJoin($rightSource, $sql);
403
+		}
404
+	}
405
+
406
+	/**
407
+	 * Transforms a constraint into SQL and parameter arrays
408
+	 *
409
+	 * @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint The constraint
410
+	 * @param SourceInterface $source The source
411
+	 * @param array &$sql The query parts
412
+	 * @param array &$parameters The parameters that will replace the markers
413
+	 * @return void
414
+	 */
415
+	protected function parseConstraint(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint = NULL, SourceInterface $source, array &$sql, array &$parameters)
416
+	{
417
+		if ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface) {
418
+			$sql['where'][] = '(';
419
+			$this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
420
+			$sql['where'][] = ' AND ';
421
+			$this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
422
+			$sql['where'][] = ')';
423
+		} elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface) {
424
+			$sql['where'][] = '(';
425
+			$this->parseConstraint($constraint->getConstraint1(), $source, $sql, $parameters);
426
+			$sql['where'][] = ' OR ';
427
+			$this->parseConstraint($constraint->getConstraint2(), $source, $sql, $parameters);
428
+			$sql['where'][] = ')';
429
+		} elseif ($constraint instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface) {
430
+			$sql['where'][] = 'NOT (';
431
+			$this->parseConstraint($constraint->getConstraint(), $source, $sql, $parameters);
432
+			$sql['where'][] = ')';
433
+		} elseif ($constraint instanceof ComparisonInterface) {
434
+			$this->parseComparison($constraint, $source, $sql, $parameters);
435
+		}
436
+	}
437
+
438
+	/**
439
+	 * Parse a Comparison into SQL and parameter arrays.
440
+	 *
441
+	 * @param ComparisonInterface $comparison The comparison to parse
442
+	 * @param SourceInterface $source The source
443
+	 * @param array &$sql SQL query parts to add to
444
+	 * @param array &$parameters Parameters to bind to the SQL
445
+	 * @throws Exception\RepositoryException
446
+	 * @return void
447
+	 */
448
+	protected function parseComparison(ComparisonInterface $comparison, SourceInterface $source, array &$sql, array &$parameters)
449
+	{
450
+		$operand1 = $comparison->getOperand1();
451
+		$operator = $comparison->getOperator();
452
+		$operand2 = $comparison->getOperand2();
453
+		if ($operator === QueryInterface::OPERATOR_IN) {
454
+			$items = array();
455
+			$hasValue = FALSE;
456
+			foreach ($operand2 as $value) {
457
+				$value = $this->getPlainValue($value);
458
+				if ($value !== NULL) {
459
+					$items[] = $value;
460
+					$hasValue = TRUE;
461
+				}
462
+			}
463
+			if ($hasValue === FALSE) {
464
+				$sql['where'][] = '1<>1';
465
+			} else {
466
+				$this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters, NULL);
467
+				$parameters[] = $items;
468
+			}
469
+		} elseif ($operator === QueryInterface::OPERATOR_CONTAINS) {
470
+			if ($operand2 === NULL) {
471
+				$sql['where'][] = '1<>1';
472
+			} else {
473
+				throw new \Exception('Not implemented! Contact extension author.', 1412931227);
474
+				# @todo re-implement me if necessary.
475
+				#$tableName = $this->query->getType();
476
+				#$propertyName = $operand1->getPropertyName();
477
+				#while (strpos($propertyName, '.') !== FALSE) {
478
+				#	$this->addUnionStatement($tableName, $propertyName, $sql);
479
+				#}
480
+				#$columnName = $propertyName;
481
+				#$columnMap = $propertyName;
482
+				#$typeOfRelation = $columnMap instanceof ColumnMap ? $columnMap->getTypeOfRelation() : NULL;
483
+				#if ($typeOfRelation === ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
484
+				#	$relationTableName = $columnMap->getRelationTableName();
485
+				#	$sql['where'][] = $tableName . '.uid IN (SELECT ' . $columnMap->getParentKeyFieldName() . ' FROM ' . $relationTableName . ' WHERE ' . $columnMap->getChildKeyFieldName() . '=?)';
486
+				#	$parameters[] = intval($this->getPlainValue($operand2));
487
+				#} elseif ($typeOfRelation === ColumnMap::RELATION_HAS_MANY) {
488
+				#	$parentKeyFieldName = $columnMap->getParentKeyFieldName();
489
+				#	if (isset($parentKeyFieldName)) {
490
+				#		$childTableName = $columnMap->getChildTableName();
491
+				#		$sql['where'][] = $tableName . '.uid=(SELECT ' . $childTableName . '.' . $parentKeyFieldName . ' FROM ' . $childTableName . ' WHERE ' . $childTableName . '.uid=?)';
492
+				#		$parameters[] = intval($this->getPlainValue($operand2));
493
+				#	} else {
494
+				#		$sql['where'][] = 'FIND_IN_SET(?,' . $tableName . '.' . $columnName . ')';
495
+				#		$parameters[] = intval($this->getPlainValue($operand2));
496
+				#	}
497
+				#} else {
498
+				#	throw new Exception\RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
499
+				#}
500
+			}
501
+		} else {
502
+			if ($operand2 === NULL) {
503
+				if ($operator === QueryInterface::OPERATOR_EQUAL_TO) {
504
+					$operator = self::OPERATOR_EQUAL_TO_NULL;
505
+				} elseif ($operator === QueryInterface::OPERATOR_NOT_EQUAL_TO) {
506
+					$operator = self::OPERATOR_NOT_EQUAL_TO_NULL;
507
+				}
508
+			}
509
+			$this->parseDynamicOperand($operand1, $operator, $source, $sql, $parameters);
510
+			$parameters[] = $this->getPlainValue($operand2);
511
+		}
512
+	}
513
+
514
+	/**
515
+	 * Returns a plain value, i.e. objects are flattened out if possible.
516
+	 *
517
+	 * @param mixed $input
518
+	 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException
519
+	 * @return mixed
520
+	 */
521
+	protected function getPlainValue($input)
522
+	{
523
+		if (is_array($input)) {
524
+			throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An array could not be converted to a plain value.', 1274799932);
525
+		}
526
+		if ($input instanceof \DateTime) {
527
+			return $input->format('U');
528
+		} elseif (is_object($input)) {
529
+			if ($input instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) {
530
+				$realInput = $input->_loadRealInstance();
531
+			} else {
532
+				$realInput = $input;
533
+			}
534
+			if ($realInput instanceof \TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface) {
535
+				return $realInput->getUid();
536
+			} else {
537
+				throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('An object of class "' . get_class($realInput) . '" could not be converted to a plain value.', 1274799934);
538
+			}
539
+		} elseif (is_bool($input)) {
540
+			return $input === TRUE ? 1 : 0;
541
+		} else {
542
+			return $input;
543
+		}
544
+	}
545
+
546
+	/**
547
+	 * Parse a DynamicOperand into SQL and parameter arrays.
548
+	 *
549
+	 * @param DynamicOperandInterface $operand
550
+	 * @param string $operator One of the JCR_OPERATOR_* constants
551
+	 * @param SourceInterface $source The source
552
+	 * @param array &$sql The query parts
553
+	 * @param array &$parameters The parameters that will replace the markers
554
+	 * @param string $valueFunction an optional SQL function to apply to the operand value
555
+	 * @return void
556
+	 */
557
+	protected function parseDynamicOperand(DynamicOperandInterface $operand, $operator, SourceInterface $source, array &$sql, array &$parameters, $valueFunction = NULL)
558
+	{
559
+		if ($operand instanceof LowerCaseInterface) {
560
+			$this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'LOWER');
561
+		} elseif ($operand instanceof UpperCaseInterface) {
562
+			$this->parseDynamicOperand($operand->getOperand(), $operator, $source, $sql, $parameters, 'UPPER');
563
+		} elseif ($operand instanceof PropertyValueInterface) {
564
+			$propertyName = $operand->getPropertyName();
565
+
566
+			// Reset value.
567
+			$this->currentChildTableNameAlias = '';
568
+
569
+			if ($source instanceof SelectorInterface) {
570
+				$tableName = $this->query->getType();
571
+				while (strpos($propertyName, '.') !== FALSE) {
572
+					$this->addUnionStatement($tableName, $propertyName, $sql);
573
+				}
574
+			} elseif ($source instanceof JoinInterface) {
575
+				$tableName = $source->getJoinCondition()->getSelector1Name();
576
+			}
577
+
578
+			$columnName = $propertyName;
579
+			$operator = $this->resolveOperator($operator);
580
+			$constraintSQL = '';
581
+			if ($valueFunction === NULL) {
582
+				$constraintSQL .= (!empty($tableName) ? $tableName . '.' : '') . $columnName . ' ' . $operator . ' ?';
583
+			} else {
584
+				$constraintSQL .= $valueFunction . '(' . (!empty($tableName) ? $tableName . '.' : '') . $columnName . ') ' . $operator . ' ?';
585
+			}
586
+
587
+			if (isset($tableName) && !empty($this->currentChildTableNameAlias)) {
588
+				$constraintSQL = $this->replaceTableNameByAlias($tableName, $this->currentChildTableNameAlias, $constraintSQL);
589
+			}
590
+			$sql['where'][] = $constraintSQL;
591
+		}
592
+	}
593
+
594
+	/**
595
+	 * @param string &$tableName
596
+	 * @param array &$propertyPath
597
+	 * @param array &$sql
598
+	 * @throws Exception
599
+	 * @throws Exception\InvalidRelationConfigurationException
600
+	 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException
601
+	 */
602
+	protected function addUnionStatement(&$tableName, &$propertyPath, array &$sql)
603
+	{
604
+
605
+		$table = Tca::table($tableName);
606
+
607
+		$explodedPropertyPath = explode('.', $propertyPath, 2);
608
+		$fieldName = $explodedPropertyPath[0];
609
+
610
+		// Field of type "group" are special because property path must contain the table name
611
+		// to determine the relation type. Example for sys_category, property path will look like "items.sys_file"
612
+		if ($table->field($fieldName)->isGroup()) {
613
+			$parts = explode('.', $propertyPath, 3);
614
+			$explodedPropertyPath[0] = $parts[0] . '.' . $parts[1];
615
+			$explodedPropertyPath[1] = $parts[2];
616
+			$fieldName = $explodedPropertyPath[0];
617
+		}
618
+
619
+		$parentKeyFieldName = $table->field($fieldName)->getForeignField();
620
+		$childTableName = $table->field($fieldName)->getForeignTable();
621
+
622
+		if ($childTableName === NULL) {
623
+			throw new Exception\InvalidRelationConfigurationException('The relation information for property "' . $fieldName . '" of class "' . $tableName . '" is missing.', 1353170925);
624
+		}
625
+
626
+		if ($table->field($fieldName)->hasOne()) { // includes relation "one-to-one" and "many-to-one"
627
+			// sometimes the opposite relation is not defined. We don't want to force this config for backward compatibility reasons.
628
+			// $parentKeyFieldName === NULL does the trick somehow. Before condition was if (isset($parentKeyFieldName))
629
+			if ($table->field($fieldName)->hasRelationManyToOne() || $parentKeyFieldName === NULL) {
630
+				$sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.' . $fieldName . '=' . $childTableName . '.uid';
631
+			} else {
632
+				$sql['unions'][$childTableName] = 'LEFT JOIN ' . $childTableName . ' ON ' . $tableName . '.uid=' . $childTableName . '.' . $parentKeyFieldName;
633
+			}
634
+		} elseif ($table->field($fieldName)->hasRelationManyToMany()) {
635
+			$relationTableName = $table->field($fieldName)->getManyToManyTable();
636
+
637
+			$parentKeyFieldName = $table->field($fieldName)->isOppositeRelation() ? 'uid_foreign' : 'uid_local';
638
+			$childKeyFieldName = !$table->field($fieldName)->isOppositeRelation() ? 'uid_foreign' : 'uid_local';
639
+
640
+			// MM table e.g sys_category_record_mm
641
+			$relationTableNameAlias = $this->generateAlias($relationTableName);
642
+			$join = sprintf(
643
+				'LEFT JOIN %s AS %s ON %s.uid=%s.%s', $relationTableName,
644
+				$relationTableNameAlias,
645
+				$tableName,
646
+				$relationTableNameAlias,
647
+				$parentKeyFieldName
648
+			);
649
+			$sql['unions'][$relationTableNameAlias] = $join;
650
+
651
+			// Foreign table e.g sys_category
652
+			$childTableNameAlias = $this->generateAlias($childTableName);
653
+			$this->currentChildTableNameAlias = $childTableNameAlias;
654
+			$join = sprintf(
655
+				'LEFT JOIN %s AS %s ON %s.%s=%s.uid',
656
+				$childTableName,
657
+				$childTableNameAlias,
658
+				$relationTableNameAlias,
659
+				$childKeyFieldName,
660
+				$childTableNameAlias
661
+			);
662
+			$sql['unions'][$childTableNameAlias] = $join;
663
+
664
+			// Find a possible table name for a MM condition.
665
+			$tableNameCondition = $table->field($fieldName)->getAdditionalTableNameCondition();
666
+			if ($tableNameCondition) {
667
+
668
+				// If we can find a source file name,  we can then retrieve more MM conditions from the TCA such as a field name.
669
+				$sourceFileName = $this->query->getSourceFieldName();
670
+				if (empty($sourceFileName)) {
671
+					$additionalMMConditions = array(
672
+						'tablenames' => $tableNameCondition,
673
+					);
674
+				} else {
675
+					$additionalMMConditions = Tca::table($tableNameCondition)->field($sourceFileName)->getAdditionalMMCondition();
676
+				}
677
+
678
+				foreach ($additionalMMConditions as $additionalFieldName => $additionalMMCondition) {
679
+					$additionalJoin = sprintf(' AND %s.%s = "%s"', $relationTableNameAlias, $additionalFieldName, $additionalMMCondition);
680
+					$sql['unions'][$relationTableNameAlias] .= $additionalJoin;
681
+
682
+					$additionalJoin = sprintf(' AND %s.%s = "%s"', $relationTableNameAlias, $additionalFieldName, $additionalMMCondition);
683
+					$sql['unions'][$childTableNameAlias] .= $additionalJoin;
684
+				}
685
+
686
+			}
687
+
688
+
689
+		} elseif ($table->field($fieldName)->hasMany()) { // includes relations "many-to-one" and "csv" relations
690
+			$childTableNameAlias = $this->generateAlias($childTableName);
691
+			$this->currentChildTableNameAlias = $childTableNameAlias;
692
+
693
+			if (isset($parentKeyFieldName)) {
694
+				$join = sprintf(
695
+					'LEFT JOIN %s AS %s ON %s.uid=%s.%s',
696
+					$childTableName,
697
+					$childTableNameAlias,
698
+					$tableName,
699
+					$childTableNameAlias,
700
+					$parentKeyFieldName
701
+				);
702
+				$sql['unions'][$childTableNameAlias] = $join;
703
+			} else {
704
+				$join = sprintf(
705
+					'LEFT JOIN %s AS %s ON (FIND_IN_SET(%s.uid, %s.%s))',
706
+					$childTableName,
707
+					$childTableNameAlias,
708
+					$childTableNameAlias,
709
+					$tableName,
710
+					$fieldName
711
+				);
712
+				$sql['unions'][$childTableNameAlias] = $join;
713
+			}
714
+		} else {
715
+			throw new Exception('Could not determine type of relation.', 1252502725);
716
+		}
717
+
718
+		// TODO check if there is another solution for this
719
+		$sql['keywords']['distinct'] = 'DISTINCT';
720
+		$propertyPath = $explodedPropertyPath[1];
721
+		$tableName = $childTableName;
722
+	}
723
+
724
+	/**
725
+	 * Returns the SQL operator for the given JCR operator type.
726
+	 *
727
+	 * @param string $operator One of the JCR_OPERATOR_* constants
728
+	 * @throws Exception
729
+	 * @return string an SQL operator
730
+	 */
731
+	protected function resolveOperator($operator)
732
+	{
733
+		switch ($operator) {
734
+			case self::OPERATOR_EQUAL_TO_NULL:
735
+				$operator = 'IS';
736
+				break;
737
+			case self::OPERATOR_NOT_EQUAL_TO_NULL:
738
+				$operator = 'IS NOT';
739
+				break;
740
+			case QueryInterface::OPERATOR_IN:
741
+				$operator = 'IN';
742
+				break;
743
+			case QueryInterface::OPERATOR_EQUAL_TO:
744
+				$operator = '=';
745
+				break;
746
+			case QueryInterface::OPERATOR_NOT_EQUAL_TO:
747
+				$operator = '!=';
748
+				break;
749
+			case QueryInterface::OPERATOR_LESS_THAN:
750
+				$operator = '<';
751
+				break;
752
+			case QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
753
+				$operator = '<=';
754
+				break;
755
+			case QueryInterface::OPERATOR_GREATER_THAN:
756
+				$operator = '>';
757
+				break;
758
+			case QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
759
+				$operator = '>=';
760
+				break;
761
+			case QueryInterface::OPERATOR_LIKE:
762
+				$operator = 'LIKE';
763
+				break;
764
+			default:
765
+				throw new Exception('Unsupported operator encountered.', 1242816073);
766
+		}
767
+		return $operator;
768
+	}
769
+
770
+	/**
771
+	 * Replace query placeholders in a query part by the given
772
+	 * parameters.
773
+	 *
774
+	 * @param string &$sqlString The query part with placeholders
775
+	 * @param array $parameters The parameters
776
+	 * @param string $tableName
777
+	 *
778
+	 * @throws Exception
779
+	 */
780
+	protected function replacePlaceholders(&$sqlString, array $parameters, $tableName = 'foo')
781
+	{
782
+		// TODO profile this method again
783
+		if (substr_count($sqlString, '?') !== count($parameters)) {
784
+			throw new Exception('The number of question marks to replace must be equal to the number of parameters.', 1242816074);
785
+		}
786
+		$offset = 0;
787
+		foreach ($parameters as $parameter) {
788
+			$markPosition = strpos($sqlString, '?', $offset);
789
+			if ($markPosition !== FALSE) {
790
+				if ($parameter === NULL) {
791
+					$parameter = 'NULL';
792
+				} elseif (is_array($parameter) || $parameter instanceof \ArrayAccess || $parameter instanceof \Traversable) {
793
+					$items = array();
794
+					foreach ($parameter as $item) {
795
+						$items[] = $this->databaseHandle->fullQuoteStr($item, $tableName);
796
+					}
797
+					$parameter = '(' . implode(',', $items) . ')';
798
+				} else {
799
+					$parameter = $this->databaseHandle->fullQuoteStr($parameter, $tableName);
800
+				}
801
+				$sqlString = substr($sqlString, 0, $markPosition) . $parameter . substr($sqlString, ($markPosition + 1));
802
+			}
803
+			$offset = $markPosition + strlen($parameter);
804
+		}
805
+	}
806
+
807
+	/**
808
+	 * Adds additional WHERE statements according to the query settings.
809
+	 *
810
+	 * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
811
+	 * @param string $tableNameOrAlias The table name to add the additional where clause for
812
+	 * @param array &$statementParts
813
+	 * @return void
814
+	 */
815
+	protected function addAdditionalWhereClause(QuerySettingsInterface $querySettings, $tableNameOrAlias, &$statementParts)
816
+	{
817
+		$this->addVisibilityConstraintStatement($querySettings, $tableNameOrAlias, $statementParts);
818
+		if ($querySettings->getRespectSysLanguage()) {
819
+			$this->addSysLanguageStatement($tableNameOrAlias, $statementParts, $querySettings);
820
+		}
821
+		if ($querySettings->getRespectStoragePage()) {
822
+			$this->addPageIdStatement($tableNameOrAlias, $statementParts, $querySettings->getStoragePageIds());
823
+		}
824
+	}
825
+
826
+	/**
827
+	 * Adds enableFields and deletedClause to the query if necessary
828
+	 *
829
+	 * @param QuerySettingsInterface $querySettings
830
+	 * @param string $tableNameOrAlias The database table name
831
+	 * @param array &$statementParts The query parts
832
+	 * @return void
833
+	 */
834
+	protected function addVisibilityConstraintStatement(QuerySettingsInterface $querySettings, $tableNameOrAlias, array &$statementParts)
835
+	{
836
+		$statement = '';
837
+		$tableName = $this->resolveTableNameAlias($tableNameOrAlias);
838
+		if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
839
+			$ignoreEnableFields = $querySettings->getIgnoreEnableFields();
840
+			$enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
841
+			$includeDeleted = $querySettings->getIncludeDeleted();
842
+			if ($this->environmentService->isEnvironmentInFrontendMode()) {
843
+				$statement .= $this->getFrontendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
844
+			} else {
845
+				// TYPO3_MODE === 'BE'
846
+				$statement .= $this->getBackendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $includeDeleted);
847
+			}
848
+
849
+			// Remove the prefixing "AND" if any.
850
+			if (!empty($statement)) {
851
+				$statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
852
+				$statementParts['additionalWhereClause'][$tableNameOrAlias][] = $statement;
853
+			}
854
+		}
855
+	}
856
+
857
+	/**
858
+	 * Returns constraint statement for frontend context
859
+	 *
860
+	 * @param string $tableNameOrAlias
861
+	 * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
862
+	 * @param array $enableFieldsToBeIgnored If $ignoreEnableFields is true, this array specifies enable fields to be ignored. If it is NULL or an empty array (default) all enable fields are ignored.
863
+	 * @param boolean $includeDeleted A flag indicating whether deleted records should be included
864
+	 * @return string
865
+	 * @throws Exception\InconsistentQuerySettingsException
866
+	 */
867
+	protected function getFrontendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $enableFieldsToBeIgnored = array(), $includeDeleted)
868
+	{
869
+		$statement = '';
870
+		$tableName = $this->resolveTableNameAlias($tableNameOrAlias);
871
+		if ($ignoreEnableFields && !$includeDeleted) {
872
+			if (count($enableFieldsToBeIgnored)) {
873
+				// array_combine() is necessary because of the way \TYPO3\CMS\Frontend\Page\PageRepository::enableFields() is implemented
874
+				$statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
875
+			} else {
876
+				$statement .= $this->getPageRepository()->deleteClause($tableName);
877
+			}
878
+		} elseif (!$ignoreEnableFields && !$includeDeleted) {
879
+			$statement .= $this->getPageRepository()->enableFields($tableName);
880
+		} elseif (!$ignoreEnableFields && $includeDeleted) {
881
+			throw new Exception\InconsistentQuerySettingsException('Query setting "ignoreEnableFields=FALSE" can not be used together with "includeDeleted=TRUE" in frontend context.', 1327678173);
882
+		}
883
+		return $this->replaceTableNameByAlias($tableName, $tableNameOrAlias, $statement);
884
+	}
885
+
886
+	/**
887
+	 * Returns constraint statement for backend context
888
+	 *
889
+	 * @param string $tableNameOrAlias
890
+	 * @param boolean $ignoreEnableFields A flag indicating whether the enable fields should be ignored
891
+	 * @param boolean $includeDeleted A flag indicating whether deleted records should be included
892
+	 * @return string
893
+	 */
894
+	protected function getBackendConstraintStatement($tableNameOrAlias, $ignoreEnableFields, $includeDeleted)
895
+	{
896
+		$tableName = $this->resolveTableNameAlias($tableNameOrAlias);
897
+		$statement = '';
898
+		if (!$ignoreEnableFields) {
899
+			$statement .= BackendUtility::BEenableFields($tableName);
900
+		}
901
+
902
+		// If the table is found to have "workspace" support, add the corresponding fields in the statement.
903
+		if (Tca::table($tableName)->hasWorkspaceSupport()) {
904
+			if ($this->getBackendUser()->workspace === 0) {
905
+				$statement .= ' AND ' . $tableName . '.t3ver_state<=' . new VersionState(VersionState::DEFAULT_STATE);
906
+			} else {
907
+				// Show only records of live and of the current workspace
908
+				// In case we are in a Versioning preview
909
+				$statement .= ' AND (' .
910
+					$tableName . '.t3ver_wsid=0 OR ' .
911
+					$tableName . '.t3ver_wsid=' . (int)$this->getBackendUser()->workspace .
912
+					')';
913
+			}
914
+
915
+			// Check if this segment make sense here or whether it should be in the "if" part when we have workspace = 0
916
+			$statement .= ' AND ' . $tableName . '.pid<>-1';
917
+		}
918
+
919
+		if (!$includeDeleted) {
920
+			$statement .= BackendUtility::deleteClause($tableName);
921
+		}
922
+
923
+		return $this->replaceTableNameByAlias($tableName, $tableNameOrAlias, $statement);
924
+	}
925
+
926
+	/**
927
+	 * Builds the language field statement
928
+	 *
929
+	 * @param string $tableNameOrAlias The database table name
930
+	 * @param array &$statementParts The query parts
931
+	 * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
932
+	 * @throws Exception
933
+	 * @return void
934
+	 */
935
+	protected function addSysLanguageStatement($tableNameOrAlias, array &$statementParts, $querySettings)
936
+	{
937
+
938
+		$tableName = $this->resolveTableNameAlias($tableNameOrAlias);
939
+		if (is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
940
+			if (!empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
941
+				// Select all entries for the current language
942
+				$additionalWhereClause = $tableNameOrAlias . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . ' IN (' . intval($querySettings->getLanguageUid()) . ',-1)';
943
+				// If any language is set -> get those entries which are not translated yet
944
+				// They will be removed by t3lib_page::getRecordOverlay if not matching overlay mode
945
+				if (isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
946
+					&& $querySettings->getLanguageUid() > 0
947
+				) {
948
+					$additionalWhereClause .= ' OR (' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0' .
949
+						' AND ' . $tableName . '.uid NOT IN (SELECT ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] .
950
+						' FROM ' . $tableName .
951
+						' WHERE ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] . '>0' .
952
+						' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '>0';
953
+
954
+					// Add delete clause to ensure all entries are loaded
955
+					if (isset($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
956
+						$additionalWhereClause .= ' AND ' . $tableNameOrAlias . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
957
+					}
958
+					$additionalWhereClause .= '))';
959
+					throw new Exception('Not tested code! It will fail', 1412928284);
960
+				}
961
+				$statementParts['additionalWhereClause'][$tableNameOrAlias][] = '(' . $additionalWhereClause . ')';
962
+			}
963
+		}
964
+	}
965
+
966
+	/**
967
+	 * Builds the page ID checking statement
968
+	 *
969
+	 * @param string $tableNameOrAlias The database table name
970
+	 * @param array &$statementParts The query parts
971
+	 * @param array $storagePageIds list of storage page ids
972
+	 * @throws Exception\InconsistentQuerySettingsException
973
+	 * @return void
974
+	 */
975
+	protected function addPageIdStatement($tableNameOrAlias, array &$statementParts, array $storagePageIds)
976
+	{
977
+
978
+		$tableName = $this->resolveTableNameAlias($tableNameOrAlias);
979
+		$tableColumns = $this->tableColumnCache->get($tableName);
980
+		if ($tableColumns === FALSE) {
981
+			$tableColumns = $this->databaseHandle->admin_get_fields($tableName);
982
+			$this->tableColumnCache->set($tableName, $tableColumns);
983
+		}
984
+		if (is_array($GLOBALS['TCA'][$tableName]['ctrl']) && array_key_exists('pid', $tableColumns)) {
985
+			$rootLevel = (int)$GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'];
986
+			if ($rootLevel) {
987
+				if ($rootLevel === 1) {
988
+					$statementParts['additionalWhereClause'][$tableNameOrAlias][] = $tableNameOrAlias . '.pid = 0';
989
+				}
990
+			} else {
991
+				if (empty($storagePageIds)) {
992
+					throw new Exception\InconsistentQuerySettingsException('Missing storage page ids.', 1365779762);
993
+				}
994
+				$statementParts['additionalWhereClause'][$tableNameOrAlias][] = $tableNameOrAlias . '.pid IN (' . implode(', ', $storagePageIds) . ')';
995
+			}
996
+		}
997
+	}
998
+
999
+	/**
1000
+	 * Transforms orderings into SQL.
1001
+	 *
1002
+	 * @param array $orderings An array of orderings (Tx_Extbase_Persistence_QOM_Ordering)
1003
+	 * @param SourceInterface $source The source
1004
+	 * @param array &$sql The query parts
1005
+	 * @throws Exception\UnsupportedOrderException
1006
+	 * @return void
1007
+	 */
1008
+	protected function parseOrderings(array $orderings, SourceInterface $source, array &$sql)
1009
+	{
1010
+		foreach ($orderings as $fieldNameAndPath => $order) {
1011
+			switch ($order) {
1012
+				case QueryInterface::ORDER_ASCENDING:
1013
+					$order = 'ASC';
1014
+					break;
1015
+				case QueryInterface::ORDER_DESCENDING:
1016
+					$order = 'DESC';
1017
+					break;
1018
+				default:
1019
+					throw new Exception\UnsupportedOrderException('Unsupported order encountered.', 1456845126);
1020
+			}
1021
+
1022
+			$tableName = $this->getFieldPathResolver()->getDataType($fieldNameAndPath, $this->query->getType());
1023
+			$fieldName = $this->getFieldPathResolver()->stripFieldPath($fieldNameAndPath, $tableName);
1024
+			$sql['orderings'][] = sprintf('%s.%s %s', $tableName, $fieldName, $order);
1025
+		}
1026
+	}
1027
+
1028
+	/**
1029
+	 * Transforms limit and offset into SQL
1030
+	 *
1031
+	 * @param int $limit
1032
+	 * @param int $offset
1033
+	 * @param array &$sql
1034
+	 * @return void
1035
+	 */
1036
+	protected function parseLimitAndOffset($limit, $offset, array &$sql)
1037
+	{
1038
+		if ($limit !== NULL && $offset !== NULL) {
1039
+			$sql['limit'] = intval($offset) . ', ' . intval($limit);
1040
+		} elseif ($limit !== NULL) {
1041
+			$sql['limit'] = intval($limit);
1042
+		}
1043
+	}
1044
+
1045
+	/**
1046
+	 * Transforms a Resource from a database query to an array of rows.
1047
+	 *
1048
+	 * @param resource $result The result
1049
+	 * @return array The result as an array of rows (tuples)
1050
+	 */
1051
+	protected function getRowsFromResult($result)
1052
+	{
1053
+		$rows = array();
1054
+		while ($row = $this->databaseHandle->sql_fetch_assoc($result)) {
1055
+			if (is_array($row)) {
1056
+
1057
+				// Get language uid from querySettings.
1058
+				// Ensure the backend handling is not broken (fallback to Get parameter 'L' if needed)
1059
+				$overlaidRow = $this->doLanguageAndWorkspaceOverlay($this->query->getSource(), $row, $this->query->getQuerySettings());
1060
+				$contentObject = GeneralUtility::makeInstance($this->objectType, $this->query->getType(), $overlaidRow);
1061
+				$rows[] = $contentObject;
1062
+			}
1063
+		}
1064
+
1065
+		return $rows;
1066
+	}
1067
+
1068
+	/**
1069
+	 * Performs workspace and language overlay on the given row array. The language and workspace id is automatically
1070
+	 * detected (depending on FE or BE context). You can also explicitly set the language/workspace id.
1071
+	 *
1072
+	 * @param SourceInterface $source The source (selector od join)
1073
+	 * @param array $row
1074
+	 * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
1075
+	 * @return array
1076
+	 */
1077
+	protected function doLanguageAndWorkspaceOverlay(SourceInterface $source, array $row, $querySettings)
1078
+	{
1079
+
1080
+		/** @var SelectorInterface $source */
1081
+		$tableName = $source->getSelectorName();
1082
+
1083
+		$pageRepository = $this->getPageRepository();
1084
+		if (is_object($GLOBALS['TSFE'])) {
1085
+			$languageMode = $GLOBALS['TSFE']->sys_language_mode;
1086
+			if ($this->isBackendUserLogged() && $this->getBackendUser()->workspace !== 0) {
1087
+				$pageRepository->versioningWorkspaceId = $this->getBackendUser()->workspace;
1088
+			}
1089
+		} else {
1090
+			$languageMode = '';
1091
+			$workspaceUid = $this->getBackendUser()->workspace;
1092
+			$pageRepository->versioningWorkspaceId = $workspaceUid;
1093
+			if ($this->getBackendUser()->workspace !== 0) {
1094
+				$pageRepository->versioningPreview = 1;
1095
+			}
1096
+		}
1097
+
1098
+		// If current row is a translation select its parent
1099
+		if (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1100
+			&& isset($GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'])
1101
+		) {
1102
+			if (isset($row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']])
1103
+				&& $row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] > 0
1104
+			) {
1105
+				$row = $this->databaseHandle->exec_SELECTgetSingleRow(
1106
+					$tableName . '.*',
1107
+					$tableName,
1108
+					$tableName . '.uid=' . (int)$row[$GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField']] .
1109
+					' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] . '=0'
1110
+				);
1111
+			}
1112
+		}
1113
+
1114
+		// Retrieve the original uid
1115
+		// @todo It looks for me this code will never be used! "_ORIG_uid" is something from extbase. Adjust me or remove me in 0.4 + 2 version!
1116
+		$pageRepository->versionOL($tableName, $row, TRUE);
1117
+		if ($pageRepository->versioningPreview && isset($row['_ORIG_uid'])) {
1118
+			$row['uid'] = $row['_ORIG_uid'];
1119
+		}
1120
+
1121
+		// Special case for table "pages"
1122
+		if ($tableName == 'pages') {
1123
+			$row = $pageRepository->getPageOverlay($row, $querySettings->getLanguageUid());
1124
+		} elseif (isset($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])
1125
+			&& $GLOBALS['TCA'][$tableName]['ctrl']['languageField'] !== ''
1126
+		) {
1127
+			if (in_array($row[$GLOBALS['TCA'][$tableName]['ctrl']['languageField']], array(-1, 0))) {
1128
+				$overlayMode = $languageMode === 'strict' ? 'hideNonTranslated' : '';
1129
+				$row = $pageRepository->getRecordOverlay($tableName, $row, $querySettings->getLanguageUid(), $overlayMode);
1130
+			}
1131
+		}
1132
+
1133
+		return $row;
1134
+	}
1135
+
1136
+	/**
1137
+	 * Return a resolved table name given a possible table name alias.
1138
+	 *
1139
+	 * @param string $tableNameOrAlias
1140
+	 * @return string
1141
+	 */
1142
+	protected function resolveTableNameAlias($tableNameOrAlias)
1143
+	{
1144
+		$resolvedTableName = $tableNameOrAlias;
1145
+		if (!empty($this->tableNameAliases['aliases'][$tableNameOrAlias])) {
1146
+			$resolvedTableName = $this->tableNameAliases['aliases'][$tableNameOrAlias];
1147
+		}
1148
+		return $resolvedTableName;
1149
+	}
1150
+
1151
+	/**
1152
+	 * Generate a unique table name alias for the given table name.
1153
+	 *
1154
+	 * @param string $tableName
1155
+	 * @return string
1156
+	 */
1157
+	protected function generateAlias($tableName)
1158
+	{
1159
+
1160
+		if (!isset($this->tableNameAliases['aliasIncrement'][$tableName])) {
1161
+			$this->tableNameAliases['aliasIncrement'][$tableName] = 0;
1162
+		}
1163
+
1164
+		$numberOfAliases = $this->tableNameAliases['aliasIncrement'][$tableName];
1165
+		$tableNameAlias = $tableName . $numberOfAliases;
1166
+
1167
+		$this->tableNameAliases['aliasIncrement'][$tableName]++;
1168
+		$this->tableNameAliases['aliases'][$tableNameAlias] = $tableName;
1169
+
1170
+		return $tableNameAlias;
1171
+	}
1172
+
1173
+	/**
1174
+	 * Replace the table names by its table name alias within the given statement.
1175
+	 *
1176
+	 * @param string $tableName
1177
+	 * @param string $tableNameAlias
1178
+	 * @param string $statement
1179
+	 * @return string
1180
+	 */
1181
+	protected function replaceTableNameByAlias($tableName, $tableNameAlias, $statement)
1182
+	{
1183
+		if ($statement && $tableName !== $tableNameAlias) {
1184
+			$statement = str_replace($tableName, $tableNameAlias, $statement);
1185
+		}
1186
+		return $statement;
1187
+	}
1188
+
1189
+	/**
1190
+	 * Returns an instance of the current Backend User.
1191
+	 *
1192
+	 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1193
+	 */
1194
+	protected function getBackendUser()
1195
+	{
1196
+		return $GLOBALS['BE_USER'];
1197
+	}
1198
+
1199
+	/**
1200
+	 * Tell whether a Backend User is logged in.
1201
+	 *
1202
+	 * @return bool
1203
+	 */
1204
+	protected function isBackendUserLogged()
1205
+	{
1206
+		return is_object($GLOBALS['BE_USER']);
1207
+	}
1208
+
1209
+	/**
1210
+	 * @return PageRepository
1211
+	 */
1212
+	protected function getPageRepository()
1213
+	{
1214
+		if (!$this->pageRepository instanceof PageRepository) {
1215
+			if ($this->environmentService->isEnvironmentInFrontendMode() && is_object($GLOBALS['TSFE'])) {
1216
+				$this->pageRepository = $GLOBALS['TSFE']->sys_page;
1217
+			} else {
1218
+				$this->pageRepository = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
1219
+			}
1220
+		}
1221
+
1222
+		return $this->pageRepository;
1223
+	}
1224
+
1225
+	/**
1226
+	 * @return \Fab\Vidi\Resolver\FieldPathResolver
1227
+	 */
1228
+	protected function getFieldPathResolver()
1229
+	{
1230
+		return GeneralUtility::makeInstance('Fab\Vidi\Resolver\FieldPathResolver');
1231
+	}
1232
+
1233
+	/**
1234
+	 * Checks if there are SQL errors in the last query, and if yes, throw an exception.
1235
+	 *
1236
+	 * @return void
1237
+	 * @param string $sql The SQL statement
1238
+	 * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException
1239
+	 */
1240
+	protected function checkSqlErrors($sql = '')
1241
+	{
1242
+		$error = $this->databaseHandle->sql_error();
1243
+		if ($error !== '') {
1244
+			$error .= $sql ? ': ' . $sql : '';
1245
+			throw new \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\SqlErrorException($error, 1247602160);
1246
+		}
1247
+	}
1248 1248
 }
Please login to merge, or discard this patch.